hexsha
stringlengths 40
40
| repo
stringlengths 4
114
| path
stringlengths 6
369
| license
sequence | language
stringclasses 1
value | identifier
stringlengths 1
123
| original_docstring
stringlengths 8
49.2k
| docstring
stringlengths 5
8.63k
| docstring_tokens
sequence | code
stringlengths 25
988k
| code_tokens
sequence | short_docstring
stringlengths 0
6.18k
| short_docstring_tokens
sequence | comment
sequence | parameters
list | docstring_params
dict |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c4656175842ba321214cb7b5077b5a1f22de74c7 | dmccoystephenson/Dans-Plugin-Manager | src/main/java/dansplugins/dpm/commands/StatsCommand.java | [
"MIT"
] | Java | StatsCommand | /**
* @author Daniel McCoy Stephenson
*/ | @author Daniel McCoy Stephenson | [
"@author",
"Daniel",
"McCoy",
"Stephenson"
] | public class StatsCommand extends AbstractPluginCommand {
public StatsCommand() {
super(new ArrayList<>(List.of("stats")), new ArrayList<>(List.of("dpm.stats")));
}
@Override
public boolean execute(CommandSender commandSender) {
commandSender.sendMessage(ChatColor.AQUA + "=== DPM Stats ===");
commandSender.sendMessage(ChatColor.AQUA + "Number of project records: " + EphemeralData.getInstance().getNumProjectRecords());
return true;
}
@Override
public boolean execute(CommandSender commandSender, String[] strings) {
return execute(commandSender);
}
} | [
"public",
"class",
"StatsCommand",
"extends",
"AbstractPluginCommand",
"{",
"public",
"StatsCommand",
"(",
")",
"{",
"super",
"(",
"new",
"ArrayList",
"<",
">",
"(",
"List",
".",
"of",
"(",
"\"",
"stats",
"\"",
")",
")",
",",
"new",
"ArrayList",
"<",
">",
"(",
"List",
".",
"of",
"(",
"\"",
"dpm.stats",
"\"",
")",
")",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"execute",
"(",
"CommandSender",
"commandSender",
")",
"{",
"commandSender",
".",
"sendMessage",
"(",
"ChatColor",
".",
"AQUA",
"+",
"\"",
"=== DPM Stats ===",
"\"",
")",
";",
"commandSender",
".",
"sendMessage",
"(",
"ChatColor",
".",
"AQUA",
"+",
"\"",
"Number of project records: ",
"\"",
"+",
"EphemeralData",
".",
"getInstance",
"(",
")",
".",
"getNumProjectRecords",
"(",
")",
")",
";",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"boolean",
"execute",
"(",
"CommandSender",
"commandSender",
",",
"String",
"[",
"]",
"strings",
")",
"{",
"return",
"execute",
"(",
"commandSender",
")",
";",
"}",
"}"
] | @author Daniel McCoy Stephenson | [
"@author",
"Daniel",
"McCoy",
"Stephenson"
] | [] | [
{
"param": "AbstractPluginCommand",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractPluginCommand",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
c4678bad502455534da6db620308c14d9490d82e | lijijordan/hack_fb | src/main/java/com/fb/hack/domain/in/PageDto.java | [
"MIT"
] | Java | PageDto | /**
* The type Page dto.
*/ | The type Page dto. | [
"The",
"type",
"Page",
"dto",
"."
] | public class PageDto {
private int page;
private int size;
/**
* Gets page.
*
* @return the page
*/
public int getPage() {
return page;
}
/**
* Sets page.
*
* @param page the page
*/
public void setPage(int page) {
this.page = page;
}
/**
* Gets size.
*
* @return the size
*/
public int getSize() {
return size;
}
/**
* Sets size.
*
* @param size the size
*/
public void setSize(int size) {
this.size = size;
}
} | [
"public",
"class",
"PageDto",
"{",
"private",
"int",
"page",
";",
"private",
"int",
"size",
";",
"/**\n * Gets page.\n *\n * @return the page\n */",
"public",
"int",
"getPage",
"(",
")",
"{",
"return",
"page",
";",
"}",
"/**\n * Sets page.\n *\n * @param page the page\n */",
"public",
"void",
"setPage",
"(",
"int",
"page",
")",
"{",
"this",
".",
"page",
"=",
"page",
";",
"}",
"/**\n * Gets size.\n *\n * @return the size\n */",
"public",
"int",
"getSize",
"(",
")",
"{",
"return",
"size",
";",
"}",
"/**\n * Sets size.\n *\n * @param size the size\n */",
"public",
"void",
"setSize",
"(",
"int",
"size",
")",
"{",
"this",
".",
"size",
"=",
"size",
";",
"}",
"}"
] | The type Page dto. | [
"The",
"type",
"Page",
"dto",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
c4697c92418316ceab78fc61d835bd118efbd5f3 | zunpiau/Scalable-IO | src/main/java/zunpiau/nio/template/BasicReactorDesign.java | [
"Apache-2.0"
] | Java | BasicReactorDesign | /**
* Copy from <a href="gee.cs.oswego.edu/dl/cpjslides/nio.pdf">Basic Reactor Design</a>
*/ | Copy from Basic Reactor Design | [
"Copy",
"from",
"Basic",
"Reactor",
"Design"
] | public class BasicReactorDesign {
private final static int MAXIN = 65535;
private final static int MAXOUT = 65535;
private final static int PORT = 65500;
public static void main(String[] args) throws IOException {
new Thread(new Reactor(PORT)).start();
}
static class Reactor implements Runnable {
private final Selector selector;
private final ServerSocketChannel serverSocket;
Reactor(int port) throws IOException {
selector = Selector.open();
serverSocket = ServerSocketChannel.open();
serverSocket.socket().bind(new InetSocketAddress(port));
serverSocket.configureBlocking(false);
SelectionKey sk = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
sk.attach(new Acceptor());
}
public void run() {
try {
while (!Thread.interrupted()) {
selector.select();
Set selected = selector.selectedKeys();
Iterator it = selected.iterator();
while (it.hasNext())
dispatch((SelectionKey) (it.next()));
selected.clear();
}
} catch (IOException ex) { /* ... */ }
}
void dispatch(SelectionKey k) {
Runnable r = (Runnable) (k.attachment());
if (r != null)
r.run();
}
class Acceptor implements Runnable {
// inner
public void run() {
try {
SocketChannel c = serverSocket.accept();
if (c != null)
new Handler(selector, c);
} catch (IOException ex) { /* ... */ }
}
}
}
static class Handler implements Runnable {
final SocketChannel socket;
final SelectionKey sk;
ByteBuffer input = ByteBuffer.allocate(MAXIN);
ByteBuffer output = ByteBuffer.allocate(MAXOUT);
Handler(Selector selector, SocketChannel channel) throws IOException {
socket = channel;
channel.configureBlocking(false);
// Optionally try first read now
sk = socket.register(selector, 0);
sk.attach(this);
sk.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}
boolean inputIsComplete() {
return false;
}
boolean outputIsComplete() {
return false;
}
void process() { /* ... */ }
class Sender implements Runnable {
public void run() { // ...
try {
socket.write(output);
} catch (IOException e) {
e.printStackTrace();
}
if (outputIsComplete()) sk.cancel();
}
}
public void run() { // initial state is reader
try {
socket.read(input);
} catch (IOException e) {
e.printStackTrace();
}
if (inputIsComplete()) {
process();
sk.attach(new Sender());
sk.interestOps(SelectionKey.OP_WRITE);
sk.selector().wakeup();
}
}
}
} | [
"public",
"class",
"BasicReactorDesign",
"{",
"private",
"final",
"static",
"int",
"MAXIN",
"=",
"65535",
";",
"private",
"final",
"static",
"int",
"MAXOUT",
"=",
"65535",
";",
"private",
"final",
"static",
"int",
"PORT",
"=",
"65500",
";",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"IOException",
"{",
"new",
"Thread",
"(",
"new",
"Reactor",
"(",
"PORT",
")",
")",
".",
"start",
"(",
")",
";",
"}",
"static",
"class",
"Reactor",
"implements",
"Runnable",
"{",
"private",
"final",
"Selector",
"selector",
";",
"private",
"final",
"ServerSocketChannel",
"serverSocket",
";",
"Reactor",
"(",
"int",
"port",
")",
"throws",
"IOException",
"{",
"selector",
"=",
"Selector",
".",
"open",
"(",
")",
";",
"serverSocket",
"=",
"ServerSocketChannel",
".",
"open",
"(",
")",
";",
"serverSocket",
".",
"socket",
"(",
")",
".",
"bind",
"(",
"new",
"InetSocketAddress",
"(",
"port",
")",
")",
";",
"serverSocket",
".",
"configureBlocking",
"(",
"false",
")",
";",
"SelectionKey",
"sk",
"=",
"serverSocket",
".",
"register",
"(",
"selector",
",",
"SelectionKey",
".",
"OP_ACCEPT",
")",
";",
"sk",
".",
"attach",
"(",
"new",
"Acceptor",
"(",
")",
")",
";",
"}",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"while",
"(",
"!",
"Thread",
".",
"interrupted",
"(",
")",
")",
"{",
"selector",
".",
"select",
"(",
")",
";",
"Set",
"selected",
"=",
"selector",
".",
"selectedKeys",
"(",
")",
";",
"Iterator",
"it",
"=",
"selected",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"dispatch",
"(",
"(",
"SelectionKey",
")",
"(",
"it",
".",
"next",
"(",
")",
")",
")",
";",
"selected",
".",
"clear",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"/* ... */",
"}",
"}",
"void",
"dispatch",
"(",
"SelectionKey",
"k",
")",
"{",
"Runnable",
"r",
"=",
"(",
"Runnable",
")",
"(",
"k",
".",
"attachment",
"(",
")",
")",
";",
"if",
"(",
"r",
"!=",
"null",
")",
"r",
".",
"run",
"(",
")",
";",
"}",
"class",
"Acceptor",
"implements",
"Runnable",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"SocketChannel",
"c",
"=",
"serverSocket",
".",
"accept",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"null",
")",
"new",
"Handler",
"(",
"selector",
",",
"c",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"/* ... */",
"}",
"}",
"}",
"}",
"static",
"class",
"Handler",
"implements",
"Runnable",
"{",
"final",
"SocketChannel",
"socket",
";",
"final",
"SelectionKey",
"sk",
";",
"ByteBuffer",
"input",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"MAXIN",
")",
";",
"ByteBuffer",
"output",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"MAXOUT",
")",
";",
"Handler",
"(",
"Selector",
"selector",
",",
"SocketChannel",
"channel",
")",
"throws",
"IOException",
"{",
"socket",
"=",
"channel",
";",
"channel",
".",
"configureBlocking",
"(",
"false",
")",
";",
"sk",
"=",
"socket",
".",
"register",
"(",
"selector",
",",
"0",
")",
";",
"sk",
".",
"attach",
"(",
"this",
")",
";",
"sk",
".",
"interestOps",
"(",
"SelectionKey",
".",
"OP_READ",
")",
";",
"selector",
".",
"wakeup",
"(",
")",
";",
"}",
"boolean",
"inputIsComplete",
"(",
")",
"{",
"return",
"false",
";",
"}",
"boolean",
"outputIsComplete",
"(",
")",
"{",
"return",
"false",
";",
"}",
"void",
"process",
"(",
")",
"{",
"/* ... */",
"}",
"class",
"Sender",
"implements",
"Runnable",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"socket",
".",
"write",
"(",
"output",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"if",
"(",
"outputIsComplete",
"(",
")",
")",
"sk",
".",
"cancel",
"(",
")",
";",
"}",
"}",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"socket",
".",
"read",
"(",
"input",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"if",
"(",
"inputIsComplete",
"(",
")",
")",
"{",
"process",
"(",
")",
";",
"sk",
".",
"attach",
"(",
"new",
"Sender",
"(",
")",
")",
";",
"sk",
".",
"interestOps",
"(",
"SelectionKey",
".",
"OP_WRITE",
")",
";",
"sk",
".",
"selector",
"(",
")",
".",
"wakeup",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Copy from <a href="gee.cs.oswego.edu/dl/cpjslides/nio.pdf">Basic Reactor Design</a> | [
"Copy",
"from",
"<a",
"href",
"=",
"\"",
"gee",
".",
"cs",
".",
"oswego",
".",
"edu",
"/",
"dl",
"/",
"cpjslides",
"/",
"nio",
".",
"pdf",
"\"",
">",
"Basic",
"Reactor",
"Design<",
"/",
"a",
">"
] | [
"// inner",
"// Optionally try first read now",
"// ...",
"// initial state is reader"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
c46cbc1042bba089f7c6e5f27e9b28b7d8370767 | gridgain/gridgain | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/CacheRemoveWithTombstonesBasicTest.java | [
"CC0-1.0"
] | Java | InsertClosure | /** Insert new value into cache. */ | Insert new value into cache. | [
"Insert",
"new",
"value",
"into",
"cache",
"."
] | private static class InsertClosure implements CacheEntryProcessor<Object, Object, Object> {
/** */
private final Object newVal;
/**
* @param newVal New value.
*/
public InsertClosure(Object newVal) {
this.newVal = newVal;
}
/** {@inheritDoc} */
@Override public Object process(MutableEntry<Object, Object> entry, Object... arguments) throws EntryProcessorException {
assert entry.getValue() == null : entry;
entry.setValue(newVal);
return null;
}
} | [
"private",
"static",
"class",
"InsertClosure",
"implements",
"CacheEntryProcessor",
"<",
"Object",
",",
"Object",
",",
"Object",
">",
"{",
"/** */",
"private",
"final",
"Object",
"newVal",
";",
"/**\n * @param newVal New value.\n */",
"public",
"InsertClosure",
"(",
"Object",
"newVal",
")",
"{",
"this",
".",
"newVal",
"=",
"newVal",
";",
"}",
"/** {@inheritDoc} */",
"@",
"Override",
"public",
"Object",
"process",
"(",
"MutableEntry",
"<",
"Object",
",",
"Object",
">",
"entry",
",",
"Object",
"...",
"arguments",
")",
"throws",
"EntryProcessorException",
"{",
"assert",
"entry",
".",
"getValue",
"(",
")",
"==",
"null",
":",
"entry",
";",
"entry",
".",
"setValue",
"(",
"newVal",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Insert new value into cache. | [
"Insert",
"new",
"value",
"into",
"cache",
"."
] | [] | [
{
"param": "CacheEntryProcessor<Object, Object, Object>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "CacheEntryProcessor<Object, Object, Object>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
c46ecddc68665495d1d3a0b674a03d56b2ac370c | dyweb/gitlab-android | app/src/main/java/io/dongyue/gitlabandroid/model/api/APIError.java | [
"Apache-2.0"
] | Java | APIError | /**
* Created by Brotherjing on 2016/3/8.
*/ | Created by Brotherjing on 2016/3/8. | [
"Created",
"by",
"Brotherjing",
"on",
"2016",
"/",
"3",
"/",
"8",
"."
] | public class APIError {
@SerializedName("message")
String message;
public APIError() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
} | [
"public",
"class",
"APIError",
"{",
"@",
"SerializedName",
"(",
"\"",
"message",
"\"",
")",
"String",
"message",
";",
"public",
"APIError",
"(",
")",
"{",
"}",
"public",
"String",
"getMessage",
"(",
")",
"{",
"return",
"message",
";",
"}",
"public",
"void",
"setMessage",
"(",
"String",
"message",
")",
"{",
"this",
".",
"message",
"=",
"message",
";",
"}",
"}"
] | Created by Brotherjing on 2016/3/8. | [
"Created",
"by",
"Brotherjing",
"on",
"2016",
"/",
"3",
"/",
"8",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13987ef8b210fda6e29f5139711946bdb5a83968 | rvelasquezc/java_crud_mvc | src/vista/frmCliente.java | [
"MIT"
] | Java | FondoPanel | // End of variables declaration//GEN-END:variables | End of variables declaration//GEN-END:variables | [
"End",
"of",
"variables",
"declaration",
"//",
"GEN",
"-",
"END",
":",
"variables"
] | class FondoPanel extends JPanel {
private Image imagen;
@Override
public void paint(Graphics g) {
imagen = new ImageIcon(getClass().getResource("/image/gris.jpg")).getImage();
g.drawImage(imagen, 0, 0, getWidth(), getHeight(), this);
setOpaque(false);
super.paint(g);
}
} | [
"class",
"FondoPanel",
"extends",
"JPanel",
"{",
"private",
"Image",
"imagen",
";",
"@",
"Override",
"public",
"void",
"paint",
"(",
"Graphics",
"g",
")",
"{",
"imagen",
"=",
"new",
"ImageIcon",
"(",
"getClass",
"(",
")",
".",
"getResource",
"(",
"\"",
"/image/gris.jpg",
"\"",
")",
")",
".",
"getImage",
"(",
")",
";",
"g",
".",
"drawImage",
"(",
"imagen",
",",
"0",
",",
"0",
",",
"getWidth",
"(",
")",
",",
"getHeight",
"(",
")",
",",
"this",
")",
";",
"setOpaque",
"(",
"false",
")",
";",
"super",
".",
"paint",
"(",
"g",
")",
";",
"}",
"}"
] | End of variables declaration//GEN-END:variables | [
"End",
"of",
"variables",
"declaration",
"//",
"GEN",
"-",
"END",
":",
"variables"
] | [] | [
{
"param": "JPanel",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "JPanel",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
139a96e4a245efd5e3d2601f54814ef2c671c905 | hkhetawat/Cetus | src/cetus/analysis/SubscriptPair.java | [
"Artistic-1.0",
"ANTLR-PD"
] | Java | SubscriptPair | /**
* Creates a pair of affine subscripts where subscript is a single dimension of
* an array reference
*/ | Creates a pair of affine subscripts where subscript is a single dimension of
an array reference | [
"Creates",
"a",
"pair",
"of",
"affine",
"subscripts",
"where",
"subscript",
"is",
"a",
"single",
"dimension",
"of",
"an",
"array",
"reference"
] | public class SubscriptPair {
/* Store normalized expression if affine */
private Expression subscript1, subscript2;
/* Statements that contain the subscripts */
private Statement stmt1, stmt2;
/* Loops from which indices are present in the subscript pair */
private LinkedList<Loop> present_loops;
/* All loops from the enclosing loop nest */
private LinkedList<Loop> enclosing_loops;
/* Loop information for the enclosing loop nest */
private HashMap<Loop, LoopInfo> enclosing_loops_info;
/**
* Constructs a new subscript pair with the given pairs of expressions,
* statements, and the loop nest information.
* @param s1 the first subscript expression.
* @param s2 the second subscript expression.
* @param st1 the first statement.
* @param st2 the second subscript expression.
* @param nest the loop nest.
* @param loopinfo the extra information about loops.
*/
public SubscriptPair(
Expression s1, Expression s2, // Two subscripts (possibly orphans)
Statement st1, Statement st2, // Two statements containing s1,s2
LinkedList<Loop> nest, HashMap <Loop, LoopInfo> loopinfo) {
// All symbols present in affine expressions
List<Identifier> symbols_in_expressions;
List symbols_in_s1, symbols_in_s2;
this.subscript1 = s1;
this.subscript2 = s2;
this.stmt1 = st1;
this.stmt2 = st2;
this.enclosing_loops = nest;
this.enclosing_loops_info = loopinfo;
Set<Symbol> symbols_s1 = DataFlowTools.getUseSymbol(s1);
Set<Symbol> symbols_s2 = DataFlowTools.getUseSymbol(s2);
present_loops = new LinkedList<Loop>();
for (Loop loop: nest) {
LoopInfo info = loopinfo.get(loop);
Expression index = info.getLoopIndex();
if (symbols_s1.contains(((Identifier)index).getSymbol()) ||
symbols_s2.contains(((Identifier)index).getSymbol())) {
present_loops.addLast(loop);
}
}
}
protected HashMap<Loop, LoopInfo> getEnclosingLoopsInfo() {
return enclosing_loops_info;
}
protected LinkedList<Loop> getEnclosingLoopsList() {
return enclosing_loops;
}
protected LinkedList<Loop> getPresentLoops() {
return present_loops;
}
protected Expression getSubscript1() {
return subscript1;
}
protected Expression getSubscript2() {
return subscript2;
}
protected Statement getStatement1() {
return stmt1;
}
protected Statement getStatement2() {
return stmt2;
}
protected int getComplexity() {
return present_loops.size();
}
public String toString() {
StringBuilder str = new StringBuilder(80);
str.append("[SUBSCRIPT-PAIR] ").append(subscript1);
str.append(", ").append(subscript2).append(PrintTools.line_sep);
for (Loop loop : enclosing_loops) {
str.append(" enclosed by ").append(enclosing_loops_info.get(loop));
str.append(PrintTools.line_sep);
}
for (Loop loop : present_loops) {
str.append(" relevant with ");
str.append(enclosing_loops_info.get(loop));
str.append(PrintTools.line_sep);
}
return str.toString();
}
} | [
"public",
"class",
"SubscriptPair",
"{",
"/* Store normalized expression if affine */",
"private",
"Expression",
"subscript1",
",",
"subscript2",
";",
"/* Statements that contain the subscripts */",
"private",
"Statement",
"stmt1",
",",
"stmt2",
";",
"/* Loops from which indices are present in the subscript pair */",
"private",
"LinkedList",
"<",
"Loop",
">",
"present_loops",
";",
"/* All loops from the enclosing loop nest */",
"private",
"LinkedList",
"<",
"Loop",
">",
"enclosing_loops",
";",
"/* Loop information for the enclosing loop nest */",
"private",
"HashMap",
"<",
"Loop",
",",
"LoopInfo",
">",
"enclosing_loops_info",
";",
"/**\n * Constructs a new subscript pair with the given pairs of expressions,\n * statements, and the loop nest information.\n * @param s1 the first subscript expression.\n * @param s2 the second subscript expression.\n * @param st1 the first statement.\n * @param st2 the second subscript expression.\n * @param nest the loop nest.\n * @param loopinfo the extra information about loops.\n */",
"public",
"SubscriptPair",
"(",
"Expression",
"s1",
",",
"Expression",
"s2",
",",
"Statement",
"st1",
",",
"Statement",
"st2",
",",
"LinkedList",
"<",
"Loop",
">",
"nest",
",",
"HashMap",
"<",
"Loop",
",",
"LoopInfo",
">",
"loopinfo",
")",
"{",
"List",
"<",
"Identifier",
">",
"symbols_in_expressions",
";",
"List",
"symbols_in_s1",
",",
"symbols_in_s2",
";",
"this",
".",
"subscript1",
"=",
"s1",
";",
"this",
".",
"subscript2",
"=",
"s2",
";",
"this",
".",
"stmt1",
"=",
"st1",
";",
"this",
".",
"stmt2",
"=",
"st2",
";",
"this",
".",
"enclosing_loops",
"=",
"nest",
";",
"this",
".",
"enclosing_loops_info",
"=",
"loopinfo",
";",
"Set",
"<",
"Symbol",
">",
"symbols_s1",
"=",
"DataFlowTools",
".",
"getUseSymbol",
"(",
"s1",
")",
";",
"Set",
"<",
"Symbol",
">",
"symbols_s2",
"=",
"DataFlowTools",
".",
"getUseSymbol",
"(",
"s2",
")",
";",
"present_loops",
"=",
"new",
"LinkedList",
"<",
"Loop",
">",
"(",
")",
";",
"for",
"(",
"Loop",
"loop",
":",
"nest",
")",
"{",
"LoopInfo",
"info",
"=",
"loopinfo",
".",
"get",
"(",
"loop",
")",
";",
"Expression",
"index",
"=",
"info",
".",
"getLoopIndex",
"(",
")",
";",
"if",
"(",
"symbols_s1",
".",
"contains",
"(",
"(",
"(",
"Identifier",
")",
"index",
")",
".",
"getSymbol",
"(",
")",
")",
"||",
"symbols_s2",
".",
"contains",
"(",
"(",
"(",
"Identifier",
")",
"index",
")",
".",
"getSymbol",
"(",
")",
")",
")",
"{",
"present_loops",
".",
"addLast",
"(",
"loop",
")",
";",
"}",
"}",
"}",
"protected",
"HashMap",
"<",
"Loop",
",",
"LoopInfo",
">",
"getEnclosingLoopsInfo",
"(",
")",
"{",
"return",
"enclosing_loops_info",
";",
"}",
"protected",
"LinkedList",
"<",
"Loop",
">",
"getEnclosingLoopsList",
"(",
")",
"{",
"return",
"enclosing_loops",
";",
"}",
"protected",
"LinkedList",
"<",
"Loop",
">",
"getPresentLoops",
"(",
")",
"{",
"return",
"present_loops",
";",
"}",
"protected",
"Expression",
"getSubscript1",
"(",
")",
"{",
"return",
"subscript1",
";",
"}",
"protected",
"Expression",
"getSubscript2",
"(",
")",
"{",
"return",
"subscript2",
";",
"}",
"protected",
"Statement",
"getStatement1",
"(",
")",
"{",
"return",
"stmt1",
";",
"}",
"protected",
"Statement",
"getStatement2",
"(",
")",
"{",
"return",
"stmt2",
";",
"}",
"protected",
"int",
"getComplexity",
"(",
")",
"{",
"return",
"present_loops",
".",
"size",
"(",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"StringBuilder",
"str",
"=",
"new",
"StringBuilder",
"(",
"80",
")",
";",
"str",
".",
"append",
"(",
"\"",
"[SUBSCRIPT-PAIR] ",
"\"",
")",
".",
"append",
"(",
"subscript1",
")",
";",
"str",
".",
"append",
"(",
"\"",
", ",
"\"",
")",
".",
"append",
"(",
"subscript2",
")",
".",
"append",
"(",
"PrintTools",
".",
"line_sep",
")",
";",
"for",
"(",
"Loop",
"loop",
":",
"enclosing_loops",
")",
"{",
"str",
".",
"append",
"(",
"\"",
" enclosed by ",
"\"",
")",
".",
"append",
"(",
"enclosing_loops_info",
".",
"get",
"(",
"loop",
")",
")",
";",
"str",
".",
"append",
"(",
"PrintTools",
".",
"line_sep",
")",
";",
"}",
"for",
"(",
"Loop",
"loop",
":",
"present_loops",
")",
"{",
"str",
".",
"append",
"(",
"\"",
" relevant with ",
"\"",
")",
";",
"str",
".",
"append",
"(",
"enclosing_loops_info",
".",
"get",
"(",
"loop",
")",
")",
";",
"str",
".",
"append",
"(",
"PrintTools",
".",
"line_sep",
")",
";",
"}",
"return",
"str",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Creates a pair of affine subscripts where subscript is a single dimension of
an array reference | [
"Creates",
"a",
"pair",
"of",
"affine",
"subscripts",
"where",
"subscript",
"is",
"a",
"single",
"dimension",
"of",
"an",
"array",
"reference"
] | [
"// Two subscripts (possibly orphans)",
"// Two statements containing s1,s2",
"// All symbols present in affine expressions"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13a109e7414cf7864e43b3b971882b242276307c | Niranjan-K/carbon4-kernel | launcher/src/main/java/org/wso2/carbon/launcher/Constants.java | [
"Apache-2.0"
] | Java | ExitCodes | /**
* Carbon server process exit codes.
*/ | Carbon server process exit codes. | [
"Carbon",
"server",
"process",
"exit",
"codes",
"."
] | static class ExitCodes {
static final int SUCCESSFUL_TERMINATION = 0;
static final int UNSUCCESSFUL_TERMINATION = -1;
static final int RESTART_ACTION = 121;
} | [
"static",
"class",
"ExitCodes",
"{",
"static",
"final",
"int",
"SUCCESSFUL_TERMINATION",
"=",
"0",
";",
"static",
"final",
"int",
"UNSUCCESSFUL_TERMINATION",
"=",
"-",
"1",
";",
"static",
"final",
"int",
"RESTART_ACTION",
"=",
"121",
";",
"}"
] | Carbon server process exit codes. | [
"Carbon",
"server",
"process",
"exit",
"codes",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13a49f839eab848104e66e687e8bcbd9915abcc2 | billwert/azure-sdk-for-java | sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactory.java | [
"MIT"
] | Java | UsernamePasswordCredentialBuilderFactory | /**
* A credential builder factory for the {@link UsernamePasswordCredentialBuilder}.
*/ | A credential builder factory for the UsernamePasswordCredentialBuilder. | [
"A",
"credential",
"builder",
"factory",
"for",
"the",
"UsernamePasswordCredentialBuilder",
"."
] | public class UsernamePasswordCredentialBuilderFactory extends AzureAadCredentialBuilderFactory<UsernamePasswordCredentialBuilder> {
/**
* Create a {@link UsernamePasswordCredentialBuilderFactory} instance with {@link AzureProperties}.
* @param azureProperties The Azure properties.
*/
public UsernamePasswordCredentialBuilderFactory(AzureProperties azureProperties) {
super(azureProperties);
}
@Override
protected UsernamePasswordCredentialBuilder createBuilderInstance() {
return new UsernamePasswordCredentialBuilder();
}
@Override
protected void configureService(UsernamePasswordCredentialBuilder builder) {
super.configureService(builder);
AzureProperties azureProperties = getAzureProperties();
TokenCredentialOptionsProvider.TokenCredentialOptions credential = azureProperties.getCredential();
PropertyMapper map = new PropertyMapper();
map.from(credential.getUsername()).to(builder::username);
map.from(credential.getPassword()).to(builder::password);
}
} | [
"public",
"class",
"UsernamePasswordCredentialBuilderFactory",
"extends",
"AzureAadCredentialBuilderFactory",
"<",
"UsernamePasswordCredentialBuilder",
">",
"{",
"/**\n * Create a {@link UsernamePasswordCredentialBuilderFactory} instance with {@link AzureProperties}.\n * @param azureProperties The Azure properties.\n */",
"public",
"UsernamePasswordCredentialBuilderFactory",
"(",
"AzureProperties",
"azureProperties",
")",
"{",
"super",
"(",
"azureProperties",
")",
";",
"}",
"@",
"Override",
"protected",
"UsernamePasswordCredentialBuilder",
"createBuilderInstance",
"(",
")",
"{",
"return",
"new",
"UsernamePasswordCredentialBuilder",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"configureService",
"(",
"UsernamePasswordCredentialBuilder",
"builder",
")",
"{",
"super",
".",
"configureService",
"(",
"builder",
")",
";",
"AzureProperties",
"azureProperties",
"=",
"getAzureProperties",
"(",
")",
";",
"TokenCredentialOptionsProvider",
".",
"TokenCredentialOptions",
"credential",
"=",
"azureProperties",
".",
"getCredential",
"(",
")",
";",
"PropertyMapper",
"map",
"=",
"new",
"PropertyMapper",
"(",
")",
";",
"map",
".",
"from",
"(",
"credential",
".",
"getUsername",
"(",
")",
")",
".",
"to",
"(",
"builder",
"::",
"username",
")",
";",
"map",
".",
"from",
"(",
"credential",
".",
"getPassword",
"(",
")",
")",
".",
"to",
"(",
"builder",
"::",
"password",
")",
";",
"}",
"}"
] | A credential builder factory for the {@link UsernamePasswordCredentialBuilder}. | [
"A",
"credential",
"builder",
"factory",
"for",
"the",
"{",
"@link",
"UsernamePasswordCredentialBuilder",
"}",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13a87cbb555dbb954dfb00e1e6123d35058ea64f | melvinodsa/ProlifeGame | core/src/com/jy/prolife/WelcomeScreen.java | [
"MIT"
] | Java | WelcomeScreen | /**
* Created by hacker on 27/3/15.
*/ | Created by hacker on 27/3/15. | [
"Created",
"by",
"hacker",
"on",
"27",
"/",
"3",
"/",
"15",
"."
] | public class WelcomeScreen implements Screen {
Game game;
OrthographicCamera camera;
SpriteBatch batch;
int playX;
Vector3 touch;
Boolean nextScreen;
public WelcomeScreen(Game game) {
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(true, 480, 854);
batch = new SpriteBatch();
playX = GameConstants.PLAY_X;
touch = new Vector3();
nextScreen = false;
}
@Override
public void show() {
}
@Override
public void render(float delta) {
update(delta);
draw(delta);
}
private void update(float delta) {
if((playX > 0 || Gdx.input.getAccelerometerX() < 0) && ((playX + GameConstants.BUTTON_WIDTH) < 480 || Gdx.input.getAccelerometerX() > 0 )){
playX -= Gdx.input.getAccelerometerX();
}
if(Gdx.input.isTouched()){
touch.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touch);
if (touch.x > playX && touch.x < playX + GameConstants.BUTTON_WIDTH && touch.y > GameConstants.PLAY_Y && touch.y < GameConstants.PLAY_Y + GameConstants.BUTTON_HEIGHT){
Assets.btn_sound.play();
Gdx.input.vibrate(100);
nextScreen = true;
}
}
if(nextScreen){
if(playX > (0 - GameConstants.BUTTON_WIDTH + 10)){
playX -= GameConstants.BUTTON_ANIMATION_SPEED;
}
if (! (playX > (0 - GameConstants.BUTTON_WIDTH + 10))){
nextScreen = false;
game.setScreen(new GameScreen(game));
game.getScreen().dispose();;
}
}
}
private void draw(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(Assets.back_sprite,0,0);
batch.draw(Assets.sprite_play, playX, GameConstants.PLAY_Y);
Assets.font.draw(batch, ""+Assets.settings.getInteger("highscore",0), 225, 700);
batch.end();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
}
} | [
"public",
"class",
"WelcomeScreen",
"implements",
"Screen",
"{",
"Game",
"game",
";",
"OrthographicCamera",
"camera",
";",
"SpriteBatch",
"batch",
";",
"int",
"playX",
";",
"Vector3",
"touch",
";",
"Boolean",
"nextScreen",
";",
"public",
"WelcomeScreen",
"(",
"Game",
"game",
")",
"{",
"this",
".",
"game",
"=",
"game",
";",
"camera",
"=",
"new",
"OrthographicCamera",
"(",
")",
";",
"camera",
".",
"setToOrtho",
"(",
"true",
",",
"480",
",",
"854",
")",
";",
"batch",
"=",
"new",
"SpriteBatch",
"(",
")",
";",
"playX",
"=",
"GameConstants",
".",
"PLAY_X",
";",
"touch",
"=",
"new",
"Vector3",
"(",
")",
";",
"nextScreen",
"=",
"false",
";",
"}",
"@",
"Override",
"public",
"void",
"show",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"render",
"(",
"float",
"delta",
")",
"{",
"update",
"(",
"delta",
")",
";",
"draw",
"(",
"delta",
")",
";",
"}",
"private",
"void",
"update",
"(",
"float",
"delta",
")",
"{",
"if",
"(",
"(",
"playX",
">",
"0",
"||",
"Gdx",
".",
"input",
".",
"getAccelerometerX",
"(",
")",
"<",
"0",
")",
"&&",
"(",
"(",
"playX",
"+",
"GameConstants",
".",
"BUTTON_WIDTH",
")",
"<",
"480",
"||",
"Gdx",
".",
"input",
".",
"getAccelerometerX",
"(",
")",
">",
"0",
")",
")",
"{",
"playX",
"-=",
"Gdx",
".",
"input",
".",
"getAccelerometerX",
"(",
")",
";",
"}",
"if",
"(",
"Gdx",
".",
"input",
".",
"isTouched",
"(",
")",
")",
"{",
"touch",
".",
"set",
"(",
"Gdx",
".",
"input",
".",
"getX",
"(",
")",
",",
"Gdx",
".",
"input",
".",
"getY",
"(",
")",
",",
"0",
")",
";",
"camera",
".",
"unproject",
"(",
"touch",
")",
";",
"if",
"(",
"touch",
".",
"x",
">",
"playX",
"&&",
"touch",
".",
"x",
"<",
"playX",
"+",
"GameConstants",
".",
"BUTTON_WIDTH",
"&&",
"touch",
".",
"y",
">",
"GameConstants",
".",
"PLAY_Y",
"&&",
"touch",
".",
"y",
"<",
"GameConstants",
".",
"PLAY_Y",
"+",
"GameConstants",
".",
"BUTTON_HEIGHT",
")",
"{",
"Assets",
".",
"btn_sound",
".",
"play",
"(",
")",
";",
"Gdx",
".",
"input",
".",
"vibrate",
"(",
"100",
")",
";",
"nextScreen",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"nextScreen",
")",
"{",
"if",
"(",
"playX",
">",
"(",
"0",
"-",
"GameConstants",
".",
"BUTTON_WIDTH",
"+",
"10",
")",
")",
"{",
"playX",
"-=",
"GameConstants",
".",
"BUTTON_ANIMATION_SPEED",
";",
"}",
"if",
"(",
"!",
"(",
"playX",
">",
"(",
"0",
"-",
"GameConstants",
".",
"BUTTON_WIDTH",
"+",
"10",
")",
")",
")",
"{",
"nextScreen",
"=",
"false",
";",
"game",
".",
"setScreen",
"(",
"new",
"GameScreen",
"(",
"game",
")",
")",
";",
"game",
".",
"getScreen",
"(",
")",
".",
"dispose",
"(",
")",
";",
";",
"}",
"}",
"}",
"private",
"void",
"draw",
"(",
"float",
"delta",
")",
"{",
"Gdx",
".",
"gl",
".",
"glClearColor",
"(",
"1",
",",
"1",
",",
"1",
",",
"1",
")",
";",
"Gdx",
".",
"gl",
".",
"glClear",
"(",
"GL20",
".",
"GL_COLOR_BUFFER_BIT",
")",
";",
"camera",
".",
"update",
"(",
")",
";",
"batch",
".",
"setProjectionMatrix",
"(",
"camera",
".",
"combined",
")",
";",
"batch",
".",
"begin",
"(",
")",
";",
"batch",
".",
"draw",
"(",
"Assets",
".",
"back_sprite",
",",
"0",
",",
"0",
")",
";",
"batch",
".",
"draw",
"(",
"Assets",
".",
"sprite_play",
",",
"playX",
",",
"GameConstants",
".",
"PLAY_Y",
")",
";",
"Assets",
".",
"font",
".",
"draw",
"(",
"batch",
",",
"\"",
"\"",
"+",
"Assets",
".",
"settings",
".",
"getInteger",
"(",
"\"",
"highscore",
"\"",
",",
"0",
")",
",",
"225",
",",
"700",
")",
";",
"batch",
".",
"end",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"resize",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"pause",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"resume",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"hide",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"dispose",
"(",
")",
"{",
"}",
"}"
] | Created by hacker on 27/3/15. | [
"Created",
"by",
"hacker",
"on",
"27",
"/",
"3",
"/",
"15",
"."
] | [] | [
{
"param": "Screen",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Screen",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13a9a12092b7ed46b7f1094ae16cfa7dec20383d | xresch/CoreFramework | src/main/java/com/xresch/cfw/features/dashboard/ServletDashboardList.java | [
"MIT",
"BSD-2-Clause",
"CC0-1.0",
"Apache-2.0"
] | Java | ServletDashboardList | /**************************************************************************************************************
*
* @author Reto Scheiwiller, (c) Copyright 2019
* @license MIT-License
**************************************************************************************************************/ | @author Reto Scheiwiller, (c) Copyright 2019
@license MIT-License | [
"@author",
"Reto",
"Scheiwiller",
"(",
"c",
")",
"Copyright",
"2019",
"@license",
"MIT",
"-",
"License"
] | public class ServletDashboardList extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger logger = CFWLog.getLogger(ServletDashboardList.class.getName());
/******************************************************************
*
******************************************************************/
@Override
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
HTMLResponse html = new HTMLResponse("Dashboard List");
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_VIEWER)
|| CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_CREATOR)
|| CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
createForms();
String action = request.getParameter("action");
if(action == null) {
//html.addCSSFile(HandlingType.JAR_RESOURCE, FeatureSpaces.RESOURCE_PACKAGE, "cfw_dashboard.css");
//html.addJSFileBottomSingle(new FileDefinition(HandlingType.JAR_RESOURCE, FeatureCore.RESOURCE_PACKAGE+".js", "cfw_usermgmt.js"));
html.addJSFileBottom(HandlingType.JAR_RESOURCE, FeatureDashboard.PACKAGE_RESOURCES, "cfw_dashboard_list.js");
//content.append(CFW.Files.readPackageResource(FeatureSpaces.RESOURCE_PACKAGE, "cfw_dashboard.html"));
html.addJavascriptCode("cfw_dashboardlist_initialDraw();");
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
}else {
handleDataRequest(request, response);
}
}else {
CFWMessages.accessDenied();
}
}
/******************************************************************
*
******************************************************************/
@Override
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
doGet(request, response);
}
/******************************************************************
*
******************************************************************/
private void handleDataRequest(HttpServletRequest request, HttpServletResponse response) {
String action = request.getParameter("action");
String item = request.getParameter("item");
String ID = request.getParameter("id");
String IDs = request.getParameter("ids");
//int userID = CFW.Context.Request.getUser().id();
JSONResponse jsonResponse = new JSONResponse();
//--------------------------------------
// Check Permissions
if(action.toLowerCase().equals("delete")
|| action.toLowerCase().equals("copy")
|| action.toLowerCase().equals("getform")) {
if(!CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_CREATOR)
&& !CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
CFWMessages.noPermission();
return;
}
}
switch(action.toLowerCase()) {
case "fetch":
switch(item.toLowerCase()) {
case "mydashboards": jsonResponse.getContent().append(CFW.DB.Dashboards.getUserDashboardListAsJSON());
break;
case "shareddashboards": jsonResponse.getContent().append(CFW.DB.Dashboards.getSharedDashboardListAsJSON());
break;
case "admindashboards": jsonResponse.getContent().append(CFW.DB.Dashboards.getAdminDashboardListAsJSON());
break;
case "export": jsonResponse.getContent().append(CFW.DB.Dashboards.getJsonArrayForExport(ID));
break;
default: CFW.Messages.itemNotSupported(item);
break;
}
break;
case "duplicate":
switch(item.toLowerCase()) {
case "dashboard": duplicateDashboard(jsonResponse, ID);
break;
default: CFW.Messages.itemNotSupported(item);
break;
}
break;
case "delete":
switch(item.toLowerCase()) {
case "dashboard": deleteDashboard(jsonResponse, ID);
break;
default: CFW.Messages.itemNotSupported(item);
break;
}
break;
case "import":
switch(item.toLowerCase()) {
case "dashboards": String jsonString = request.getParameter("jsonString");
CFW.DB.Dashboards.importByJson(jsonString, false);
CFW.Context.Request.addAlertMessage(MessageType.INFO, "Import finished!");
break;
default: CFW.Messages.itemNotSupported(item);
break;
}
break;
case "getform":
switch(item.toLowerCase()) {
case "editdashboard": createEditDashboardForm(jsonResponse, ID);
break;
case "changeowner": createChangeDashboardOwnerForm(jsonResponse, ID);
break;
default: CFW.Messages.itemNotSupported(item);
break;
}
break;
default: CFW.Messages.actionNotSupported(action);
break;
}
}
/******************************************************************
*
******************************************************************/
private void deleteDashboard(JSONResponse jsonResponse, String ID) {
// TODO Auto-generated method stub
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
jsonResponse.setSuccess(CFW.DB.Dashboards.deleteByID(ID));
}else {
jsonResponse.setSuccess(CFW.DB.Dashboards.deleteByIDForCurrentUser(ID));
}
}
/******************************************************************
*
******************************************************************/
private void duplicateDashboard(JSONResponse jsonResponse, String dashboardID) {
// TODO Auto-generated method stub
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_CREATOR)
|| CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
Dashboard duplicate = CFW.DB.Dashboards.selectByID(dashboardID);
duplicate.id(null);
duplicate.foreignKeyOwner(CFW.Context.Request.getUser().id());
duplicate.name(duplicate.name()+"(Copy)");
duplicate.isShared(false);
duplicate.sharedWithUsers(null);
duplicate.editors(null);
Integer newID = duplicate.insertGetPrimaryKey();
if(newID != null) {
//-----------------------------------------
// Duplicate Widgets
//-----------------------------------------
ArrayList<CFWObject> widgetList = CFW.DB.DashboardWidgets.getWidgetsForDashboard(dashboardID);
boolean success = true;
for(CFWObject object : widgetList) {
DashboardWidget widgetToCopy = (DashboardWidget)object;
widgetToCopy.id(null);
widgetToCopy.foreignKeyDashboard(newID);
if(!widgetToCopy.insert()) {
success = false;
CFW.Context.Request.addAlertMessage(MessageType.ERROR, "Error while duplicating widget.");
}
}
//-----------------------------------------
// Duplicate Parameters
//-----------------------------------------
ArrayList<CFWObject> parameterList = CFW.DB.DashboardParameters.getParametersForDashboard(dashboardID);
for(CFWObject object : parameterList) {
DashboardParameter paramToCopy = (DashboardParameter)object;
paramToCopy.id(null);
paramToCopy.foreignKeyDashboard(newID);
if(!paramToCopy.insert()) {
success = false;
CFW.Context.Request.addAlertMessage(MessageType.ERROR, "Error while duplicating parameter.");
}
}
if(success) {
CFW.Context.Request.addAlertMessage(MessageType.SUCCESS, "Dashboard duplicated successfully.");
}
jsonResponse.setSuccess(success);
}else {
jsonResponse.setSuccess(false);
}
}else {
jsonResponse.setSuccess(false);
CFW.Context.Request.addAlertMessage(MessageType.ERROR, "Insufficient permissions to duplicate the dashboard.");
}
}
/******************************************************************
*
******************************************************************/
private void createForms() {
//--------------------------------------
// Create Dashboard Form
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_CREATOR)
|| CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
CFWForm createDashboardForm = new Dashboard().toForm("cfwCreateDashboardForm", "{!cfw_dashboard_create!}");
createDashboardForm.setFormHandler(new CFWFormHandler() {
@Override
public void handleForm(HttpServletRequest request, HttpServletResponse response, CFWForm form, CFWObject origin) {
if(origin != null) {
origin.mapRequestParameters(request);
Dashboard dashboard = (Dashboard)origin;
dashboard.foreignKeyOwner(CFW.Context.Request.getUser().id());
if( CFW.DB.Dashboards.create(dashboard) ) {
CFW.Context.Request.addAlertMessage(MessageType.SUCCESS, "Dashboard created successfully!");
}
}
}
});
}
}
/******************************************************************
*
******************************************************************/
private void createEditDashboardForm(JSONResponse json, String ID) {
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_CREATOR)
|| CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
Dashboard dashboard = CFW.DB.Dashboards.selectByID(Integer.parseInt(ID));
if(dashboard != null) {
CFWForm editDashboardForm = dashboard.toForm("cfwEditDashboardForm"+ID, "Update Dashboard");
editDashboardForm.setFormHandler(new CFWFormHandler() {
@Override
public void handleForm(HttpServletRequest request, HttpServletResponse response, CFWForm form, CFWObject origin) {
Dashboard dashboard = (Dashboard)origin;
if(origin.mapRequestParameters(request)
&& CFW.DB.Dashboards.update((Dashboard)origin)) {
CFW.Context.Request.addAlertMessage(MessageType.SUCCESS, "Updated!");
if(!dashboard.isShared()
&& (dashboard.sharedWithUsers().size() > 0
|| dashboard.sharedWithGroups().size() > 0
|| dashboard.editors().size() > 0
|| dashboard.editorGroups().size() > 0
)
) {
CFW.Context.Request.addAlertMessage(
MessageType.INFO,
"Users won't be able to access your dashboard until you set shared to true. The dashboard was saved as not shared and with at least one shared users or roles. "
);
}
if(dashboard.isShared()
&& dashboard.sharedWithUsers().size() == 0
&& dashboard.sharedWithGroups().size() == 0
&& dashboard.editors().size() == 0
&& dashboard.editorGroups().size() == 0) {
CFW.Context.Request.addAlertMessage(
MessageType.INFO,
"All dashboard users will see this dashboard. The dashboard was saved as shared and no specific shared users or roles. "
);
}
}
}
});
editDashboardForm.appendToPayload(json);
json.setSuccess(true);
}
}else {
CFW.Context.Request.addAlertMessage(MessageType.ERROR, "Insufficient permissions to execute action.");
}
}
/******************************************************************
*
******************************************************************/
private void createChangeDashboardOwnerForm(JSONResponse json, String ID) {
if(CFW.Context.Request.hasPermission(FeatureDashboard.PERMISSION_DASHBOARD_ADMIN)) {
Dashboard dashboard = CFW.DB.Dashboards.selectByID(Integer.parseInt(ID));
final String NEW_OWNER = "JSON_NEW_OWNER";
if(dashboard != null) {
CFWForm changeOwnerForm = new CFWForm("cfwChangeDashboardOwnerForm"+ID, "Update Dashboard");
changeOwnerForm.addField(
CFWField.newTagsSelector(NEW_OWNER)
.setLabel("New Owner")
.addAttribute("maxTags", "1")
.setDescription("Select the new owner of the Dashboard.")
.addValidator(new NotNullOrEmptyValidator())
.setAutocompleteHandler(new CFWAutocompleteHandler(10) {
public AutocompleteResult getAutocompleteData(HttpServletRequest request, String searchValue) {
return CFW.DB.Users.autocompleteUser(searchValue, this.getMaxResults());
}
})
);
changeOwnerForm.setFormHandler(new CFWFormHandler() {
@Override
public void handleForm(HttpServletRequest request, HttpServletResponse response, CFWForm form, CFWObject origin) {
String newOwnerJson = request.getParameter(NEW_OWNER);
if(form.mapRequestParameters(request)) {
LinkedHashMap<String,String> mappedValue = CFW.JSON.fromJsonLinkedHashMap(newOwnerJson);
String newOwner = mappedValue.keySet().iterator().next();
if(!Strings.isNullOrEmpty(newOwner)) {
new CFWLog(logger).audit("UPDATE", Dashboard.class, "Change owner ID of dashboard from "+dashboard.foreignKeyOwner()+" to "+newOwner);
Integer oldOwner = dashboard.foreignKeyOwner();
dashboard.foreignKeyOwner(Integer.parseInt(newOwner));
if(dashboard.update(DashboardFields.FK_ID_USER)) {
CFW.Context.Request.addAlertMessage(MessageType.SUCCESS, "Updated!");
User currentUser = CFW.Context.Request.getUser();
//----------------------------------
// Send Notification to New Owner
Notification newOwnerNotification =
new Notification()
.foreignKeyUser(Integer.parseInt(newOwner))
.messageType(MessageType.INFO)
.title("Dashboard assigned to you: '"+dashboard.name()+"'")
.message("The user '"+currentUser.createUserLabel()+"' has assigned the dashboard to you. You are now the new owner of the dashboard.");
CFW.DB.Notifications.create(newOwnerNotification);
//----------------------------------
// Send Notification to Old Owner
User user = CFW.DB.Users.selectByID(newOwner);
Notification oldOwnerNotification =
new Notification()
.foreignKeyUser(oldOwner)
.messageType(MessageType.INFO)
.title("Owner of dashboard '"+dashboard.name()+"' is now "+user.createUserLabel())
.message("The user '"+currentUser.createUserLabel()+"' has changed the owner of your former dashboard to the user '"+user.createUserLabel()+"'. ");
CFW.DB.Notifications.create(oldOwnerNotification);
}
}
}
}
});
changeOwnerForm.appendToPayload(json);
json.setSuccess(true);
}
}else {
CFWMessages.noPermission();
}
}
} | [
"public",
"class",
"ServletDashboardList",
"extends",
"HttpServlet",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"private",
"static",
"final",
"Logger",
"logger",
"=",
"CFWLog",
".",
"getLogger",
"(",
"ServletDashboardList",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"@",
"Override",
"protected",
"void",
"doGet",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"HTMLResponse",
"html",
"=",
"new",
"HTMLResponse",
"(",
"\"",
"Dashboard List",
"\"",
")",
";",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_VIEWER",
")",
"||",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_CREATOR",
")",
"||",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"createForms",
"(",
")",
";",
"String",
"action",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"action",
"\"",
")",
";",
"if",
"(",
"action",
"==",
"null",
")",
"{",
"html",
".",
"addJSFileBottom",
"(",
"HandlingType",
".",
"JAR_RESOURCE",
",",
"FeatureDashboard",
".",
"PACKAGE_RESOURCES",
",",
"\"",
"cfw_dashboard_list.js",
"\"",
")",
";",
"html",
".",
"addJavascriptCode",
"(",
"\"",
"cfw_dashboardlist_initialDraw();",
"\"",
")",
";",
"response",
".",
"setContentType",
"(",
"\"",
"text/html",
"\"",
")",
";",
"response",
".",
"setStatus",
"(",
"HttpServletResponse",
".",
"SC_OK",
")",
";",
"}",
"else",
"{",
"handleDataRequest",
"(",
"request",
",",
"response",
")",
";",
"}",
"}",
"else",
"{",
"CFWMessages",
".",
"accessDenied",
"(",
")",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"@",
"Override",
"protected",
"void",
"doPost",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"doGet",
"(",
"request",
",",
"response",
")",
";",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"handleDataRequest",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"String",
"action",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"action",
"\"",
")",
";",
"String",
"item",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"item",
"\"",
")",
";",
"String",
"ID",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"id",
"\"",
")",
";",
"String",
"IDs",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"ids",
"\"",
")",
";",
"JSONResponse",
"jsonResponse",
"=",
"new",
"JSONResponse",
"(",
")",
";",
"if",
"(",
"action",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"",
"delete",
"\"",
")",
"||",
"action",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"",
"copy",
"\"",
")",
"||",
"action",
".",
"toLowerCase",
"(",
")",
".",
"equals",
"(",
"\"",
"getform",
"\"",
")",
")",
"{",
"if",
"(",
"!",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_CREATOR",
")",
"&&",
"!",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"CFWMessages",
".",
"noPermission",
"(",
")",
";",
"return",
";",
"}",
"}",
"switch",
"(",
"action",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"fetch",
"\"",
":",
"switch",
"(",
"item",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"mydashboards",
"\"",
":",
"jsonResponse",
".",
"getContent",
"(",
")",
".",
"append",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"getUserDashboardListAsJSON",
"(",
")",
")",
";",
"break",
";",
"case",
"\"",
"shareddashboards",
"\"",
":",
"jsonResponse",
".",
"getContent",
"(",
")",
".",
"append",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"getSharedDashboardListAsJSON",
"(",
")",
")",
";",
"break",
";",
"case",
"\"",
"admindashboards",
"\"",
":",
"jsonResponse",
".",
"getContent",
"(",
")",
".",
"append",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"getAdminDashboardListAsJSON",
"(",
")",
")",
";",
"break",
";",
"case",
"\"",
"export",
"\"",
":",
"jsonResponse",
".",
"getContent",
"(",
")",
".",
"append",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"getJsonArrayForExport",
"(",
"ID",
")",
")",
";",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"itemNotSupported",
"(",
"item",
")",
";",
"break",
";",
"}",
"break",
";",
"case",
"\"",
"duplicate",
"\"",
":",
"switch",
"(",
"item",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"dashboard",
"\"",
":",
"duplicateDashboard",
"(",
"jsonResponse",
",",
"ID",
")",
";",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"itemNotSupported",
"(",
"item",
")",
";",
"break",
";",
"}",
"break",
";",
"case",
"\"",
"delete",
"\"",
":",
"switch",
"(",
"item",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"dashboard",
"\"",
":",
"deleteDashboard",
"(",
"jsonResponse",
",",
"ID",
")",
";",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"itemNotSupported",
"(",
"item",
")",
";",
"break",
";",
"}",
"break",
";",
"case",
"\"",
"import",
"\"",
":",
"switch",
"(",
"item",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"dashboards",
"\"",
":",
"String",
"jsonString",
"=",
"request",
".",
"getParameter",
"(",
"\"",
"jsonString",
"\"",
")",
";",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"importByJson",
"(",
"jsonString",
",",
"false",
")",
";",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"INFO",
",",
"\"",
"Import finished!",
"\"",
")",
";",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"itemNotSupported",
"(",
"item",
")",
";",
"break",
";",
"}",
"break",
";",
"case",
"\"",
"getform",
"\"",
":",
"switch",
"(",
"item",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"\"",
"editdashboard",
"\"",
":",
"createEditDashboardForm",
"(",
"jsonResponse",
",",
"ID",
")",
";",
"break",
";",
"case",
"\"",
"changeowner",
"\"",
":",
"createChangeDashboardOwnerForm",
"(",
"jsonResponse",
",",
"ID",
")",
";",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"itemNotSupported",
"(",
"item",
")",
";",
"break",
";",
"}",
"break",
";",
"default",
":",
"CFW",
".",
"Messages",
".",
"actionNotSupported",
"(",
"action",
")",
";",
"break",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"deleteDashboard",
"(",
"JSONResponse",
"jsonResponse",
",",
"String",
"ID",
")",
"{",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"jsonResponse",
".",
"setSuccess",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"deleteByID",
"(",
"ID",
")",
")",
";",
"}",
"else",
"{",
"jsonResponse",
".",
"setSuccess",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"deleteByIDForCurrentUser",
"(",
"ID",
")",
")",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"duplicateDashboard",
"(",
"JSONResponse",
"jsonResponse",
",",
"String",
"dashboardID",
")",
"{",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_CREATOR",
")",
"||",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"Dashboard",
"duplicate",
"=",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"selectByID",
"(",
"dashboardID",
")",
";",
"duplicate",
".",
"id",
"(",
"null",
")",
";",
"duplicate",
".",
"foreignKeyOwner",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"getUser",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"duplicate",
".",
"name",
"(",
"duplicate",
".",
"name",
"(",
")",
"+",
"\"",
"(Copy)",
"\"",
")",
";",
"duplicate",
".",
"isShared",
"(",
"false",
")",
";",
"duplicate",
".",
"sharedWithUsers",
"(",
"null",
")",
";",
"duplicate",
".",
"editors",
"(",
"null",
")",
";",
"Integer",
"newID",
"=",
"duplicate",
".",
"insertGetPrimaryKey",
"(",
")",
";",
"if",
"(",
"newID",
"!=",
"null",
")",
"{",
"ArrayList",
"<",
"CFWObject",
">",
"widgetList",
"=",
"CFW",
".",
"DB",
".",
"DashboardWidgets",
".",
"getWidgetsForDashboard",
"(",
"dashboardID",
")",
";",
"boolean",
"success",
"=",
"true",
";",
"for",
"(",
"CFWObject",
"object",
":",
"widgetList",
")",
"{",
"DashboardWidget",
"widgetToCopy",
"=",
"(",
"DashboardWidget",
")",
"object",
";",
"widgetToCopy",
".",
"id",
"(",
"null",
")",
";",
"widgetToCopy",
".",
"foreignKeyDashboard",
"(",
"newID",
")",
";",
"if",
"(",
"!",
"widgetToCopy",
".",
"insert",
"(",
")",
")",
"{",
"success",
"=",
"false",
";",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"ERROR",
",",
"\"",
"Error while duplicating widget.",
"\"",
")",
";",
"}",
"}",
"ArrayList",
"<",
"CFWObject",
">",
"parameterList",
"=",
"CFW",
".",
"DB",
".",
"DashboardParameters",
".",
"getParametersForDashboard",
"(",
"dashboardID",
")",
";",
"for",
"(",
"CFWObject",
"object",
":",
"parameterList",
")",
"{",
"DashboardParameter",
"paramToCopy",
"=",
"(",
"DashboardParameter",
")",
"object",
";",
"paramToCopy",
".",
"id",
"(",
"null",
")",
";",
"paramToCopy",
".",
"foreignKeyDashboard",
"(",
"newID",
")",
";",
"if",
"(",
"!",
"paramToCopy",
".",
"insert",
"(",
")",
")",
"{",
"success",
"=",
"false",
";",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"ERROR",
",",
"\"",
"Error while duplicating parameter.",
"\"",
")",
";",
"}",
"}",
"if",
"(",
"success",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"SUCCESS",
",",
"\"",
"Dashboard duplicated successfully.",
"\"",
")",
";",
"}",
"jsonResponse",
".",
"setSuccess",
"(",
"success",
")",
";",
"}",
"else",
"{",
"jsonResponse",
".",
"setSuccess",
"(",
"false",
")",
";",
"}",
"}",
"else",
"{",
"jsonResponse",
".",
"setSuccess",
"(",
"false",
")",
";",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"ERROR",
",",
"\"",
"Insufficient permissions to duplicate the dashboard.",
"\"",
")",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"createForms",
"(",
")",
"{",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_CREATOR",
")",
"||",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"CFWForm",
"createDashboardForm",
"=",
"new",
"Dashboard",
"(",
")",
".",
"toForm",
"(",
"\"",
"cfwCreateDashboardForm",
"\"",
",",
"\"",
"{!cfw_dashboard_create!}",
"\"",
")",
";",
"createDashboardForm",
".",
"setFormHandler",
"(",
"new",
"CFWFormHandler",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"handleForm",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"CFWForm",
"form",
",",
"CFWObject",
"origin",
")",
"{",
"if",
"(",
"origin",
"!=",
"null",
")",
"{",
"origin",
".",
"mapRequestParameters",
"(",
"request",
")",
";",
"Dashboard",
"dashboard",
"=",
"(",
"Dashboard",
")",
"origin",
";",
"dashboard",
".",
"foreignKeyOwner",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"getUser",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"if",
"(",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"create",
"(",
"dashboard",
")",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"SUCCESS",
",",
"\"",
"Dashboard created successfully!",
"\"",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"createEditDashboardForm",
"(",
"JSONResponse",
"json",
",",
"String",
"ID",
")",
"{",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_CREATOR",
")",
"||",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"Dashboard",
"dashboard",
"=",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"selectByID",
"(",
"Integer",
".",
"parseInt",
"(",
"ID",
")",
")",
";",
"if",
"(",
"dashboard",
"!=",
"null",
")",
"{",
"CFWForm",
"editDashboardForm",
"=",
"dashboard",
".",
"toForm",
"(",
"\"",
"cfwEditDashboardForm",
"\"",
"+",
"ID",
",",
"\"",
"Update Dashboard",
"\"",
")",
";",
"editDashboardForm",
".",
"setFormHandler",
"(",
"new",
"CFWFormHandler",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"handleForm",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"CFWForm",
"form",
",",
"CFWObject",
"origin",
")",
"{",
"Dashboard",
"dashboard",
"=",
"(",
"Dashboard",
")",
"origin",
";",
"if",
"(",
"origin",
".",
"mapRequestParameters",
"(",
"request",
")",
"&&",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"update",
"(",
"(",
"Dashboard",
")",
"origin",
")",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"SUCCESS",
",",
"\"",
"Updated!",
"\"",
")",
";",
"if",
"(",
"!",
"dashboard",
".",
"isShared",
"(",
")",
"&&",
"(",
"dashboard",
".",
"sharedWithUsers",
"(",
")",
".",
"size",
"(",
")",
">",
"0",
"||",
"dashboard",
".",
"sharedWithGroups",
"(",
")",
".",
"size",
"(",
")",
">",
"0",
"||",
"dashboard",
".",
"editors",
"(",
")",
".",
"size",
"(",
")",
">",
"0",
"||",
"dashboard",
".",
"editorGroups",
"(",
")",
".",
"size",
"(",
")",
">",
"0",
")",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"INFO",
",",
"\"",
"Users won't be able to access your dashboard until you set shared to true. The dashboard was saved as not shared and with at least one shared users or roles. ",
"\"",
")",
";",
"}",
"if",
"(",
"dashboard",
".",
"isShared",
"(",
")",
"&&",
"dashboard",
".",
"sharedWithUsers",
"(",
")",
".",
"size",
"(",
")",
"==",
"0",
"&&",
"dashboard",
".",
"sharedWithGroups",
"(",
")",
".",
"size",
"(",
")",
"==",
"0",
"&&",
"dashboard",
".",
"editors",
"(",
")",
".",
"size",
"(",
")",
"==",
"0",
"&&",
"dashboard",
".",
"editorGroups",
"(",
")",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"INFO",
",",
"\"",
"All dashboard users will see this dashboard. The dashboard was saved as shared and no specific shared users or roles. ",
"\"",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"editDashboardForm",
".",
"appendToPayload",
"(",
"json",
")",
";",
"json",
".",
"setSuccess",
"(",
"true",
")",
";",
"}",
"}",
"else",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"ERROR",
",",
"\"",
"Insufficient permissions to execute action.",
"\"",
")",
";",
"}",
"}",
"/******************************************************************\n\t *\n\t ******************************************************************/",
"private",
"void",
"createChangeDashboardOwnerForm",
"(",
"JSONResponse",
"json",
",",
"String",
"ID",
")",
"{",
"if",
"(",
"CFW",
".",
"Context",
".",
"Request",
".",
"hasPermission",
"(",
"FeatureDashboard",
".",
"PERMISSION_DASHBOARD_ADMIN",
")",
")",
"{",
"Dashboard",
"dashboard",
"=",
"CFW",
".",
"DB",
".",
"Dashboards",
".",
"selectByID",
"(",
"Integer",
".",
"parseInt",
"(",
"ID",
")",
")",
";",
"final",
"String",
"NEW_OWNER",
"=",
"\"",
"JSON_NEW_OWNER",
"\"",
";",
"if",
"(",
"dashboard",
"!=",
"null",
")",
"{",
"CFWForm",
"changeOwnerForm",
"=",
"new",
"CFWForm",
"(",
"\"",
"cfwChangeDashboardOwnerForm",
"\"",
"+",
"ID",
",",
"\"",
"Update Dashboard",
"\"",
")",
";",
"changeOwnerForm",
".",
"addField",
"(",
"CFWField",
".",
"newTagsSelector",
"(",
"NEW_OWNER",
")",
".",
"setLabel",
"(",
"\"",
"New Owner",
"\"",
")",
".",
"addAttribute",
"(",
"\"",
"maxTags",
"\"",
",",
"\"",
"1",
"\"",
")",
".",
"setDescription",
"(",
"\"",
"Select the new owner of the Dashboard.",
"\"",
")",
".",
"addValidator",
"(",
"new",
"NotNullOrEmptyValidator",
"(",
")",
")",
".",
"setAutocompleteHandler",
"(",
"new",
"CFWAutocompleteHandler",
"(",
"10",
")",
"{",
"public",
"AutocompleteResult",
"getAutocompleteData",
"(",
"HttpServletRequest",
"request",
",",
"String",
"searchValue",
")",
"{",
"return",
"CFW",
".",
"DB",
".",
"Users",
".",
"autocompleteUser",
"(",
"searchValue",
",",
"this",
".",
"getMaxResults",
"(",
")",
")",
";",
"}",
"}",
")",
")",
";",
"changeOwnerForm",
".",
"setFormHandler",
"(",
"new",
"CFWFormHandler",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"handleForm",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"CFWForm",
"form",
",",
"CFWObject",
"origin",
")",
"{",
"String",
"newOwnerJson",
"=",
"request",
".",
"getParameter",
"(",
"NEW_OWNER",
")",
";",
"if",
"(",
"form",
".",
"mapRequestParameters",
"(",
"request",
")",
")",
"{",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"mappedValue",
"=",
"CFW",
".",
"JSON",
".",
"fromJsonLinkedHashMap",
"(",
"newOwnerJson",
")",
";",
"String",
"newOwner",
"=",
"mappedValue",
".",
"keySet",
"(",
")",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"newOwner",
")",
")",
"{",
"new",
"CFWLog",
"(",
"logger",
")",
".",
"audit",
"(",
"\"",
"UPDATE",
"\"",
",",
"Dashboard",
".",
"class",
",",
"\"",
"Change owner ID of dashboard from ",
"\"",
"+",
"dashboard",
".",
"foreignKeyOwner",
"(",
")",
"+",
"\"",
" to ",
"\"",
"+",
"newOwner",
")",
";",
"Integer",
"oldOwner",
"=",
"dashboard",
".",
"foreignKeyOwner",
"(",
")",
";",
"dashboard",
".",
"foreignKeyOwner",
"(",
"Integer",
".",
"parseInt",
"(",
"newOwner",
")",
")",
";",
"if",
"(",
"dashboard",
".",
"update",
"(",
"DashboardFields",
".",
"FK_ID_USER",
")",
")",
"{",
"CFW",
".",
"Context",
".",
"Request",
".",
"addAlertMessage",
"(",
"MessageType",
".",
"SUCCESS",
",",
"\"",
"Updated!",
"\"",
")",
";",
"User",
"currentUser",
"=",
"CFW",
".",
"Context",
".",
"Request",
".",
"getUser",
"(",
")",
";",
"Notification",
"newOwnerNotification",
"=",
"new",
"Notification",
"(",
")",
".",
"foreignKeyUser",
"(",
"Integer",
".",
"parseInt",
"(",
"newOwner",
")",
")",
".",
"messageType",
"(",
"MessageType",
".",
"INFO",
")",
".",
"title",
"(",
"\"",
"Dashboard assigned to you: '",
"\"",
"+",
"dashboard",
".",
"name",
"(",
")",
"+",
"\"",
"'",
"\"",
")",
".",
"message",
"(",
"\"",
"The user '",
"\"",
"+",
"currentUser",
".",
"createUserLabel",
"(",
")",
"+",
"\"",
"' has assigned the dashboard to you. You are now the new owner of the dashboard.",
"\"",
")",
";",
"CFW",
".",
"DB",
".",
"Notifications",
".",
"create",
"(",
"newOwnerNotification",
")",
";",
"User",
"user",
"=",
"CFW",
".",
"DB",
".",
"Users",
".",
"selectByID",
"(",
"newOwner",
")",
";",
"Notification",
"oldOwnerNotification",
"=",
"new",
"Notification",
"(",
")",
".",
"foreignKeyUser",
"(",
"oldOwner",
")",
".",
"messageType",
"(",
"MessageType",
".",
"INFO",
")",
".",
"title",
"(",
"\"",
"Owner of dashboard '",
"\"",
"+",
"dashboard",
".",
"name",
"(",
")",
"+",
"\"",
"' is now ",
"\"",
"+",
"user",
".",
"createUserLabel",
"(",
")",
")",
".",
"message",
"(",
"\"",
"The user '",
"\"",
"+",
"currentUser",
".",
"createUserLabel",
"(",
")",
"+",
"\"",
"' has changed the owner of your former dashboard to the user '",
"\"",
"+",
"user",
".",
"createUserLabel",
"(",
")",
"+",
"\"",
"'. ",
"\"",
")",
";",
"CFW",
".",
"DB",
".",
"Notifications",
".",
"create",
"(",
"oldOwnerNotification",
")",
";",
"}",
"}",
"}",
"}",
"}",
")",
";",
"changeOwnerForm",
".",
"appendToPayload",
"(",
"json",
")",
";",
"json",
".",
"setSuccess",
"(",
"true",
")",
";",
"}",
"}",
"else",
"{",
"CFWMessages",
".",
"noPermission",
"(",
")",
";",
"}",
"}",
"}"
] | @author Reto Scheiwiller, (c) Copyright 2019
@license MIT-License | [
"@author",
"Reto",
"Scheiwiller",
"(",
"c",
")",
"Copyright",
"2019",
"@license",
"MIT",
"-",
"License"
] | [
"//html.addCSSFile(HandlingType.JAR_RESOURCE, FeatureSpaces.RESOURCE_PACKAGE, \"cfw_dashboard.css\");",
"//html.addJSFileBottomSingle(new FileDefinition(HandlingType.JAR_RESOURCE, FeatureCore.RESOURCE_PACKAGE+\".js\", \"cfw_usermgmt.js\"));",
"//content.append(CFW.Files.readPackageResource(FeatureSpaces.RESOURCE_PACKAGE, \"cfw_dashboard.html\"));",
"//int\tuserID = CFW.Context.Request.getUser().id();",
"//--------------------------------------",
"// Check Permissions",
"// TODO Auto-generated method stub",
"// TODO Auto-generated method stub",
"//-----------------------------------------",
"// Duplicate Widgets",
"//-----------------------------------------",
"//-----------------------------------------",
"// Duplicate Parameters",
"//-----------------------------------------",
"//--------------------------------------",
"// Create Dashboard Form",
"//----------------------------------",
"// Send Notification to New Owner",
"//----------------------------------",
"// Send Notification to Old Owner"
] | [
{
"param": "HttpServlet",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "HttpServlet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13ab118bc1b4af697d1290462334aa1b5a434d7d | ghandalf/Logscape | vs-log/src/com/liquidlabs/log/indexer/persistit/PIFieldStore.java | [
"Apache-2.0"
] | Java | PIFieldStore | /**
* Created with IntelliJ IDEA.
* User: neil
* Date: 11/02/2013
* Time: 12:41
* To change this template use File | Settings | File Templates.
*/ | Created with IntelliJ IDEA.
User: neil
Date: 11/02/2013
Time: 12:41
To change this template use File | Settings | File Templates. | [
"Created",
"with",
"IntelliJ",
"IDEA",
".",
"User",
":",
"neil",
"Date",
":",
"11",
"/",
"02",
"/",
"2013",
"Time",
":",
"12",
":",
"41",
"To",
"change",
"this",
"template",
"use",
"File",
"|",
"Settings",
"|",
"File",
"Templates",
"."
] | public class PIFieldStore {
private Db<String, byte[]> store;
public PIFieldStore(Db<String, byte[]> store) {
try {
//store = AbstractIndexer.getStore(environment, "DT", threadLocal);
this.store = store;
if (!Boolean.getBoolean("log.db.readonly")) add(FieldSets.getBasicFieldSet());
} catch (Exception e) {
throw new RuntimeException("Failed:", e);
}
}
public static final ThreadLocal threadLocal = new ThreadLocal();
public FieldSet get(String fieldSetId) {
try {
FieldSet result = (FieldSet) Convertor.deserialize(store.get(fieldSetId));
if (result != null) {
result.upgrade();
}
return result;
} catch (Exception e) {
throw new RuntimeException("Failed:", e);
}
}
public void add(FieldSet fieldSet) throws Exception {
store.put(fieldSet.getId(), Convertor.serialize(fieldSet));
}
public List<FieldSet> list(Indexer.Filter<FieldSet> filter) {
List<FieldSet> results = new ArrayList<FieldSet>();
Set<String> fieldSets = store.keySet();
for (String key : fieldSets) {
FieldSet fieldSet = null;
try {
fieldSet = (FieldSet) Convertor.deserialize(store.get(key));
} catch (Exception e) {
e.printStackTrace();
}
if (filter.accept(fieldSet) && fieldSet != null) results.add(fieldSet);
}
Collections.sort(results, new Comparator<FieldSet>() {
public int compare(FieldSet o1, FieldSet o2) {
try {
return Integer.valueOf(o2.priority).compareTo(o1.priority);
} catch (Throwable t) {
return 0;
}
}
});
return results;
}
public void remove(FieldSet data) {
try {
if (data != null) {
store.remove(data.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
if (store != null) {
this.store.commit();
this.store.close();
this.store = null;
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void sync() {
try {
this.store.commit();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
} | [
"public",
"class",
"PIFieldStore",
"{",
"private",
"Db",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"store",
";",
"public",
"PIFieldStore",
"(",
"Db",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"store",
")",
"{",
"try",
"{",
"this",
".",
"store",
"=",
"store",
";",
"if",
"(",
"!",
"Boolean",
".",
"getBoolean",
"(",
"\"",
"log.db.readonly",
"\"",
")",
")",
"add",
"(",
"FieldSets",
".",
"getBasicFieldSet",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Failed:",
"\"",
",",
"e",
")",
";",
"}",
"}",
"public",
"static",
"final",
"ThreadLocal",
"threadLocal",
"=",
"new",
"ThreadLocal",
"(",
")",
";",
"public",
"FieldSet",
"get",
"(",
"String",
"fieldSetId",
")",
"{",
"try",
"{",
"FieldSet",
"result",
"=",
"(",
"FieldSet",
")",
"Convertor",
".",
"deserialize",
"(",
"store",
".",
"get",
"(",
"fieldSetId",
")",
")",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"result",
".",
"upgrade",
"(",
")",
";",
"}",
"return",
"result",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Failed:",
"\"",
",",
"e",
")",
";",
"}",
"}",
"public",
"void",
"add",
"(",
"FieldSet",
"fieldSet",
")",
"throws",
"Exception",
"{",
"store",
".",
"put",
"(",
"fieldSet",
".",
"getId",
"(",
")",
",",
"Convertor",
".",
"serialize",
"(",
"fieldSet",
")",
")",
";",
"}",
"public",
"List",
"<",
"FieldSet",
">",
"list",
"(",
"Indexer",
".",
"Filter",
"<",
"FieldSet",
">",
"filter",
")",
"{",
"List",
"<",
"FieldSet",
">",
"results",
"=",
"new",
"ArrayList",
"<",
"FieldSet",
">",
"(",
")",
";",
"Set",
"<",
"String",
">",
"fieldSets",
"=",
"store",
".",
"keySet",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"fieldSets",
")",
"{",
"FieldSet",
"fieldSet",
"=",
"null",
";",
"try",
"{",
"fieldSet",
"=",
"(",
"FieldSet",
")",
"Convertor",
".",
"deserialize",
"(",
"store",
".",
"get",
"(",
"key",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"if",
"(",
"filter",
".",
"accept",
"(",
"fieldSet",
")",
"&&",
"fieldSet",
"!=",
"null",
")",
"results",
".",
"add",
"(",
"fieldSet",
")",
";",
"}",
"Collections",
".",
"sort",
"(",
"results",
",",
"new",
"Comparator",
"<",
"FieldSet",
">",
"(",
")",
"{",
"public",
"int",
"compare",
"(",
"FieldSet",
"o1",
",",
"FieldSet",
"o2",
")",
"{",
"try",
"{",
"return",
"Integer",
".",
"valueOf",
"(",
"o2",
".",
"priority",
")",
".",
"compareTo",
"(",
"o1",
".",
"priority",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"return",
"0",
";",
"}",
"}",
"}",
")",
";",
"return",
"results",
";",
"}",
"public",
"void",
"remove",
"(",
"FieldSet",
"data",
")",
"{",
"try",
"{",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"store",
".",
"remove",
"(",
"data",
".",
"getId",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"public",
"void",
"close",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"store",
"!=",
"null",
")",
"{",
"this",
".",
"store",
".",
"commit",
"(",
")",
";",
"this",
".",
"store",
".",
"close",
"(",
")",
";",
"this",
".",
"store",
"=",
"null",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"public",
"void",
"sync",
"(",
")",
"{",
"try",
"{",
"this",
".",
"store",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}"
] | Created with IntelliJ IDEA. | [
"Created",
"with",
"IntelliJ",
"IDEA",
"."
] | [
"//store = AbstractIndexer.getStore(environment, \"DT\", threadLocal);",
"//To change body of catch statement use File | Settings | File Templates.",
"//To change body of catch statement use File | Settings | File Templates."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13ab20a5a0f517fe84d3b977cb0fc56eb90263f5 | vdogaru/incubator-quarks | samples/connectors/src/main/java/org/apache/edgent/samples/connectors/obd2/Obd2Streams.java | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | Java | Obd2Streams | /**
* Sample OBD-II streams.
*
*/ | Sample OBD-II streams. | [
"Sample",
"OBD",
"-",
"II",
"streams",
"."
] | public class Obd2Streams {
/**
* Get a stream of temperature readings which
* are increasing over the last minute.
*
* Poll temperatures every five seconds and
* calculate the maximum reading and rate of change
* (slope) over the last minute, partitioned by parameter
* {@link org.apache.edgent.samples.connectors.elm327.Cmd#PID pid}. Filter so that only
* those with a rate of increase greater than
* or equal to 1 degree C/minute is present on the returned stream.
*
* Temperatures included are
* {@link org.apache.edgent.samples.connectors.elm327.Pids01#AIR_INTAKE_TEMP AIR_INTAKE_TEMP} and
* {@link org.apache.edgent.samples.connectors.elm327.Pids01#ENGINE_COOLANT_TEMP ENGINE_COOLANT_TEMP}.
*
* @param device Serial device the ELM327 is connected to.
* @return Stream that will contain parameters with increasing temperatures.
*/
public static TStream<JsonObject> increasingTemps(SerialDevice device) {
TStream<JsonArray> tempsA = Elm327Streams.poll(device, 5, SECONDS,
AIR_INTAKE_TEMP,
ENGINE_COOLANT_TEMP);
TStream<JsonObject> temps = tempsA.flatMap(je -> je).map(je -> je.getAsJsonObject());
TWindow<JsonObject, JsonElement> window = temps.last(1, MINUTES, j -> j.get(PID));
TStream<JsonObject> temperatureRate = JsonAnalytics.aggregate(window, PID, VALUE, MAX, SLOPE);
// Have the stream contain only tuples where
// the rise in temperatures >= 1 degree C/minute
temperatureRate = temperatureRate.filter(j -> {
JsonObject v = getObject(j, "value");
return v.has("SLOPE") && getDouble(v, "SLOPE") >= 1.0;
});
return temperatureRate;
}
/**
* Get a stream containing vehicle speed (km/h)
* and engine revs (rpm).
*
* {@link org.apache.edgent.samples.connectors.elm327.Pids01#SPEED Speed}
* and {@link org.apache.edgent.samples.connectors.elm327.Pids01#RPM engine revs}
* are polled every 200ms and returned as a stream
* containing JSON objects with keys {@code speed}
* and {@code rpm}.
*
* The two readings may not be exactly consistent with
* each other as there are fetched sequentially from
* the ELM327.
*
* @param device Serial device the ELM327 is connected to.
* @return Stream that will contain speed and engine revolutions.
*/
public static TStream<JsonObject> tach(SerialDevice device) {
TStream<JsonArray> rpmSpeed = Elm327Streams.poll(device, 200, TimeUnit.MILLISECONDS,
SPEED, RPM);
TStream<JsonObject> tach = rpmSpeed.map(ja -> {
JsonObject j = new JsonObject();
double speed = getDouble(ja.get(0), VALUE);
double rpm = getDouble(ja.get(1), VALUE);
j.addProperty("speed", speed);
j.addProperty("rpm", rpm);
return j;
});
return tach;
}
/**
* Utility method to simplify accessing a JSON object.
* @param json JSON object containing the object to be got.
* @param key Key of the object to be got.
* @return JSON object with key {@code key} from {@code json}.
*/
public static JsonObject getObject(JsonObject json, String key) {
return json.getAsJsonObject(key);
}
/**
* Utility method to simplify accessing a number as a double.
* @param json JSON object containing the number to be got.
* @param key Key of the number to be got.
* @return Number with key {@code key} from {@code json}.
*/
public static double getDouble(JsonElement json, String key) {
return json.getAsJsonObject().get(key).getAsDouble();
}
} | [
"public",
"class",
"Obd2Streams",
"{",
"/**\n * Get a stream of temperature readings which\n * are increasing over the last minute.\n * \n * Poll temperatures every five seconds and\n * calculate the maximum reading and rate of change\n * (slope) over the last minute, partitioned by parameter\n * {@link org.apache.edgent.samples.connectors.elm327.Cmd#PID pid}. Filter so that only\n * those with a rate of increase greater than\n * or equal to 1 degree C/minute is present on the returned stream.\n * \n * Temperatures included are\n * {@link org.apache.edgent.samples.connectors.elm327.Pids01#AIR_INTAKE_TEMP AIR_INTAKE_TEMP} and\n * {@link org.apache.edgent.samples.connectors.elm327.Pids01#ENGINE_COOLANT_TEMP ENGINE_COOLANT_TEMP}.\n * \n * @param device Serial device the ELM327 is connected to.\n * @return Stream that will contain parameters with increasing temperatures.\n */",
"public",
"static",
"TStream",
"<",
"JsonObject",
">",
"increasingTemps",
"(",
"SerialDevice",
"device",
")",
"{",
"TStream",
"<",
"JsonArray",
">",
"tempsA",
"=",
"Elm327Streams",
".",
"poll",
"(",
"device",
",",
"5",
",",
"SECONDS",
",",
"AIR_INTAKE_TEMP",
",",
"ENGINE_COOLANT_TEMP",
")",
";",
"TStream",
"<",
"JsonObject",
">",
"temps",
"=",
"tempsA",
".",
"flatMap",
"(",
"je",
"->",
"je",
")",
".",
"map",
"(",
"je",
"->",
"je",
".",
"getAsJsonObject",
"(",
")",
")",
";",
"TWindow",
"<",
"JsonObject",
",",
"JsonElement",
">",
"window",
"=",
"temps",
".",
"last",
"(",
"1",
",",
"MINUTES",
",",
"j",
"->",
"j",
".",
"get",
"(",
"PID",
")",
")",
";",
"TStream",
"<",
"JsonObject",
">",
"temperatureRate",
"=",
"JsonAnalytics",
".",
"aggregate",
"(",
"window",
",",
"PID",
",",
"VALUE",
",",
"MAX",
",",
"SLOPE",
")",
";",
"temperatureRate",
"=",
"temperatureRate",
".",
"filter",
"(",
"j",
"->",
"{",
"JsonObject",
"v",
"=",
"getObject",
"(",
"j",
",",
"\"",
"value",
"\"",
")",
";",
"return",
"v",
".",
"has",
"(",
"\"",
"SLOPE",
"\"",
")",
"&&",
"getDouble",
"(",
"v",
",",
"\"",
"SLOPE",
"\"",
")",
">=",
"1.0",
";",
"}",
")",
";",
"return",
"temperatureRate",
";",
"}",
"/**\n * Get a stream containing vehicle speed (km/h)\n * and engine revs (rpm).\n * \n * {@link org.apache.edgent.samples.connectors.elm327.Pids01#SPEED Speed}\n * and {@link org.apache.edgent.samples.connectors.elm327.Pids01#RPM engine revs}\n * are polled every 200ms and returned as a stream\n * containing JSON objects with keys {@code speed}\n * and {@code rpm}.\n * \n * The two readings may not be exactly consistent with\n * each other as there are fetched sequentially from\n * the ELM327. \n * \n * @param device Serial device the ELM327 is connected to.\n * @return Stream that will contain speed and engine revolutions.\n */",
"public",
"static",
"TStream",
"<",
"JsonObject",
">",
"tach",
"(",
"SerialDevice",
"device",
")",
"{",
"TStream",
"<",
"JsonArray",
">",
"rpmSpeed",
"=",
"Elm327Streams",
".",
"poll",
"(",
"device",
",",
"200",
",",
"TimeUnit",
".",
"MILLISECONDS",
",",
"SPEED",
",",
"RPM",
")",
";",
"TStream",
"<",
"JsonObject",
">",
"tach",
"=",
"rpmSpeed",
".",
"map",
"(",
"ja",
"->",
"{",
"JsonObject",
"j",
"=",
"new",
"JsonObject",
"(",
")",
";",
"double",
"speed",
"=",
"getDouble",
"(",
"ja",
".",
"get",
"(",
"0",
")",
",",
"VALUE",
")",
";",
"double",
"rpm",
"=",
"getDouble",
"(",
"ja",
".",
"get",
"(",
"1",
")",
",",
"VALUE",
")",
";",
"j",
".",
"addProperty",
"(",
"\"",
"speed",
"\"",
",",
"speed",
")",
";",
"j",
".",
"addProperty",
"(",
"\"",
"rpm",
"\"",
",",
"rpm",
")",
";",
"return",
"j",
";",
"}",
")",
";",
"return",
"tach",
";",
"}",
"/**\n * Utility method to simplify accessing a JSON object.\n * @param json JSON object containing the object to be got.\n * @param key Key of the object to be got.\n * @return JSON object with key {@code key} from {@code json}.\n */",
"public",
"static",
"JsonObject",
"getObject",
"(",
"JsonObject",
"json",
",",
"String",
"key",
")",
"{",
"return",
"json",
".",
"getAsJsonObject",
"(",
"key",
")",
";",
"}",
"/**\n * Utility method to simplify accessing a number as a double.\n * @param json JSON object containing the number to be got.\n * @param key Key of the number to be got.\n * @return Number with key {@code key} from {@code json}.\n */",
"public",
"static",
"double",
"getDouble",
"(",
"JsonElement",
"json",
",",
"String",
"key",
")",
"{",
"return",
"json",
".",
"getAsJsonObject",
"(",
")",
".",
"get",
"(",
"key",
")",
".",
"getAsDouble",
"(",
")",
";",
"}",
"}"
] | Sample OBD-II streams. | [
"Sample",
"OBD",
"-",
"II",
"streams",
"."
] | [
"// Have the stream contain only tuples where",
"// the rise in temperatures >= 1 degree C/minute"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13ac215348a47488feafe59a77e84438a4625673 | adrientetar/xi-android | app/src/main/java/io/github/adrientetar/xi/objects/XiBridge.java | [
"Apache-2.0"
] | Java | XiBridge | /**
* Bridge that spawns a xi-core process and provides a comm interface.
*
* The RPC APIs are similar to those of xi-gtk CoreConnection.
*/ | Bridge that spawns a xi-core process and provides a comm interface.
The RPC APIs are similar to those of xi-gtk CoreConnection. | [
"Bridge",
"that",
"spawns",
"a",
"xi",
"-",
"core",
"process",
"and",
"provides",
"a",
"comm",
"interface",
".",
"The",
"RPC",
"APIs",
"are",
"similar",
"to",
"those",
"of",
"xi",
"-",
"gtk",
"CoreConnection",
"."
] | public class XiBridge {
private int id = 0;
// Bridge to app
private SparseArray<ResponseHandler> handlers;
private OnUpdateListener listener = null;
// Bridge to process
private Process process;
private BufferedWriter writer;
// Bridge to polling thread
private Handler handler;
private Thread watcher;
// App interfaces
public interface ResponseHandler {
void invoke(Object result);
}
public interface OnUpdateListener {
void onUpdate(String tab, JSONObject update);
}
public OnUpdateListener getUpdateListener() {
return this.listener;
}
public void setUpdateListener(OnUpdateListener listener) {
this.listener = listener;
}
//
public XiBridge(Context ctx) {
try {
this.process = Runtime.getRuntime().exec(
ctx.getApplicationInfo().nativeLibraryDir + "/lib_xi-core_.so");
} catch (java.io.IOException e) {
Log.e("Xi", "Couldn't open dependant binary.");
return;
}
OutputStream stdin = this.process.getOutputStream();
InputStream stdout = this.process.getInputStream();
this.writer = new BufferedWriter(new OutputStreamWriter(stdin));
this.handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
XiBridge.this.processMessage((String) message.obj);
}
};
this.watcher = new WatcherThread(stdout, this.handler);
this.watcher.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
// Xi will quit silently when stdin is closed
XiBridge.this.process.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
this.handlers = new SparseArray<>();
}
/* Receive */
private boolean processMessage(String line) {
try {
JSONObject root = new JSONObject(line);
if (root.has("id")) {
int id = root.getInt("id");
ResponseHandler handler = this.handlers.get(id);
if (handler != null) {
Object result = root.get("result");
handler.invoke(result);
this.handlers.remove(id);
}
} else {
String method = root.getString("method");
JSONObject params = root.getJSONObject("params");
switch (method) {
case "update":
this.handleUpdate(params);
break;
}
}
} catch (JSONException e) {
Log.e("Xi", "Couldn't process message from back-end.");
e.printStackTrace();
return false;
}
return true;
}
private void handleUpdate(JSONObject params) {
if (this.listener == null) {
return;
}
String tab;
JSONObject update;
try {
tab = params.getString("tab");
update = params.getJSONObject("update");
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.listener.onUpdate(tab, update);
}
/* Send */
private void send(JSONObject root) {
try {
this.writer.write(root.toString());
this.writer.write("\n");
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendNotification(String method, JSONObject params) {
JSONObject root = new JSONObject();
try {
root.put("method", method);
root.put("params", params);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.send(root);
}
private void sendRequest(String method, JSONObject params, ResponseHandler handler) {
this.handlers.put(this.id, handler);
JSONObject root = new JSONObject();
try {
root.put("id", this.id);
root.put("method", method);
root.put("params", params);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.id += 1;
this.send(root);
}
public void sendEdit(String tab, String method) {
this.sendEdit(tab, method, new JSONObject());
}
public void sendEdit(String tab, String method, JSONObject editParams) {
JSONObject params = new JSONObject();
try {
params.put("method", method);
params.put("tab", tab);
params.put("params", editParams);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendNotification("edit", params);
}
private void sendEditArray(String tab, String method, JSONArray editParams) {
JSONObject params = new JSONObject();
try {
params.put("method", method);
params.put("tab", tab);
params.put("params", editParams);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendNotification("edit", params);
}
private void sendEditRequest(String tab, String method, JSONObject editParams, ResponseHandler handler) {
JSONObject params = new JSONObject();
try {
params.put("method", method);
params.put("tab", tab);
params.put("params", editParams);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendRequest("edit", params, handler);
}
public void sendNewTab(ResponseHandler handler) {
this.sendRequest("new_tab", new JSONObject(), handler);
}
public void sendDeleteTab(String tab) {
JSONObject params = new JSONObject();
try {
params.put("tab", tab);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendNotification("delete_tab", params);
}
public void sendInsert(String tab, String chars) {
JSONObject params = new JSONObject();
try {
params.put("chars", chars);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendEdit(tab, "insert", params);
}
public void sendOpen(String tab, String filename) {
JSONObject params = new JSONObject();
try {
params.put("filename", filename);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendEdit(tab, "open", params);
}
public void sendSave(String tab, String filename) {
JSONObject params = new JSONObject();
try {
params.put("filename", filename);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendEdit(tab, "save", params);
}
public void sendScroll(String tab, int firstLine, int lastLine) {
JSONArray params = new JSONArray();
params.put(firstLine);
params.put(lastLine);
this.sendEditArray(tab, "scroll", params);
}
public void sendClick(String tab, int line, int column, int modifiers, int clickCount) {
JSONArray params = new JSONArray();
params.put(line);
params.put(column);
params.put(modifiers);
params.put(clickCount);
this.sendEditArray(tab, "click", params);
}
public void sendDrag(String tab, int line, int column, int modifiers) {
JSONArray params = new JSONArray();
params.put(line);
params.put(column);
params.put(modifiers);
this.sendEditArray(tab, "drag", params);
}
public void sendRenderLines(String tab, int firstLine, int lastLine, ResponseHandler handler) {
JSONObject params = new JSONObject();
try {
params.put("first_line", firstLine);
params.put("last_line", lastLine);
} catch (JSONException e) {
e.printStackTrace();
return;
}
this.sendEditRequest(tab, "render_lines", params, handler);
}
} | [
"public",
"class",
"XiBridge",
"{",
"private",
"int",
"id",
"=",
"0",
";",
"private",
"SparseArray",
"<",
"ResponseHandler",
">",
"handlers",
";",
"private",
"OnUpdateListener",
"listener",
"=",
"null",
";",
"private",
"Process",
"process",
";",
"private",
"BufferedWriter",
"writer",
";",
"private",
"Handler",
"handler",
";",
"private",
"Thread",
"watcher",
";",
"public",
"interface",
"ResponseHandler",
"{",
"void",
"invoke",
"(",
"Object",
"result",
")",
";",
"}",
"public",
"interface",
"OnUpdateListener",
"{",
"void",
"onUpdate",
"(",
"String",
"tab",
",",
"JSONObject",
"update",
")",
";",
"}",
"public",
"OnUpdateListener",
"getUpdateListener",
"(",
")",
"{",
"return",
"this",
".",
"listener",
";",
"}",
"public",
"void",
"setUpdateListener",
"(",
"OnUpdateListener",
"listener",
")",
"{",
"this",
".",
"listener",
"=",
"listener",
";",
"}",
"public",
"XiBridge",
"(",
"Context",
"ctx",
")",
"{",
"try",
"{",
"this",
".",
"process",
"=",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"exec",
"(",
"ctx",
".",
"getApplicationInfo",
"(",
")",
".",
"nativeLibraryDir",
"+",
"\"",
"/lib_xi-core_.so",
"\"",
")",
";",
"}",
"catch",
"(",
"java",
".",
"io",
".",
"IOException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"Xi",
"\"",
",",
"\"",
"Couldn't open dependant binary.",
"\"",
")",
";",
"return",
";",
"}",
"OutputStream",
"stdin",
"=",
"this",
".",
"process",
".",
"getOutputStream",
"(",
")",
";",
"InputStream",
"stdout",
"=",
"this",
".",
"process",
".",
"getInputStream",
"(",
")",
";",
"this",
".",
"writer",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"stdin",
")",
")",
";",
"this",
".",
"handler",
"=",
"new",
"Handler",
"(",
"Looper",
".",
"getMainLooper",
"(",
")",
")",
"{",
"@",
"Override",
"public",
"void",
"handleMessage",
"(",
"Message",
"message",
")",
"{",
"XiBridge",
".",
"this",
".",
"processMessage",
"(",
"(",
"String",
")",
"message",
".",
"obj",
")",
";",
"}",
"}",
";",
"this",
".",
"watcher",
"=",
"new",
"WatcherThread",
"(",
"stdout",
",",
"this",
".",
"handler",
")",
";",
"this",
".",
"watcher",
".",
"start",
"(",
")",
";",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"new",
"Thread",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"XiBridge",
".",
"this",
".",
"process",
".",
"getOutputStream",
"(",
")",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"this",
".",
"handlers",
"=",
"new",
"SparseArray",
"<",
">",
"(",
")",
";",
"}",
"/* Receive */",
"private",
"boolean",
"processMessage",
"(",
"String",
"line",
")",
"{",
"try",
"{",
"JSONObject",
"root",
"=",
"new",
"JSONObject",
"(",
"line",
")",
";",
"if",
"(",
"root",
".",
"has",
"(",
"\"",
"id",
"\"",
")",
")",
"{",
"int",
"id",
"=",
"root",
".",
"getInt",
"(",
"\"",
"id",
"\"",
")",
";",
"ResponseHandler",
"handler",
"=",
"this",
".",
"handlers",
".",
"get",
"(",
"id",
")",
";",
"if",
"(",
"handler",
"!=",
"null",
")",
"{",
"Object",
"result",
"=",
"root",
".",
"get",
"(",
"\"",
"result",
"\"",
")",
";",
"handler",
".",
"invoke",
"(",
"result",
")",
";",
"this",
".",
"handlers",
".",
"remove",
"(",
"id",
")",
";",
"}",
"}",
"else",
"{",
"String",
"method",
"=",
"root",
".",
"getString",
"(",
"\"",
"method",
"\"",
")",
";",
"JSONObject",
"params",
"=",
"root",
".",
"getJSONObject",
"(",
"\"",
"params",
"\"",
")",
";",
"switch",
"(",
"method",
")",
"{",
"case",
"\"",
"update",
"\"",
":",
"this",
".",
"handleUpdate",
"(",
"params",
")",
";",
"break",
";",
"}",
"}",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"Xi",
"\"",
",",
"\"",
"Couldn't process message from back-end.",
"\"",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"private",
"void",
"handleUpdate",
"(",
"JSONObject",
"params",
")",
"{",
"if",
"(",
"this",
".",
"listener",
"==",
"null",
")",
"{",
"return",
";",
"}",
"String",
"tab",
";",
"JSONObject",
"update",
";",
"try",
"{",
"tab",
"=",
"params",
".",
"getString",
"(",
"\"",
"tab",
"\"",
")",
";",
"update",
"=",
"params",
".",
"getJSONObject",
"(",
"\"",
"update",
"\"",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"listener",
".",
"onUpdate",
"(",
"tab",
",",
"update",
")",
";",
"}",
"/* Send */",
"private",
"void",
"send",
"(",
"JSONObject",
"root",
")",
"{",
"try",
"{",
"this",
".",
"writer",
".",
"write",
"(",
"root",
".",
"toString",
"(",
")",
")",
";",
"this",
".",
"writer",
".",
"write",
"(",
"\"",
"\\n",
"\"",
")",
";",
"this",
".",
"writer",
".",
"flush",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"private",
"void",
"sendNotification",
"(",
"String",
"method",
",",
"JSONObject",
"params",
")",
"{",
"JSONObject",
"root",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"root",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"root",
".",
"put",
"(",
"\"",
"params",
"\"",
",",
"params",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"send",
"(",
"root",
")",
";",
"}",
"private",
"void",
"sendRequest",
"(",
"String",
"method",
",",
"JSONObject",
"params",
",",
"ResponseHandler",
"handler",
")",
"{",
"this",
".",
"handlers",
".",
"put",
"(",
"this",
".",
"id",
",",
"handler",
")",
";",
"JSONObject",
"root",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"root",
".",
"put",
"(",
"\"",
"id",
"\"",
",",
"this",
".",
"id",
")",
";",
"root",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"root",
".",
"put",
"(",
"\"",
"params",
"\"",
",",
"params",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"id",
"+=",
"1",
";",
"this",
".",
"send",
"(",
"root",
")",
";",
"}",
"public",
"void",
"sendEdit",
"(",
"String",
"tab",
",",
"String",
"method",
")",
"{",
"this",
".",
"sendEdit",
"(",
"tab",
",",
"method",
",",
"new",
"JSONObject",
"(",
")",
")",
";",
"}",
"public",
"void",
"sendEdit",
"(",
"String",
"tab",
",",
"String",
"method",
",",
"JSONObject",
"editParams",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"params",
".",
"put",
"(",
"\"",
"tab",
"\"",
",",
"tab",
")",
";",
"params",
".",
"put",
"(",
"\"",
"params",
"\"",
",",
"editParams",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendNotification",
"(",
"\"",
"edit",
"\"",
",",
"params",
")",
";",
"}",
"private",
"void",
"sendEditArray",
"(",
"String",
"tab",
",",
"String",
"method",
",",
"JSONArray",
"editParams",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"params",
".",
"put",
"(",
"\"",
"tab",
"\"",
",",
"tab",
")",
";",
"params",
".",
"put",
"(",
"\"",
"params",
"\"",
",",
"editParams",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendNotification",
"(",
"\"",
"edit",
"\"",
",",
"params",
")",
";",
"}",
"private",
"void",
"sendEditRequest",
"(",
"String",
"tab",
",",
"String",
"method",
",",
"JSONObject",
"editParams",
",",
"ResponseHandler",
"handler",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"params",
".",
"put",
"(",
"\"",
"tab",
"\"",
",",
"tab",
")",
";",
"params",
".",
"put",
"(",
"\"",
"params",
"\"",
",",
"editParams",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendRequest",
"(",
"\"",
"edit",
"\"",
",",
"params",
",",
"handler",
")",
";",
"}",
"public",
"void",
"sendNewTab",
"(",
"ResponseHandler",
"handler",
")",
"{",
"this",
".",
"sendRequest",
"(",
"\"",
"new_tab",
"\"",
",",
"new",
"JSONObject",
"(",
")",
",",
"handler",
")",
";",
"}",
"public",
"void",
"sendDeleteTab",
"(",
"String",
"tab",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"tab",
"\"",
",",
"tab",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendNotification",
"(",
"\"",
"delete_tab",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendInsert",
"(",
"String",
"tab",
",",
"String",
"chars",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"chars",
"\"",
",",
"chars",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendEdit",
"(",
"tab",
",",
"\"",
"insert",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendOpen",
"(",
"String",
"tab",
",",
"String",
"filename",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"filename",
"\"",
",",
"filename",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendEdit",
"(",
"tab",
",",
"\"",
"open",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendSave",
"(",
"String",
"tab",
",",
"String",
"filename",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"filename",
"\"",
",",
"filename",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendEdit",
"(",
"tab",
",",
"\"",
"save",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendScroll",
"(",
"String",
"tab",
",",
"int",
"firstLine",
",",
"int",
"lastLine",
")",
"{",
"JSONArray",
"params",
"=",
"new",
"JSONArray",
"(",
")",
";",
"params",
".",
"put",
"(",
"firstLine",
")",
";",
"params",
".",
"put",
"(",
"lastLine",
")",
";",
"this",
".",
"sendEditArray",
"(",
"tab",
",",
"\"",
"scroll",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendClick",
"(",
"String",
"tab",
",",
"int",
"line",
",",
"int",
"column",
",",
"int",
"modifiers",
",",
"int",
"clickCount",
")",
"{",
"JSONArray",
"params",
"=",
"new",
"JSONArray",
"(",
")",
";",
"params",
".",
"put",
"(",
"line",
")",
";",
"params",
".",
"put",
"(",
"column",
")",
";",
"params",
".",
"put",
"(",
"modifiers",
")",
";",
"params",
".",
"put",
"(",
"clickCount",
")",
";",
"this",
".",
"sendEditArray",
"(",
"tab",
",",
"\"",
"click",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendDrag",
"(",
"String",
"tab",
",",
"int",
"line",
",",
"int",
"column",
",",
"int",
"modifiers",
")",
"{",
"JSONArray",
"params",
"=",
"new",
"JSONArray",
"(",
")",
";",
"params",
".",
"put",
"(",
"line",
")",
";",
"params",
".",
"put",
"(",
"column",
")",
";",
"params",
".",
"put",
"(",
"modifiers",
")",
";",
"this",
".",
"sendEditArray",
"(",
"tab",
",",
"\"",
"drag",
"\"",
",",
"params",
")",
";",
"}",
"public",
"void",
"sendRenderLines",
"(",
"String",
"tab",
",",
"int",
"firstLine",
",",
"int",
"lastLine",
",",
"ResponseHandler",
"handler",
")",
"{",
"JSONObject",
"params",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"params",
".",
"put",
"(",
"\"",
"first_line",
"\"",
",",
"firstLine",
")",
";",
"params",
".",
"put",
"(",
"\"",
"last_line",
"\"",
",",
"lastLine",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"sendEditRequest",
"(",
"tab",
",",
"\"",
"render_lines",
"\"",
",",
"params",
",",
"handler",
")",
";",
"}",
"}"
] | Bridge that spawns a xi-core process and provides a comm interface. | [
"Bridge",
"that",
"spawns",
"a",
"xi",
"-",
"core",
"process",
"and",
"provides",
"a",
"comm",
"interface",
"."
] | [
"// Bridge to app",
"// Bridge to process",
"// Bridge to polling thread",
"// App interfaces",
"//",
"// Xi will quit silently when stdin is closed"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13b0d177f2a78cd3a78af4076df7484e8dc10408 | venanciolm/afirma-ui-miniapplet_x_x | afirma_ui_miniapplet/src/main/java/es/gob/afirma/signers/pkcs7/DigestedData.java | [
"MIT"
] | Java | DigestedData | /** Clase base para la implementación del tipo DigestedData. La Estructura
* del mensaje es la siguiente:<br>
*
* <pre>
* <code>
* DigestedData ::= SEQUENCE {
* version CMSVersion,
* digestAlgorithm DigestAlgorithmIdentifier,
* encapContentInfo EncapsulatedContentInfo,
* digest Digest }
*
* Digest ::= OCTET STRING
* </code>
* </pre>
*
* La implementación del código ha seguido los pasos necesarios
* para crear un mensaje DigestedData de BouncyCastle: <a
* href="http://www.bouncycastle.org/">www.bouncycastle.org</a> */ | Clase base para la implementación del tipo DigestedData. La Estructura
del mensaje es la siguiente:
Digest ::= OCTET STRING
| [
"Clase",
"base",
"para",
"la",
"implementación",
"del",
"tipo",
"DigestedData",
".",
"La",
"Estructura",
"del",
"mensaje",
"es",
"la",
"siguiente",
":",
"Digest",
"::",
"=",
"OCTET",
"STRING"
] | public final class DigestedData implements ASN1Encodable {
private final ASN1Integer version;
private final AlgorithmIdentifier digestAlgorithm;
private final ContentInfo contentInfo;
private final ASN1OctetString digest;
static DigestedData getInstance(final Object o) {
if (o instanceof DigestedData) {
return (DigestedData) o;
}
else if (o instanceof ASN1Sequence) {
return new DigestedData((ASN1Sequence) o);
}
throw new IllegalArgumentException("Objeto desconocido: " + o.getClass().getName()); //$NON-NLS-1$
}
/** Crea un objeto CMS DigestedData.
* @param digestAlgo ALgoritmo de huella digital
* @param contentInfo ContentInfo
* @param digest Valor de la huella digital
*/
public DigestedData(final AlgorithmIdentifier digestAlgo, final ContentInfo contentInfo, final ASN1OctetString digest) {
this.version = new ASN1Integer(0);
this.digestAlgorithm = digestAlgo;
this.contentInfo = contentInfo;
this.digest = digest;
}
/** Crea un object CMS DigestedData a partir de una Secuencia ASN.1.
* @param seq Secuencia origen
*/
public DigestedData(final ASN1Sequence seq) {
final Enumeration<?> e = seq.getObjects();
this.version = (ASN1Integer) e.nextElement();
this.digestAlgorithm = AlgorithmIdentifier.getInstance(e.nextElement());
this.contentInfo = ContentInfo.getInstance(e.nextElement());
this.digest = (ASN1OctetString) e.nextElement();
}
/**
* Recupera la versión del sistema de empaquetado PKCS#7.
* @return Versión del empaquetado.
*/
public String getVersion() {
return this.version.toString();
}
/**
* Recupera el algoritmo de huella digital configurada para los empaquetados.
* @return Algoritmo.
*/
public String getDigestAlgorithm() {
return this.digestAlgorithm.getAlgorithm().toString();
}
ASN1OctetString getDigest() {
return this.digest;
}
/**
* Recupera el tipo de contenido.
* @return Tipo de contenido.
*/
public String getContentType() {
return this.contentInfo.getContentType().toString();
}
/** Produce an object suitable for an ASN1OutputStream.
*
* <pre>
* DigestedData ::= SEQUENCE {
* version CMSVersion,
* digestAlgorithms DigestAlgorithmIdentifiers,
* encapContentInfo EncapsulatedContentInfo,
* digest Digest
* }
*
* Digest ::= OCTET STRING
* </pre> */
@Override
public ASN1Primitive toASN1Primitive() {
final ASN1EncodableVector v = new ASN1EncodableVector();
v.add(this.version);
v.add(this.digestAlgorithm);
v.add(this.contentInfo);
v.add(this.digest);
return new BERSequence(v);
}
} | [
"public",
"final",
"class",
"DigestedData",
"implements",
"ASN1Encodable",
"{",
"private",
"final",
"ASN1Integer",
"version",
";",
"private",
"final",
"AlgorithmIdentifier",
"digestAlgorithm",
";",
"private",
"final",
"ContentInfo",
"contentInfo",
";",
"private",
"final",
"ASN1OctetString",
"digest",
";",
"static",
"DigestedData",
"getInstance",
"(",
"final",
"Object",
"o",
")",
"{",
"if",
"(",
"o",
"instanceof",
"DigestedData",
")",
"{",
"return",
"(",
"DigestedData",
")",
"o",
";",
"}",
"else",
"if",
"(",
"o",
"instanceof",
"ASN1Sequence",
")",
"{",
"return",
"new",
"DigestedData",
"(",
"(",
"ASN1Sequence",
")",
"o",
")",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Objeto desconocido: ",
"\"",
"+",
"o",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"/** Crea un objeto CMS DigestedData.\n * @param digestAlgo ALgoritmo de huella digital\n * @param contentInfo ContentInfo\n * @param digest Valor de la huella digital\n */",
"public",
"DigestedData",
"(",
"final",
"AlgorithmIdentifier",
"digestAlgo",
",",
"final",
"ContentInfo",
"contentInfo",
",",
"final",
"ASN1OctetString",
"digest",
")",
"{",
"this",
".",
"version",
"=",
"new",
"ASN1Integer",
"(",
"0",
")",
";",
"this",
".",
"digestAlgorithm",
"=",
"digestAlgo",
";",
"this",
".",
"contentInfo",
"=",
"contentInfo",
";",
"this",
".",
"digest",
"=",
"digest",
";",
"}",
"/** Crea un object CMS DigestedData a partir de una Secuencia ASN.1.\n * @param seq Secuencia origen\n */",
"public",
"DigestedData",
"(",
"final",
"ASN1Sequence",
"seq",
")",
"{",
"final",
"Enumeration",
"<",
"?",
">",
"e",
"=",
"seq",
".",
"getObjects",
"(",
")",
";",
"this",
".",
"version",
"=",
"(",
"ASN1Integer",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"this",
".",
"digestAlgorithm",
"=",
"AlgorithmIdentifier",
".",
"getInstance",
"(",
"e",
".",
"nextElement",
"(",
")",
")",
";",
"this",
".",
"contentInfo",
"=",
"ContentInfo",
".",
"getInstance",
"(",
"e",
".",
"nextElement",
"(",
")",
")",
";",
"this",
".",
"digest",
"=",
"(",
"ASN1OctetString",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"}",
"/**\n * Recupera la versión del sistema de empaquetado PKCS#7.\n * @return Versión del empaquetado.\n */",
"public",
"String",
"getVersion",
"(",
")",
"{",
"return",
"this",
".",
"version",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Recupera el algoritmo de huella digital configurada para los empaquetados.\n * @return Algoritmo.\n */",
"public",
"String",
"getDigestAlgorithm",
"(",
")",
"{",
"return",
"this",
".",
"digestAlgorithm",
".",
"getAlgorithm",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"ASN1OctetString",
"getDigest",
"(",
")",
"{",
"return",
"this",
".",
"digest",
";",
"}",
"/**\n * Recupera el tipo de contenido.\n * @return Tipo de contenido.\n */",
"public",
"String",
"getContentType",
"(",
")",
"{",
"return",
"this",
".",
"contentInfo",
".",
"getContentType",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"/** Produce an object suitable for an ASN1OutputStream.\n *\n * <pre>\n * DigestedData ::= SEQUENCE {\n * version CMSVersion,\n * digestAlgorithms DigestAlgorithmIdentifiers,\n * encapContentInfo EncapsulatedContentInfo,\n * digest Digest\n * }\n *\n * Digest ::= OCTET STRING\n * </pre> */",
"@",
"Override",
"public",
"ASN1Primitive",
"toASN1Primitive",
"(",
")",
"{",
"final",
"ASN1EncodableVector",
"v",
"=",
"new",
"ASN1EncodableVector",
"(",
")",
";",
"v",
".",
"add",
"(",
"this",
".",
"version",
")",
";",
"v",
".",
"add",
"(",
"this",
".",
"digestAlgorithm",
")",
";",
"v",
".",
"add",
"(",
"this",
".",
"contentInfo",
")",
";",
"v",
".",
"add",
"(",
"this",
".",
"digest",
")",
";",
"return",
"new",
"BERSequence",
"(",
"v",
")",
";",
"}",
"}"
] | Clase base para la implementación del tipo DigestedData. | [
"Clase",
"base",
"para",
"la",
"implementació",
";",
"n",
"del",
"tipo",
"DigestedData",
"."
] | [
"//$NON-NLS-1$"
] | [
{
"param": "ASN1Encodable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ASN1Encodable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13b33308a83a92ff6219a052c1cc0f6750555c04 | yangxuQZhit/DesignPatternJava | src/J2EE/interceptingfilter/filter/DebugFilter.java | [
"MIT"
] | Java | DebugFilter | /**
* @ClassName DebugFilter
* @Description
* @Author yangxu
* @Date 2019-12-18 09:20
**/ | @ClassName DebugFilter
@Description
@Author yangxu
@Date 2019-12-18 09:20 | [
"@ClassName",
"DebugFilter",
"@Description",
"@Author",
"yangxu",
"@Date",
"2019",
"-",
"12",
"-",
"18",
"09",
":",
"20"
] | public class DebugFilter implements Filter {
@Override
public void execute(String request) {
System.out.println("request log: " + request);
}
} | [
"public",
"class",
"DebugFilter",
"implements",
"Filter",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
"String",
"request",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"request log: ",
"\"",
"+",
"request",
")",
";",
"}",
"}"
] | @ClassName DebugFilter
@Description
@Author yangxu
@Date 2019-12-18 09:20 | [
"@ClassName",
"DebugFilter",
"@Description",
"@Author",
"yangxu",
"@Date",
"2019",
"-",
"12",
"-",
"18",
"09",
":",
"20"
] | [] | [
{
"param": "Filter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Filter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13b4fdfdf0ca9fec8051ffb00894c52d7f5b8d1e | francois07/zuul-bad | pkg_commands/TalkCommand.java | [
"MIT"
] | Java | TalkCommand | /**
* Write a description of class TalkCommand here.
*
* @author (your name)
* @version (a version number or a date)
*/ | Write a description of class TalkCommand here.
@author (your name)
@version (a version number or a date) | [
"Write",
"a",
"description",
"of",
"class",
"TalkCommand",
"here",
".",
"@author",
"(",
"your",
"name",
")",
"@version",
"(",
"a",
"version",
"number",
"or",
"a",
"date",
")"
] | public class TalkCommand extends Command
{
public TalkCommand(){
}
public void execute(Player pP){
GameEngine vG = pP.getGameEngine();
UserInterface vU = vG.getGUI();
if( !this.hasSecondWord() ){
vU.println("Talk to who?");
return;
}
String vS = pP.talkTo(this.getSecondWord());
vU.println(vS);
}
} | [
"public",
"class",
"TalkCommand",
"extends",
"Command",
"{",
"public",
"TalkCommand",
"(",
")",
"{",
"}",
"public",
"void",
"execute",
"(",
"Player",
"pP",
")",
"{",
"GameEngine",
"vG",
"=",
"pP",
".",
"getGameEngine",
"(",
")",
";",
"UserInterface",
"vU",
"=",
"vG",
".",
"getGUI",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"hasSecondWord",
"(",
")",
")",
"{",
"vU",
".",
"println",
"(",
"\"",
"Talk to who?",
"\"",
")",
";",
"return",
";",
"}",
"String",
"vS",
"=",
"pP",
".",
"talkTo",
"(",
"this",
".",
"getSecondWord",
"(",
")",
")",
";",
"vU",
".",
"println",
"(",
"vS",
")",
";",
"}",
"}"
] | Write a description of class TalkCommand here. | [
"Write",
"a",
"description",
"of",
"class",
"TalkCommand",
"here",
"."
] | [] | [
{
"param": "Command",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Command",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13ba3e094094fe75917ddc1ad7d29cc05cb258f9 | AgenaRisk/api-example-app | src/main/java/example/legacy/DemoLegacy.java | [
"Linux-OpenIB"
] | Java | DemoLegacy | /**
* These examples correspond to the ones from AgenaRisk 10 Developer manual.
*
* @author Norman Fenton
* @author Eugene Dementiev
*/ | These examples correspond to the ones from AgenaRisk 10 Developer manual.
@author Norman Fenton
@author Eugene Dementiev | [
"These",
"examples",
"correspond",
"to",
"the",
"ones",
"from",
"AgenaRisk",
"10",
"Developer",
"manual",
".",
"@author",
"Norman",
"Fenton",
"@author",
"Eugene",
"Dementiev"
] | public class DemoLegacy {
public static void main(String args[]) {
DemoLegacy ex = new DemoLegacy();
ex.createSaveLoadSimpleModel();
ex.editStates();
ex.nptManipulation();
ex.learnTablesWithExpertJudgement();
ex.learnTablesWithExpertJudgementForIndividualNodes();
}
public void createSaveLoadSimpleModel() {
try {
Model myModel = Model.createEmptyModel();
// First get the single BN
ExtendedBN ebn = myModel.getExtendedBNAtIndex(0);
// Add a new node of type Boolean to this BN;
// its identifier is “b” ands its name is “B”
BooleanEN booleanNode = ebn.addBooleanNode("b", "B");
LabelledEN labelledNode = ebn.addLabelledNode("l", "L");
labelledNode.addChild(booleanNode);
myModel.calculate();
myModel.save("test.cmp");
Model m = Model.load("test.cmp");
} catch (Exception e) {
};
}
public void editStates() {
try {
Model m = Model.createEmptyModel();
// First get the single BN
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
LabelledEN len = ebn.addLabelledNode("l", "L");
BooleanEN ben = ebn.addBooleanNode("b", "B");
ContinuousIntervalEN cien = ebn.addContinuousIntervalNode("ci", "CI");
IntegerIntervalEN iien = ebn.addIntegerIntervalNode("ii", "II");
DiscreteRealEN dren = ebn.addDiscreteRealNode("dr", "DR");
RankedEN ren = ebn.addRankedNode("r", "R");
//Create DataSet object:
DataSet lds = new DataSet();
//Add the set of state names to lds:
lds.addLabelledDataPoint("Red");
lds.addLabelledDataPoint("Amber");
lds.addLabelledDataPoint("Green");
//Now completely redefine the set of states of len:
len.createExtendedStates(lds);
//For the Boolean node:
DataSet bds = new DataSet();
bds.addLabelledDataPoint("Yes");
bds.addLabelledDataPoint("No");
ben.createExtendedStates(bds);
//For the Continuous Interval Node:
DataSet cids = new DataSet();
cids.addIntervalDataPoint(0.0, 100.0);
cids.addIntervalDataPoint(100.0, 200.0);
cids.addIntervalDataPoint(200.0, 300.0);
cien.createExtendedStates(cids);
//For the Integer Interval Node:
DataSet iids = new DataSet();
iids.addIntervalDataPoint(10, 20);
iids.addIntervalDataPoint(20, 30);
iids.addIntervalDataPoint(30, 40);
iien.createExtendedStates(iids);
//For the Discrete Real Node:
DataSet drds = new DataSet();
drds.addAbsoluteDataPoint(1.0);
drds.addAbsoluteDataPoint(2.0);
drds.addAbsoluteDataPoint(3.0);
dren.createExtendedStates(drds);
//For the ranked node:
DataSet rds = new DataSet();
rds.addLabelledDataPoint("Bad");
rds.addLabelledDataPoint("OK");
rds.addLabelledDataPoint("Good");
ren.createExtendedStates(rds);
//Finally save the model
m.save("test.cmp");
} catch (Exception e) {
};
}
public void nptManipulation() {
try {
// Load the model that was created and saved
// in the method editStates
Model m = Model.load("test.cmp");
// Get the single BN
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Get the three of the nodes labelled B, L, and R.
//Note use of casting as the ebn.getExtendedNodewithName() method returns the ExtendedNode superclass:
BooleanEN ben = (BooleanEN) ebn.getExtendedNodeWithName("B");
LabelledEN len = (LabelledEN) ebn.getExtendedNodeWithName("L");
RankedEN ren = (RankedEN) ebn.getExtendedNodeWithName("R");
//Next we make nodes B (ben) and R (ren) parents of L (len):
len.addParent(ben);
len.addParent(ren);
//Next redefine the NPTs of nodes B and R to overwrite the default NPTs.
//These NPTs are easy because the nodes have no parents.
//B has two states so we need to define an array of length 2.
// R has three states so we need to define an array of length 3:
ben.setNPT(new double[]{0.9, 0.1});
ren.setNPT(new double[]{0.2, 0.3, 0.5});
//To redefine the NPT for the node L is harder because it has two parents (B and R)
//To generate this NPT we must first get the list of parents of L:
List lenParents = ebn.getParentNodes(len);
//Now we define the NPT of L:
len.setNPT(new double[][]{{0.7, 0.2, 0.1},
{0.5, 0.3, 0.2},
{0.3, 0.4, 0.3},
{0.1, 0.1, 0.8},
{0.3, 0.3, 0.4},
{0.5, 0.4, 0.1}}, lenParents);
//Save the model:
m.save("test.cmp");
} //try
catch (Exception e) {
};
} //nptManipulation
public void printMarginals(Model m, ExtendedBN ebn, ExtendedNode enode) {
// Get the Marginals for the node
MarginalDataItemList mdil
= m.getMarginalDataStore().getMarginalDataItemListForNode(ebn, enode);
// There’s only one scenario, so get the first
// MarginalDataItem in the list
MarginalDataItem mdi = mdil.getMarginalDataItemAtIndex(0);
// Now print out the node name and marginals
System.out.println(enode.getName().getShortDescription());
List marginals = mdi.getDataset().getDataPoints();
for (int i = 0; i < marginals.size(); i++) {
DataPoint marginal = (DataPoint) marginals.get(i);
System.out.println(marginal.getLabel()
+ " = "
+ marginal.getValue());
}
//Print the mean of the distribution
System.out.println("Mean = " + mdi.getMeanValue());
//get the variance of the distribution
System.out.println("Variance = " + mdi.getVarianceValue());
}
public void workingWithEvidence() {
try {
Model m = Model.load("test.cmp");
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Calculate the entire model:
m.calculate();
//get the node L
LabelledEN len = (LabelledEN) ebn.getExtendedNodeWithName("L");
//print the marginals and statistics for L
printMarginals(m, ebn, len);
//get the node CI
ContinuousIntervalEN cien = (ContinuousIntervalEN) ebn.getExtendedNodeWithName("CI");
//print the marginals and statistics for L
printMarginals(m, ebn, cien);
} catch (Exception e) {
};
} //workingWithEvidence
public void enteringEvidence() {
try {
Model m = Model.load("test.cmp");
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
m.calculate();
//get the node L whose NPT we created in the nptManipulation() method:
LabelledEN len = (LabelledEN) ebn.getExtendedNodeWithName("L");
//We are going to enter evidence on one of the parents of the node L.
//So, first we need to get one such parent, the Ranked node R:
RankedEN ren = (RankedEN) ebn.getExtendedNodeWithName("R");
//All evidence entry is done via “scenarios”
//(there is an enterEvidence() method associated with the ExtendedNode class but you should ignore this).
//So we need to get the single (default) scenario, which currently has no evidence:
Scenario s = m.getScenarioAtIndex(0);
//Now we enter hard evidence on node R (ren):
s.addHardEvidenceObservation(ebn.getId(), ren.getId(), ren.getExtendedStateAtIndex(2).getId());
//Now calculate again and print the marginals:
m.calculate();
printMarginals(m, ebn, len);
//Nex we show how to enter evidence for continuous nodes
//get the continuous node CI (cien):
ContinuousIntervalEN cien = (ContinuousIntervalEN) ebn.getExtendedNodeWithName("CI");
//Now enter a “real number” observation, 48.0, using the same scenario s:
s.addRealObservation(ebn.getId(), cien.getId(), 48.0);
//Note: For an Integer Interval node you would use the method addIntegerObservation().
//Calculate the model again and and print the marginals for the node CI (cien):
m.calculate();
printMarginals(m, ebn, cien);
//save the model:
m.save("test.cmp");
} catch (Exception e) {
};
} //enteringEvidence
public void testSimpleExpression() {
try {
// create a new model and get the single BN:
Model m = Model.createEmptyModel();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Add a new Continuous Interval node to this BN:
ContinuousIntervalEN a = ebn.addContinuousIntervalNode("a", "A");
//Redefine the states of node A as just a single state range from 0 to infinity:
DataSet cids = new DataSet();
cids.addIntervalDataPoint(0.0, Double.POSITIVE_INFINITY);
a.createExtendedStates(cids);
//make this node a simulation node by setting the node's simulation property to true:
a.setSimulationNode(true);
//define a Normal distribution as the expression for the NPT of this node:
List parameters = new ArrayList();
parameters.add("150"); // mean
parameters.add("100"); // variance
ExtendedNodeFunction enf = new ExtendedNodeFunction(Normal.displayName, parameters);
a.setExpression(enf);
//Now regenerate the NPT for this node:
ebn.regenerateNPT(a);
// setting the number of iterations (the default is 25 if you do not set it explicitly)
m.setSimulationNoOfIterations(30);
//Calculate the entire model:
m.calculate();
//Use the printMarginals() method defined above to print out the marginals:
printMarginals(m, ebn, a);
//save the model so you can inspect it in AgenaRisk:
m.save("test2.cmp");
} catch (Exception e) {
};
}//testSimpleExpression
public void testExpressionWithParent() {
try {
// create a new model and get the single BN:
Model m = Model.createEmptyModel();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Create three Continuous Interval nodes, A and B, and C:
ContinuousIntervalEN a = ebn.addContinuousIntervalNode("a", "A");
ContinuousIntervalEN b = ebn.addContinuousIntervalNode("b", "B");
ContinuousIntervalEN c = ebn.addContinuousIntervalNode("c", "C");
//Redefine the states of each node as just a single state range from 0 to infinity
DataSet cids = new DataSet();
cids.addIntervalDataPoint(0.0, Double.POSITIVE_INFINITY);
a.createExtendedStates(cids);
b.createExtendedStates(cids);
c.createExtendedStates(cids);
//Make C the child of both A and B:
a.addChild(c);
b.addChild(c);
//Make all nodes simulation nodes:
a.setSimulationNode(true);
b.setSimulationNode(true);
c.setSimulationNode(true);
//Define the NPTs of A and B to be Uniform:
List uniformParameters = new ArrayList();
uniformParameters.add("0.0"); //lower bound
uniformParameters.add("10000000000.0"); //upper bound
ExtendedNodeFunction uniform
= new ExtendedNodeFunction(Uniform.displayName, uniformParameters);
a.setExpression(uniform);
b.setExpression(uniform);
//Define the NPT of C as an arithmetic expression of the parents (we use a simple sum):
List parameters = new ArrayList();
parameters.add("a + b");
ExtendedNodeFunction enf = new ExtendedNodeFunction(Arithmetic.displayName, parameters);
c.setExpression(enf);
//regenerate the NPTs:
ebn.regenerateNPT(a);
ebn.regenerateNPT(b);
ebn.regenerateNPT(c);
//Calculate the entire model and print the marginals:
m.calculate();
printMarginals(m, ebn, c);
//Now enter observations for A and B. First we get the single Scenario:
Scenario s = m.getScenarioAtIndex(0);
s.addRealObservation(ebn.getId(), a.getId(), 33.0);
s.addRealObservation(ebn.getId(), b.getId(), 44.0);
//Calculate again:
m.calculate();
printMarginals(m, ebn, c);
//Save the model:
m.save("test3.cmp");
} catch (Exception e) {
};
}//testExpressionWithParent
public void testPartitionedExpression() {
try {
// create a new model and get the single BN:
Model m = Model.createEmptyModel();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
// Create a Labelled node, A, and set up new states for it:
LabelledEN a = ebn.addLabelledNode("a", "A");
DataSet lds = new DataSet();
lds.addLabelledDataPoint("Red");
lds.addLabelledDataPoint("Amber");
lds.addLabelledDataPoint("Green");
a.createExtendedStates(lds);
//Create a Continuous Interval node, B:
ContinuousIntervalEN b = ebn.addContinuousIntervalNode("b", "B");
//Make it a child of A:
a.addChild(b);
//Make it a simulation node:
b.setSimulationNode(true);
//Set the new state range to be 0 to infinity:
DataSet cids = new DataSet();
cids.addIntervalDataPoint(0.0, Double.POSITIVE_INFINITY);
b.createExtendedStates(cids);
//Make A a model node of B:
List modelNodes = new ArrayList();
b.setPartitionedExpressionModelNodes(modelNodes);
modelNodes.add(a);
//Next we create a partitioned expression for each state of A.
//First we need a List to store the expressions we will create:
List expressions = new ArrayList();
b.setPartitionedExpressions(expressions);
//Create the expression Normal(10, 100) for the first state (Red):
List redParameters = new ArrayList();
redParameters.add("10");
redParameters.add("100");
expressions.add(new ExtendedNodeFunction(Normal.displayName, redParameters));
//Create the expression Normal(25, 100) for second state (Amber):
List amberParameters = new ArrayList();
amberParameters.add("25");
amberParameters.add("100");
expressions.add(new ExtendedNodeFunction(Normal.displayName, amberParameters));
//Create the expression Normal(40, 100) for third state (Green):
List greenParameters = new ArrayList();
greenParameters.add("40");
greenParameters.add("100");
expressions.add(new ExtendedNodeFunction(Normal.displayName, greenParameters));
//Now regenerate the NPT for B:
ebn.regenerateNPT(b);
//Calculate the entire model and print the marginals:
m.calculate();
printMarginals(m, ebn, b);
//Next we will add observations, so we need to get the single scenario:
Scenario s = m.getScenarioAtIndex(0);
//Enter observation Red, calculate and view the marginals:
s.addHardEvidenceObservation(ebn.getId(), a.getId(), a.getExtendedStateAtIndex(0).getId());
m.calculate();
printMarginals(m, ebn, b);
//Enter observation Amber, calculate and view the marginals:
s.addHardEvidenceObservation(ebn.getId(), a.getId(), a.getExtendedStateAtIndex(1).getId());
m.calculate();
printMarginals(m, ebn, b);
//Enter observation Green, calculate and view the marginals:
s.addHardEvidenceObservation(ebn.getId(), a.getId(), a.getExtendedStateAtIndex(2).getId());
m.calculate();
printMarginals(m, ebn, b);
//save the file:
m.save("test4.cmp");
} catch (Exception e) {
};
}//testPartitionedExpression
public void testBNOs() {
try {
// create an empty model and get the existing BN:
Model m = Model.createEmptyModel();
ExtendedBN one = m.getExtendedBNAtIndex(0);
//Rename the existing BN
NameDescription name = new NameDescription("One", "First BN");
one.setName(name);
//This time we want to create a new BN called “Two”:
ExtendedBN two = m.addExtendedBN("Two", "Second BN");
//Use method populateSimpleExtendedBN to populate both BNs:
populateSimpleExtendedBN(one);
populateSimpleExtendedBN(two);
//get the node A in BN “One” and set it as an output node:
ExtendedNode source = one.getExtendedNodeWithUniqueIdentifier("a");
source.setConnectableOutputNode(true);
//Get the node A in BN “Two” and set it as an input node:
ExtendedNode target = two.getExtendedNodeWithUniqueIdentifier("a");
target.setConnectableInputNode(true);
//Link the two nodes (and, thus, the two BNs)
m.link(source, target);
//Add an observation to c in BN "one":
Scenario s = m.getScenarioAtIndex(0);
s.addRealObservation(one.getId(), one.getExtendedNodeWithUniqueIdentifier("c").getId(), 30.0);
//Calculate and print the marginals of a in both BNs:
m.calculate();
printMarginals(m, one, one.getExtendedNodeWithUniqueIdentifier("a"));
printMarginals(m, two, two.getExtendedNodeWithUniqueIdentifier("a"));
//save the model
m.save("test5.cmp");
} catch (Exception e) {
};
}//testBNOs
private void populateSimpleExtendedBN(ExtendedBN ebn) throws Exception {
// Create two nodes, A and B, and a child C
ContinuousIntervalEN a = ebn.addContinuousIntervalNode("a", "A");
ContinuousIntervalEN b = ebn.addContinuousIntervalNode("b", "B");
ContinuousIntervalEN c = ebn.addContinuousIntervalNode("c", "C");
a.addChild(c);
b.addChild(c);
List parameters = new ArrayList();
parameters.add("a + b");
ExtendedNodeFunction enf = new ExtendedNodeFunction(
Arithmetic.displayName, parameters);
c.setExpression(enf);
//For the node c redefine its states
DataSet cids = new DataSet();
cids.addIntervalDataPoint(0.0, 10.0);
cids.addIntervalDataPoint(10.0, 20.0);
cids.addIntervalDataPoint(20.0, 30.0);
cids.addIntervalDataPoint(30.0, 40.0);
c.createExtendedStates(cids);
// Now regenerate the NPT for C
ebn.regenerateNPT(a);
ebn.regenerateNPT(b);
ebn.regenerateNPT(c);
} //populateSimpleExtendedBN
private void printNPTs(ExtendedBN ebn) {
System.out.println("=======================");
((List<ExtendedNode>) ebn.getExtendedNodes())
.stream()
.forEach(e -> {
System.out.println(e.getConnNodeId() + " " + e + " " + e.getConfidence());
try {
System.out.println(Arrays.deepToString(e.getNPT()));
} catch (ExtendedBNException ex) {
}
});
}
/**
* Demonstrates generating example data file.
*
* @throws Exception
*/
private void generateExampleDataFile() {
try {
//Load example model
Path examplesDirectoryPath = Paths.get(Config.getDirectoryHomeAgenaRisk(), "Model Library", "Advanced", "Learning from Data");
Model m = Model.load(Paths.get(examplesDirectoryPath.toString(), "Asia.ast").toString());
//Prepare data path
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Number of data rows to be generated
int numberOfDataSamplesToGenerate = 10;
//File name for example data
File dataFile = new File("data_example.csv");
//Initialize generator
SampleDataGenerator generator = new SampleDataGenerator();
//Generate data
List sampleData = generator.generateDataForEBN(ebn, numberOfDataSamplesToGenerate, true, null);
//Save generated data to a file
try (CSVWriter writer = new CSVWriter(new BufferedWriter(new FileWriter(dataFile)), ',', '\0')) {
writer.writeAll(sampleData);
} catch (IOException ex) {
//custom exception handling for problems with saving data file
}
} catch (FileHandlingException ex) {
//custom exception handling for problems with saving data file
}
}
/**
* Demonstrates learning purely from data.
*
* @throws Exception
*/
private void learnTablesPurelyFromData() {
try {
//Load example model
Path examplesDirectoryPath = Paths.get(Config.getDirectoryHomeAgenaRisk(), "Model Library", "Advanced", "Learning from Data");
Model m = Model.load(Paths.get(examplesDirectoryPath.toString(), "Asia.ast").toString());
//Prepare data path
String dataFileName = Paths.get(examplesDirectoryPath.toString(), "Asia - example dataset.csv").toString();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Print NPTs
printNPTs(ebn);
//Read in data
Data data = new Data(dataFileName, "NA");
//If the values in the data file are separated not by a comma, you can provide custom separator
data = new Data(dataFileName, "NA", ",");
//If the learning process should be logged turn it on
m.setEMLogging(true);
//Set up EMCal object
Model.EM_ON = true;
EMCal emcal = new EMCal(m, ebn, data, "NA", dataFileName, new ArrayList(), false);
emcal.setMaxIterations(25);
emcal.threshold = 0.01;
//emcal.laplacian = 0;
//Start calculations
emcal.calculateEM();
//Print NPTs
printNPTs(ebn);
//Save learnt model
m.save("model_learnt_purely_from_data.cmp");
} catch (FileHandlingException | IOException | CoreBNException | CoreBNInconsistentEvidenceException | PropagationException | MessagePassingLinkException | PropagationTerminatedException ex) {
//custom exception handling
} catch (InconsistentDataVsModelStatesException ex) {
//custom exception handling
} catch (ExtendedBNException ex) {
//custom exception handling
}
catch (EMLearningException ex) {
//custom exception handling
}
}
/**
* Demonstrates learning from data and expert judgement (set at the level of
* ExtendedBN)
*/
private void learnTablesWithExpertJudgement() {
try {
//Load example model
Path examplesDirectoryPath = Paths.get(Config.getDirectoryHomeAgenaRisk(), "Model Library", "Advanced", "Learning from Data");
Model m = Model.load(Paths.get(examplesDirectoryPath.toString(), "Asia.ast").toString());
//Prepare data path
String dataFileName = Paths.get(examplesDirectoryPath.toString(), "Asia - example dataset.csv").toString();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Print NPTs
printNPTs(ebn);
//Read in data
Data data = new Data(dataFileName, "NA");
//If the learning process should be logged turn it on
m.setEMLogging(true);
//set confidence
ebn.setConfidence(0.5);
//Set up EMCal object
Model.EM_ON = true;
EMCal emcal = new EMCal(m, ebn, data, "NA", dataFileName, Arrays.asList("TBoC"), false);
emcal.setMaxIterations(25);
emcal.threshold = 0.01;
//emcal.laplacian = 0;
//Start calculations
emcal.calculateEM();
//Print NPTs
printNPTs(ebn);
//Save learnt model
m.save("model_learnt_from_data_and_expert_judgement.cmp");
} catch (FileHandlingException | IOException | CoreBNException | CoreBNInconsistentEvidenceException | PropagationException | MessagePassingLinkException | PropagationTerminatedException ex) {
//custom exception handling
} catch (InconsistentDataVsModelStatesException ex) {
//custom exception handling
} catch (ExtendedBNException ex) {
//custom exception handling
} catch (EMLearningException ex) {
//custom exception handling
}
}
/**
* Demonstrates learning from data and expert judgement (set at the level of
* individual nodes)
*/
private void learnTablesWithExpertJudgementForIndividualNodes() {
try {
//Load example model
Path examplesDirectoryPath = Paths.get(Config.getDirectoryHomeAgenaRisk(), "Model Library", "Advanced", "Learning from Data");
Model m = Model.load(Paths.get(examplesDirectoryPath.toString(), "Asia.ast").toString());
//Prepare data path
String dataFileName = Paths.get(examplesDirectoryPath.toString(), "Asia - example dataset.csv").toString();
ExtendedBN ebn = m.getExtendedBNAtIndex(0);
//Print NPTs
printNPTs(ebn);
//Read in data
Data data = new Data(dataFileName, "NA");
//If the learning process should be logged turn it on
m.setEMLogging(true);
//set confidence
//globally as default for the whole ExtendedBN
ebn.setConfidence(0.5);
//only from data
ebn.getExtendedNodeWithUniqueIdentifier("D").setConfidence(0);
//knowledge is 3x more important than data
ebn.getExtendedNodeWithUniqueIdentifier("B").setConfidence(0.75);
//100% knowledge, do not learn
ebn.getExtendedNodeWithUniqueIdentifier("L").setConfidence(1);
//use the default confidence for the whole ExtendedBN but make it a fixed node
ebn.getExtendedNodeWithUniqueIdentifier("T").setConfidence(-1);
List<String> fixedNodes = new ArrayList();
fixedNodes.add("T");
//try to assign a value form outside possible range
ebn.getExtendedNodeWithUniqueIdentifier("A").setConfidence(1.3);
//check confidence for individual nodes
((List<ExtendedNode>) ebn.getExtendedNodes())
.stream()
.forEach(e -> System.out.println(e.getConnNodeId() + " " + e + " " + e.getConfidence()));
//Set up EMCal object
Model.EM_ON = true;
EMCal emcal = new EMCal(m, ebn, data, "NA", dataFileName, Arrays.asList("TBoC"), false);
emcal.setMaxIterations(25);
emcal.threshold = 0.01;
//emcal.laplacian = 0;
emcal.setFixedNodes(fixedNodes);
//Start calculations
emcal.calculateEM();
//Print NPTs
printNPTs(ebn);
//Save learnt model
m.save("model_learnt_from_data_and_expert_judgement_individual_nodes.cmp");
} catch (FileHandlingException | IOException | CoreBNException | CoreBNInconsistentEvidenceException | PropagationException | MessagePassingLinkException | PropagationTerminatedException ex) {
//custom exception handling
} catch (InconsistentDataVsModelStatesException ex) {
//custom exception handling
} catch (ExtendedBNException ex) {
//custom exception handling
} catch (EMLearningException ex) {
//custom exception handling
}
}
} | [
"public",
"class",
"DemoLegacy",
"{",
"public",
"static",
"void",
"main",
"(",
"String",
"args",
"[",
"]",
")",
"{",
"DemoLegacy",
"ex",
"=",
"new",
"DemoLegacy",
"(",
")",
";",
"ex",
".",
"createSaveLoadSimpleModel",
"(",
")",
";",
"ex",
".",
"editStates",
"(",
")",
";",
"ex",
".",
"nptManipulation",
"(",
")",
";",
"ex",
".",
"learnTablesWithExpertJudgement",
"(",
")",
";",
"ex",
".",
"learnTablesWithExpertJudgementForIndividualNodes",
"(",
")",
";",
"}",
"public",
"void",
"createSaveLoadSimpleModel",
"(",
")",
"{",
"try",
"{",
"Model",
"myModel",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"myModel",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"BooleanEN",
"booleanNode",
"=",
"ebn",
".",
"addBooleanNode",
"(",
"\"",
"b",
"\"",
",",
"\"",
"B",
"\"",
")",
";",
"LabelledEN",
"labelledNode",
"=",
"ebn",
".",
"addLabelledNode",
"(",
"\"",
"l",
"\"",
",",
"\"",
"L",
"\"",
")",
";",
"labelledNode",
".",
"addChild",
"(",
"booleanNode",
")",
";",
"myModel",
".",
"calculate",
"(",
")",
";",
"myModel",
".",
"save",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"editStates",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"LabelledEN",
"len",
"=",
"ebn",
".",
"addLabelledNode",
"(",
"\"",
"l",
"\"",
",",
"\"",
"L",
"\"",
")",
";",
"BooleanEN",
"ben",
"=",
"ebn",
".",
"addBooleanNode",
"(",
"\"",
"b",
"\"",
",",
"\"",
"B",
"\"",
")",
";",
"ContinuousIntervalEN",
"cien",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"ci",
"\"",
",",
"\"",
"CI",
"\"",
")",
";",
"IntegerIntervalEN",
"iien",
"=",
"ebn",
".",
"addIntegerIntervalNode",
"(",
"\"",
"ii",
"\"",
",",
"\"",
"II",
"\"",
")",
";",
"DiscreteRealEN",
"dren",
"=",
"ebn",
".",
"addDiscreteRealNode",
"(",
"\"",
"dr",
"\"",
",",
"\"",
"DR",
"\"",
")",
";",
"RankedEN",
"ren",
"=",
"ebn",
".",
"addRankedNode",
"(",
"\"",
"r",
"\"",
",",
"\"",
"R",
"\"",
")",
";",
"DataSet",
"lds",
"=",
"new",
"DataSet",
"(",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Red",
"\"",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Amber",
"\"",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Green",
"\"",
")",
";",
"len",
".",
"createExtendedStates",
"(",
"lds",
")",
";",
"DataSet",
"bds",
"=",
"new",
"DataSet",
"(",
")",
";",
"bds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Yes",
"\"",
")",
";",
"bds",
".",
"addLabelledDataPoint",
"(",
"\"",
"No",
"\"",
")",
";",
"ben",
".",
"createExtendedStates",
"(",
"bds",
")",
";",
"DataSet",
"cids",
"=",
"new",
"DataSet",
"(",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"0.0",
",",
"100.0",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"100.0",
",",
"200.0",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"200.0",
",",
"300.0",
")",
";",
"cien",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"DataSet",
"iids",
"=",
"new",
"DataSet",
"(",
")",
";",
"iids",
".",
"addIntervalDataPoint",
"(",
"10",
",",
"20",
")",
";",
"iids",
".",
"addIntervalDataPoint",
"(",
"20",
",",
"30",
")",
";",
"iids",
".",
"addIntervalDataPoint",
"(",
"30",
",",
"40",
")",
";",
"iien",
".",
"createExtendedStates",
"(",
"iids",
")",
";",
"DataSet",
"drds",
"=",
"new",
"DataSet",
"(",
")",
";",
"drds",
".",
"addAbsoluteDataPoint",
"(",
"1.0",
")",
";",
"drds",
".",
"addAbsoluteDataPoint",
"(",
"2.0",
")",
";",
"drds",
".",
"addAbsoluteDataPoint",
"(",
"3.0",
")",
";",
"dren",
".",
"createExtendedStates",
"(",
"drds",
")",
";",
"DataSet",
"rds",
"=",
"new",
"DataSet",
"(",
")",
";",
"rds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Bad",
"\"",
")",
";",
"rds",
".",
"addLabelledDataPoint",
"(",
"\"",
"OK",
"\"",
")",
";",
"rds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Good",
"\"",
")",
";",
"ren",
".",
"createExtendedStates",
"(",
"rds",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"nptManipulation",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"BooleanEN",
"ben",
"=",
"(",
"BooleanEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"B",
"\"",
")",
";",
"LabelledEN",
"len",
"=",
"(",
"LabelledEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"L",
"\"",
")",
";",
"RankedEN",
"ren",
"=",
"(",
"RankedEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"R",
"\"",
")",
";",
"len",
".",
"addParent",
"(",
"ben",
")",
";",
"len",
".",
"addParent",
"(",
"ren",
")",
";",
"ben",
".",
"setNPT",
"(",
"new",
"double",
"[",
"]",
"{",
"0.9",
",",
"0.1",
"}",
")",
";",
"ren",
".",
"setNPT",
"(",
"new",
"double",
"[",
"]",
"{",
"0.2",
",",
"0.3",
",",
"0.5",
"}",
")",
";",
"List",
"lenParents",
"=",
"ebn",
".",
"getParentNodes",
"(",
"len",
")",
";",
"len",
".",
"setNPT",
"(",
"new",
"double",
"[",
"]",
"[",
"]",
"{",
"{",
"0.7",
",",
"0.2",
",",
"0.1",
"}",
",",
"{",
"0.5",
",",
"0.3",
",",
"0.2",
"}",
",",
"{",
"0.3",
",",
"0.4",
",",
"0.3",
"}",
",",
"{",
"0.1",
",",
"0.1",
",",
"0.8",
"}",
",",
"{",
"0.3",
",",
"0.3",
",",
"0.4",
"}",
",",
"{",
"0.5",
",",
"0.4",
",",
"0.1",
"}",
"}",
",",
"lenParents",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"printMarginals",
"(",
"Model",
"m",
",",
"ExtendedBN",
"ebn",
",",
"ExtendedNode",
"enode",
")",
"{",
"MarginalDataItemList",
"mdil",
"=",
"m",
".",
"getMarginalDataStore",
"(",
")",
".",
"getMarginalDataItemListForNode",
"(",
"ebn",
",",
"enode",
")",
";",
"MarginalDataItem",
"mdi",
"=",
"mdil",
".",
"getMarginalDataItemAtIndex",
"(",
"0",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"enode",
".",
"getName",
"(",
")",
".",
"getShortDescription",
"(",
")",
")",
";",
"List",
"marginals",
"=",
"mdi",
".",
"getDataset",
"(",
")",
".",
"getDataPoints",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"marginals",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"DataPoint",
"marginal",
"=",
"(",
"DataPoint",
")",
"marginals",
".",
"get",
"(",
"i",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"marginal",
".",
"getLabel",
"(",
")",
"+",
"\"",
" = ",
"\"",
"+",
"marginal",
".",
"getValue",
"(",
")",
")",
";",
"}",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Mean = ",
"\"",
"+",
"mdi",
".",
"getMeanValue",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Variance = ",
"\"",
"+",
"mdi",
".",
"getVarianceValue",
"(",
")",
")",
";",
"}",
"public",
"void",
"workingWithEvidence",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"LabelledEN",
"len",
"=",
"(",
"LabelledEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"L",
"\"",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"len",
")",
";",
"ContinuousIntervalEN",
"cien",
"=",
"(",
"ContinuousIntervalEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"CI",
"\"",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"cien",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"enteringEvidence",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"LabelledEN",
"len",
"=",
"(",
"LabelledEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"L",
"\"",
")",
";",
"RankedEN",
"ren",
"=",
"(",
"RankedEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"R",
"\"",
")",
";",
"Scenario",
"s",
"=",
"m",
".",
"getScenarioAtIndex",
"(",
"0",
")",
";",
"s",
".",
"addHardEvidenceObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"ren",
".",
"getId",
"(",
")",
",",
"ren",
".",
"getExtendedStateAtIndex",
"(",
"2",
")",
".",
"getId",
"(",
")",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"len",
")",
";",
"ContinuousIntervalEN",
"cien",
"=",
"(",
"ContinuousIntervalEN",
")",
"ebn",
".",
"getExtendedNodeWithName",
"(",
"\"",
"CI",
"\"",
")",
";",
"s",
".",
"addRealObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"cien",
".",
"getId",
"(",
")",
",",
"48.0",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"cien",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"testSimpleExpression",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"ContinuousIntervalEN",
"a",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"a",
"\"",
",",
"\"",
"A",
"\"",
")",
";",
"DataSet",
"cids",
"=",
"new",
"DataSet",
"(",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"0.0",
",",
"Double",
".",
"POSITIVE_INFINITY",
")",
";",
"a",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"a",
".",
"setSimulationNode",
"(",
"true",
")",
";",
"List",
"parameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"\"",
"150",
"\"",
")",
";",
"parameters",
".",
"add",
"(",
"\"",
"100",
"\"",
")",
";",
"ExtendedNodeFunction",
"enf",
"=",
"new",
"ExtendedNodeFunction",
"(",
"Normal",
".",
"displayName",
",",
"parameters",
")",
";",
"a",
".",
"setExpression",
"(",
"enf",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"a",
")",
";",
"m",
".",
"setSimulationNoOfIterations",
"(",
"30",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"a",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test2.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"testExpressionWithParent",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"ContinuousIntervalEN",
"a",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"a",
"\"",
",",
"\"",
"A",
"\"",
")",
";",
"ContinuousIntervalEN",
"b",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"b",
"\"",
",",
"\"",
"B",
"\"",
")",
";",
"ContinuousIntervalEN",
"c",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"c",
"\"",
",",
"\"",
"C",
"\"",
")",
";",
"DataSet",
"cids",
"=",
"new",
"DataSet",
"(",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"0.0",
",",
"Double",
".",
"POSITIVE_INFINITY",
")",
";",
"a",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"b",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"c",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"a",
".",
"addChild",
"(",
"c",
")",
";",
"b",
".",
"addChild",
"(",
"c",
")",
";",
"a",
".",
"setSimulationNode",
"(",
"true",
")",
";",
"b",
".",
"setSimulationNode",
"(",
"true",
")",
";",
"c",
".",
"setSimulationNode",
"(",
"true",
")",
";",
"List",
"uniformParameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"uniformParameters",
".",
"add",
"(",
"\"",
"0.0",
"\"",
")",
";",
"uniformParameters",
".",
"add",
"(",
"\"",
"10000000000.0",
"\"",
")",
";",
"ExtendedNodeFunction",
"uniform",
"=",
"new",
"ExtendedNodeFunction",
"(",
"Uniform",
".",
"displayName",
",",
"uniformParameters",
")",
";",
"a",
".",
"setExpression",
"(",
"uniform",
")",
";",
"b",
".",
"setExpression",
"(",
"uniform",
")",
";",
"List",
"parameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"\"",
"a + b",
"\"",
")",
";",
"ExtendedNodeFunction",
"enf",
"=",
"new",
"ExtendedNodeFunction",
"(",
"Arithmetic",
".",
"displayName",
",",
"parameters",
")",
";",
"c",
".",
"setExpression",
"(",
"enf",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"a",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"b",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"c",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"c",
")",
";",
"Scenario",
"s",
"=",
"m",
".",
"getScenarioAtIndex",
"(",
"0",
")",
";",
"s",
".",
"addRealObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"a",
".",
"getId",
"(",
")",
",",
"33.0",
")",
";",
"s",
".",
"addRealObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"b",
".",
"getId",
"(",
")",
",",
"44.0",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"c",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test3.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"testPartitionedExpression",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"LabelledEN",
"a",
"=",
"ebn",
".",
"addLabelledNode",
"(",
"\"",
"a",
"\"",
",",
"\"",
"A",
"\"",
")",
";",
"DataSet",
"lds",
"=",
"new",
"DataSet",
"(",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Red",
"\"",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Amber",
"\"",
")",
";",
"lds",
".",
"addLabelledDataPoint",
"(",
"\"",
"Green",
"\"",
")",
";",
"a",
".",
"createExtendedStates",
"(",
"lds",
")",
";",
"ContinuousIntervalEN",
"b",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"b",
"\"",
",",
"\"",
"B",
"\"",
")",
";",
"a",
".",
"addChild",
"(",
"b",
")",
";",
"b",
".",
"setSimulationNode",
"(",
"true",
")",
";",
"DataSet",
"cids",
"=",
"new",
"DataSet",
"(",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"0.0",
",",
"Double",
".",
"POSITIVE_INFINITY",
")",
";",
"b",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"List",
"modelNodes",
"=",
"new",
"ArrayList",
"(",
")",
";",
"b",
".",
"setPartitionedExpressionModelNodes",
"(",
"modelNodes",
")",
";",
"modelNodes",
".",
"add",
"(",
"a",
")",
";",
"List",
"expressions",
"=",
"new",
"ArrayList",
"(",
")",
";",
"b",
".",
"setPartitionedExpressions",
"(",
"expressions",
")",
";",
"List",
"redParameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"redParameters",
".",
"add",
"(",
"\"",
"10",
"\"",
")",
";",
"redParameters",
".",
"add",
"(",
"\"",
"100",
"\"",
")",
";",
"expressions",
".",
"add",
"(",
"new",
"ExtendedNodeFunction",
"(",
"Normal",
".",
"displayName",
",",
"redParameters",
")",
")",
";",
"List",
"amberParameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"amberParameters",
".",
"add",
"(",
"\"",
"25",
"\"",
")",
";",
"amberParameters",
".",
"add",
"(",
"\"",
"100",
"\"",
")",
";",
"expressions",
".",
"add",
"(",
"new",
"ExtendedNodeFunction",
"(",
"Normal",
".",
"displayName",
",",
"amberParameters",
")",
")",
";",
"List",
"greenParameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"greenParameters",
".",
"add",
"(",
"\"",
"40",
"\"",
")",
";",
"greenParameters",
".",
"add",
"(",
"\"",
"100",
"\"",
")",
";",
"expressions",
".",
"add",
"(",
"new",
"ExtendedNodeFunction",
"(",
"Normal",
".",
"displayName",
",",
"greenParameters",
")",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"b",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"b",
")",
";",
"Scenario",
"s",
"=",
"m",
".",
"getScenarioAtIndex",
"(",
"0",
")",
";",
"s",
".",
"addHardEvidenceObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"a",
".",
"getId",
"(",
")",
",",
"a",
".",
"getExtendedStateAtIndex",
"(",
"0",
")",
".",
"getId",
"(",
")",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"b",
")",
";",
"s",
".",
"addHardEvidenceObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"a",
".",
"getId",
"(",
")",
",",
"a",
".",
"getExtendedStateAtIndex",
"(",
"1",
")",
".",
"getId",
"(",
")",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"b",
")",
";",
"s",
".",
"addHardEvidenceObservation",
"(",
"ebn",
".",
"getId",
"(",
")",
",",
"a",
".",
"getId",
"(",
")",
",",
"a",
".",
"getExtendedStateAtIndex",
"(",
"2",
")",
".",
"getId",
"(",
")",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"ebn",
",",
"b",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test4.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"public",
"void",
"testBNOs",
"(",
")",
"{",
"try",
"{",
"Model",
"m",
"=",
"Model",
".",
"createEmptyModel",
"(",
")",
";",
"ExtendedBN",
"one",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"NameDescription",
"name",
"=",
"new",
"NameDescription",
"(",
"\"",
"One",
"\"",
",",
"\"",
"First BN",
"\"",
")",
";",
"one",
".",
"setName",
"(",
"name",
")",
";",
"ExtendedBN",
"two",
"=",
"m",
".",
"addExtendedBN",
"(",
"\"",
"Two",
"\"",
",",
"\"",
"Second BN",
"\"",
")",
";",
"populateSimpleExtendedBN",
"(",
"one",
")",
";",
"populateSimpleExtendedBN",
"(",
"two",
")",
";",
"ExtendedNode",
"source",
"=",
"one",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"a",
"\"",
")",
";",
"source",
".",
"setConnectableOutputNode",
"(",
"true",
")",
";",
"ExtendedNode",
"target",
"=",
"two",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"a",
"\"",
")",
";",
"target",
".",
"setConnectableInputNode",
"(",
"true",
")",
";",
"m",
".",
"link",
"(",
"source",
",",
"target",
")",
";",
"Scenario",
"s",
"=",
"m",
".",
"getScenarioAtIndex",
"(",
"0",
")",
";",
"s",
".",
"addRealObservation",
"(",
"one",
".",
"getId",
"(",
")",
",",
"one",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"c",
"\"",
")",
".",
"getId",
"(",
")",
",",
"30.0",
")",
";",
"m",
".",
"calculate",
"(",
")",
";",
"printMarginals",
"(",
"m",
",",
"one",
",",
"one",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"a",
"\"",
")",
")",
";",
"printMarginals",
"(",
"m",
",",
"two",
",",
"two",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"a",
"\"",
")",
")",
";",
"m",
".",
"save",
"(",
"\"",
"test5.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
";",
"}",
"private",
"void",
"populateSimpleExtendedBN",
"(",
"ExtendedBN",
"ebn",
")",
"throws",
"Exception",
"{",
"ContinuousIntervalEN",
"a",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"a",
"\"",
",",
"\"",
"A",
"\"",
")",
";",
"ContinuousIntervalEN",
"b",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"b",
"\"",
",",
"\"",
"B",
"\"",
")",
";",
"ContinuousIntervalEN",
"c",
"=",
"ebn",
".",
"addContinuousIntervalNode",
"(",
"\"",
"c",
"\"",
",",
"\"",
"C",
"\"",
")",
";",
"a",
".",
"addChild",
"(",
"c",
")",
";",
"b",
".",
"addChild",
"(",
"c",
")",
";",
"List",
"parameters",
"=",
"new",
"ArrayList",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"\"",
"a + b",
"\"",
")",
";",
"ExtendedNodeFunction",
"enf",
"=",
"new",
"ExtendedNodeFunction",
"(",
"Arithmetic",
".",
"displayName",
",",
"parameters",
")",
";",
"c",
".",
"setExpression",
"(",
"enf",
")",
";",
"DataSet",
"cids",
"=",
"new",
"DataSet",
"(",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"0.0",
",",
"10.0",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"10.0",
",",
"20.0",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"20.0",
",",
"30.0",
")",
";",
"cids",
".",
"addIntervalDataPoint",
"(",
"30.0",
",",
"40.0",
")",
";",
"c",
".",
"createExtendedStates",
"(",
"cids",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"a",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"b",
")",
";",
"ebn",
".",
"regenerateNPT",
"(",
"c",
")",
";",
"}",
"private",
"void",
"printNPTs",
"(",
"ExtendedBN",
"ebn",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"=======================",
"\"",
")",
";",
"(",
"(",
"List",
"<",
"ExtendedNode",
">",
")",
"ebn",
".",
"getExtendedNodes",
"(",
")",
")",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"e",
"->",
"{",
"System",
".",
"out",
".",
"println",
"(",
"e",
".",
"getConnNodeId",
"(",
")",
"+",
"\"",
" ",
"\"",
"+",
"e",
"+",
"\"",
" ",
"\"",
"+",
"e",
".",
"getConfidence",
"(",
")",
")",
";",
"try",
"{",
"System",
".",
"out",
".",
"println",
"(",
"Arrays",
".",
"deepToString",
"(",
"e",
".",
"getNPT",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"ExtendedBNException",
"ex",
")",
"{",
"}",
"}",
")",
";",
"}",
"/**\n * Demonstrates generating example data file.\n *\n * @throws Exception\n */",
"private",
"void",
"generateExampleDataFile",
"(",
")",
"{",
"try",
"{",
"Path",
"examplesDirectoryPath",
"=",
"Paths",
".",
"get",
"(",
"Config",
".",
"getDirectoryHomeAgenaRisk",
"(",
")",
",",
"\"",
"Model Library",
"\"",
",",
"\"",
"Advanced",
"\"",
",",
"\"",
"Learning from Data",
"\"",
")",
";",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia.ast",
"\"",
")",
".",
"toString",
"(",
")",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"int",
"numberOfDataSamplesToGenerate",
"=",
"10",
";",
"File",
"dataFile",
"=",
"new",
"File",
"(",
"\"",
"data_example.csv",
"\"",
")",
";",
"SampleDataGenerator",
"generator",
"=",
"new",
"SampleDataGenerator",
"(",
")",
";",
"List",
"sampleData",
"=",
"generator",
".",
"generateDataForEBN",
"(",
"ebn",
",",
"numberOfDataSamplesToGenerate",
",",
"true",
",",
"null",
")",
";",
"try",
"(",
"CSVWriter",
"writer",
"=",
"new",
"CSVWriter",
"(",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"dataFile",
")",
")",
",",
"','",
",",
"'\\0'",
")",
")",
"{",
"writer",
".",
"writeAll",
"(",
"sampleData",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"}",
"}",
"catch",
"(",
"FileHandlingException",
"ex",
")",
"{",
"}",
"}",
"/**\n * Demonstrates learning purely from data.\n *\n * @throws Exception\n */",
"private",
"void",
"learnTablesPurelyFromData",
"(",
")",
"{",
"try",
"{",
"Path",
"examplesDirectoryPath",
"=",
"Paths",
".",
"get",
"(",
"Config",
".",
"getDirectoryHomeAgenaRisk",
"(",
")",
",",
"\"",
"Model Library",
"\"",
",",
"\"",
"Advanced",
"\"",
",",
"\"",
"Learning from Data",
"\"",
")",
";",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia.ast",
"\"",
")",
".",
"toString",
"(",
")",
")",
";",
"String",
"dataFileName",
"=",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia - example dataset.csv",
"\"",
")",
".",
"toString",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"Data",
"data",
"=",
"new",
"Data",
"(",
"dataFileName",
",",
"\"",
"NA",
"\"",
")",
";",
"data",
"=",
"new",
"Data",
"(",
"dataFileName",
",",
"\"",
"NA",
"\"",
",",
"\"",
",",
"\"",
")",
";",
"m",
".",
"setEMLogging",
"(",
"true",
")",
";",
"Model",
".",
"EM_ON",
"=",
"true",
";",
"EMCal",
"emcal",
"=",
"new",
"EMCal",
"(",
"m",
",",
"ebn",
",",
"data",
",",
"\"",
"NA",
"\"",
",",
"dataFileName",
",",
"new",
"ArrayList",
"(",
")",
",",
"false",
")",
";",
"emcal",
".",
"setMaxIterations",
"(",
"25",
")",
";",
"emcal",
".",
"threshold",
"=",
"0.01",
";",
"emcal",
".",
"calculateEM",
"(",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"m",
".",
"save",
"(",
"\"",
"model_learnt_purely_from_data.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"FileHandlingException",
"|",
"IOException",
"|",
"CoreBNException",
"|",
"CoreBNInconsistentEvidenceException",
"|",
"PropagationException",
"|",
"MessagePassingLinkException",
"|",
"PropagationTerminatedException",
"ex",
")",
"{",
"}",
"catch",
"(",
"InconsistentDataVsModelStatesException",
"ex",
")",
"{",
"}",
"catch",
"(",
"ExtendedBNException",
"ex",
")",
"{",
"}",
"catch",
"(",
"EMLearningException",
"ex",
")",
"{",
"}",
"}",
"/**\n * Demonstrates learning from data and expert judgement (set at the level of\n * ExtendedBN)\n */",
"private",
"void",
"learnTablesWithExpertJudgement",
"(",
")",
"{",
"try",
"{",
"Path",
"examplesDirectoryPath",
"=",
"Paths",
".",
"get",
"(",
"Config",
".",
"getDirectoryHomeAgenaRisk",
"(",
")",
",",
"\"",
"Model Library",
"\"",
",",
"\"",
"Advanced",
"\"",
",",
"\"",
"Learning from Data",
"\"",
")",
";",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia.ast",
"\"",
")",
".",
"toString",
"(",
")",
")",
";",
"String",
"dataFileName",
"=",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia - example dataset.csv",
"\"",
")",
".",
"toString",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"Data",
"data",
"=",
"new",
"Data",
"(",
"dataFileName",
",",
"\"",
"NA",
"\"",
")",
";",
"m",
".",
"setEMLogging",
"(",
"true",
")",
";",
"ebn",
".",
"setConfidence",
"(",
"0.5",
")",
";",
"Model",
".",
"EM_ON",
"=",
"true",
";",
"EMCal",
"emcal",
"=",
"new",
"EMCal",
"(",
"m",
",",
"ebn",
",",
"data",
",",
"\"",
"NA",
"\"",
",",
"dataFileName",
",",
"Arrays",
".",
"asList",
"(",
"\"",
"TBoC",
"\"",
")",
",",
"false",
")",
";",
"emcal",
".",
"setMaxIterations",
"(",
"25",
")",
";",
"emcal",
".",
"threshold",
"=",
"0.01",
";",
"emcal",
".",
"calculateEM",
"(",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"m",
".",
"save",
"(",
"\"",
"model_learnt_from_data_and_expert_judgement.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"FileHandlingException",
"|",
"IOException",
"|",
"CoreBNException",
"|",
"CoreBNInconsistentEvidenceException",
"|",
"PropagationException",
"|",
"MessagePassingLinkException",
"|",
"PropagationTerminatedException",
"ex",
")",
"{",
"}",
"catch",
"(",
"InconsistentDataVsModelStatesException",
"ex",
")",
"{",
"}",
"catch",
"(",
"ExtendedBNException",
"ex",
")",
"{",
"}",
"catch",
"(",
"EMLearningException",
"ex",
")",
"{",
"}",
"}",
"/**\n * Demonstrates learning from data and expert judgement (set at the level of\n * individual nodes)\n */",
"private",
"void",
"learnTablesWithExpertJudgementForIndividualNodes",
"(",
")",
"{",
"try",
"{",
"Path",
"examplesDirectoryPath",
"=",
"Paths",
".",
"get",
"(",
"Config",
".",
"getDirectoryHomeAgenaRisk",
"(",
")",
",",
"\"",
"Model Library",
"\"",
",",
"\"",
"Advanced",
"\"",
",",
"\"",
"Learning from Data",
"\"",
")",
";",
"Model",
"m",
"=",
"Model",
".",
"load",
"(",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia.ast",
"\"",
")",
".",
"toString",
"(",
")",
")",
";",
"String",
"dataFileName",
"=",
"Paths",
".",
"get",
"(",
"examplesDirectoryPath",
".",
"toString",
"(",
")",
",",
"\"",
"Asia - example dataset.csv",
"\"",
")",
".",
"toString",
"(",
")",
";",
"ExtendedBN",
"ebn",
"=",
"m",
".",
"getExtendedBNAtIndex",
"(",
"0",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"Data",
"data",
"=",
"new",
"Data",
"(",
"dataFileName",
",",
"\"",
"NA",
"\"",
")",
";",
"m",
".",
"setEMLogging",
"(",
"true",
")",
";",
"ebn",
".",
"setConfidence",
"(",
"0.5",
")",
";",
"ebn",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"D",
"\"",
")",
".",
"setConfidence",
"(",
"0",
")",
";",
"ebn",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"B",
"\"",
")",
".",
"setConfidence",
"(",
"0.75",
")",
";",
"ebn",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"L",
"\"",
")",
".",
"setConfidence",
"(",
"1",
")",
";",
"ebn",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"T",
"\"",
")",
".",
"setConfidence",
"(",
"-",
"1",
")",
";",
"List",
"<",
"String",
">",
"fixedNodes",
"=",
"new",
"ArrayList",
"(",
")",
";",
"fixedNodes",
".",
"add",
"(",
"\"",
"T",
"\"",
")",
";",
"ebn",
".",
"getExtendedNodeWithUniqueIdentifier",
"(",
"\"",
"A",
"\"",
")",
".",
"setConfidence",
"(",
"1.3",
")",
";",
"(",
"(",
"List",
"<",
"ExtendedNode",
">",
")",
"ebn",
".",
"getExtendedNodes",
"(",
")",
")",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"e",
"->",
"System",
".",
"out",
".",
"println",
"(",
"e",
".",
"getConnNodeId",
"(",
")",
"+",
"\"",
" ",
"\"",
"+",
"e",
"+",
"\"",
" ",
"\"",
"+",
"e",
".",
"getConfidence",
"(",
")",
")",
")",
";",
"Model",
".",
"EM_ON",
"=",
"true",
";",
"EMCal",
"emcal",
"=",
"new",
"EMCal",
"(",
"m",
",",
"ebn",
",",
"data",
",",
"\"",
"NA",
"\"",
",",
"dataFileName",
",",
"Arrays",
".",
"asList",
"(",
"\"",
"TBoC",
"\"",
")",
",",
"false",
")",
";",
"emcal",
".",
"setMaxIterations",
"(",
"25",
")",
";",
"emcal",
".",
"threshold",
"=",
"0.01",
";",
"emcal",
".",
"setFixedNodes",
"(",
"fixedNodes",
")",
";",
"emcal",
".",
"calculateEM",
"(",
")",
";",
"printNPTs",
"(",
"ebn",
")",
";",
"m",
".",
"save",
"(",
"\"",
"model_learnt_from_data_and_expert_judgement_individual_nodes.cmp",
"\"",
")",
";",
"}",
"catch",
"(",
"FileHandlingException",
"|",
"IOException",
"|",
"CoreBNException",
"|",
"CoreBNInconsistentEvidenceException",
"|",
"PropagationException",
"|",
"MessagePassingLinkException",
"|",
"PropagationTerminatedException",
"ex",
")",
"{",
"}",
"catch",
"(",
"InconsistentDataVsModelStatesException",
"ex",
")",
"{",
"}",
"catch",
"(",
"ExtendedBNException",
"ex",
")",
"{",
"}",
"catch",
"(",
"EMLearningException",
"ex",
")",
"{",
"}",
"}",
"}"
] | These examples correspond to the ones from AgenaRisk 10 Developer manual. | [
"These",
"examples",
"correspond",
"to",
"the",
"ones",
"from",
"AgenaRisk",
"10",
"Developer",
"manual",
"."
] | [
"// First get the single BN",
"// Add a new node of type Boolean to this BN;",
"// its identifier is “b” ands its name is “B”",
"// First get the single BN",
"//Create DataSet object:",
"//Add the set of state names to lds:",
"//Now completely redefine the set of states of len:",
"//For the Boolean node:",
"//For the Continuous Interval Node:",
"//For the Integer Interval Node:",
"//For the Discrete Real Node:",
"//For the ranked node:",
"//Finally save the model",
"// Load the model that was created and saved ",
"// in the method editStates",
"// Get the single BN",
"//Get the three of the nodes labelled B, L, and R. ",
"//Note use of casting as the ebn.getExtendedNodewithName() method returns the ExtendedNode superclass:",
"//Next we make nodes B (ben) and R (ren) parents of L (len):",
"//Next redefine the NPTs of nodes B and R to overwrite the default NPTs. ",
"//These NPTs are easy because the nodes have no parents. ",
"//B has two states so we need to define an array of length 2. ",
"// R has three states so we need to define an array of length 3:",
"//To redefine the NPT for the node L is harder because it has two parents (B and R)",
"//To generate this NPT we must first get the list of parents of L:",
"//Now we define the NPT of L:",
"//Save the model:",
"//try",
"//nptManipulation",
"// Get the Marginals for the node",
"// There’s only one scenario, so get the first ",
"// MarginalDataItem in the list",
"// Now print out the node name and marginals",
"//Print the mean of the distribution",
"//get the variance of the distribution",
"//Calculate the entire model:",
"//get the node L ",
"//print the marginals and statistics for L",
"//get the node CI ",
"//print the marginals and statistics for L",
"//workingWithEvidence",
"//get the node L whose NPT we created in the nptManipulation() method:",
"//We are going to enter evidence on one of the parents of the node L. ",
"//So, first we need to get one such parent, the Ranked node R:",
"//All evidence entry is done via “scenarios” ",
"//(there is an enterEvidence() method associated with the ExtendedNode class but you should ignore this). ",
"//So we need to get the single (default) scenario, which currently has no evidence:",
"//Now we enter hard evidence on node R (ren):",
"//Now calculate again and print the marginals:",
"//Nex we show how to enter evidence for continuous nodes",
"//get the continuous node CI (cien):",
"//Now enter a “real number” observation, 48.0, using the same scenario s:",
"//Note: For an Integer Interval node you would use the method addIntegerObservation().",
"//Calculate the model again and and print the marginals for the node CI (cien):",
"//save the model:",
"//enteringEvidence",
"// create a new model and get the single BN:",
"//Add a new Continuous Interval node to this BN:",
"//Redefine the states of node A as just a single state range from 0 to infinity:",
"//make this node a simulation node by setting the node's simulation property to true:",
"//define a Normal distribution as the expression for the NPT of this node:",
"// mean",
"// variance",
"//Now regenerate the NPT for this node:",
"// setting the number of iterations (the default is 25 if you do not set it explicitly)",
"//Calculate the entire model:",
"//Use the printMarginals() method defined above to print out the marginals:",
"//save the model so you can inspect it in AgenaRisk:",
"//testSimpleExpression",
"// create a new model and get the single BN:",
"//Create three Continuous Interval nodes, A and B, and C:",
"//Redefine the states of each node as just a single state range from 0 to infinity",
"//Make C the child of both A and B:",
"//Make all nodes simulation nodes:",
"//Define the NPTs of A and B to be Uniform:",
"//lower bound",
"//upper bound",
"//Define the NPT of C as an arithmetic expression of the parents (we use a simple sum):",
"//regenerate the NPTs:",
"//Calculate the entire model and print the marginals:",
"//Now enter observations for A and B. First we get the single Scenario:",
"//Calculate again:",
"//Save the model:",
"//testExpressionWithParent",
"// create a new model and get the single BN:",
"// Create a Labelled node, A, and set up new states for it:",
"//Create a Continuous Interval node, B:",
"//Make it a child of A: ",
"//Make it a simulation node:",
"//Set the new state range to be 0 to infinity:",
"//Make A a model node of B:",
"//Next we create a partitioned expression for each state of A. ",
"//First we need a List to store the expressions we will create:",
"//Create the expression Normal(10, 100) for the first state (Red):",
"//Create the expression Normal(25, 100) for second state (Amber):",
"//Create the expression Normal(40, 100) for third state (Green):",
"//Now regenerate the NPT for B:",
"//Calculate the entire model and print the marginals:",
"//Next we will add observations, so we need to get the single scenario:",
"//Enter observation Red, calculate and view the marginals:",
"//Enter observation Amber, calculate and view the marginals:",
"//Enter observation Green, calculate and view the marginals:",
"//save the file:",
"//testPartitionedExpression",
"// create an empty model and get the existing BN:",
"//Rename the existing BN",
"//This time we want to create a new BN called “Two”:",
"//Use method populateSimpleExtendedBN to populate both BNs:",
"//get the node A in BN “One” and set it as an output node:",
"//Get the node A in BN “Two” and set it as an input node:",
"//Link the two nodes (and, thus, the two BNs)",
"//Add an observation to c in BN \"one\":",
"//Calculate and print the marginals of a in both BNs:",
"//save the model",
"//testBNOs",
"// Create two nodes, A and B, and a child C",
"//For the node c redefine its states",
"// Now regenerate the NPT for C",
"//populateSimpleExtendedBN",
"//Load example model",
"//Prepare data path",
"//Number of data rows to be generated",
"//File name for example data",
"//Initialize generator",
"//Generate data",
"//Save generated data to a file",
"//custom exception handling for problems with saving data file",
"//custom exception handling for problems with saving data file",
"//Load example model",
"//Prepare data path",
"//Print NPTs",
"//Read in data",
"//If the values in the data file are separated not by a comma, you can provide custom separator",
"//If the learning process should be logged turn it on",
"//Set up EMCal object",
"//emcal.laplacian = 0;",
"//Start calculations",
"//Print NPTs",
"//Save learnt model",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling ",
"//Load example model",
"//Prepare data path",
"//Print NPTs",
"//Read in data",
"//If the learning process should be logged turn it on",
"//set confidence",
"//Set up EMCal object",
"//emcal.laplacian = 0;",
"//Start calculations",
"//Print NPTs",
"//Save learnt model",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling ",
"//Load example model",
"//Prepare data path",
"//Print NPTs",
"//Read in data",
"//If the learning process should be logged turn it on",
"//set confidence",
"//globally as default for the whole ExtendedBN",
"//only from data",
"//knowledge is 3x more important than data",
"//100% knowledge, do not learn",
"//use the default confidence for the whole ExtendedBN but make it a fixed node",
"//try to assign a value form outside possible range",
"//check confidence for individual nodes",
"//Set up EMCal object",
"//emcal.laplacian = 0;",
"//Start calculations",
"//Print NPTs",
"//Save learnt model",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling ",
"//custom exception handling "
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13bbc1130470cd6732eb2b6bc775c057d36673ee | jusjoken/gemstone2 | src/main/java/Gemstone/AutoPlaylist.java | [
"Apache-2.0"
] | Java | AutoPlaylist | /**
*
* @author SBANTA
* - 04/04/2012 - updated for Gemstone...jusjoken
* - 02/29/2016 - updated to better handle a list from a View result...jusjoken
*/ | @author SBANTA
- 04/04/2012 - updated for Gemstone...jusjoken
- 02/29/2016 - updated to better handle a list from a View result...jusjoken | [
"@author",
"SBANTA",
"-",
"04",
"/",
"04",
"/",
"2012",
"-",
"updated",
"for",
"Gemstone",
"...",
"jusjoken",
"-",
"02",
"/",
"29",
"/",
"2016",
"-",
"updated",
"to",
"better",
"handle",
"a",
"list",
"from",
"a",
"View",
"result",
"...",
"jusjoken"
] | public class AutoPlaylist {
static private final Logger LOG = Logger.getLogger(Source.class);
public static void MakeTVPlaylistandPlay(List MediaList){
//get the now playing playlist
Object NewPlaylist = sagex.api.PlaylistAPI.GetNowPlayingList(new UIContext(sagex.api.Global.GetUIContextName()));
//LOG.debug("MakeTVPlaylistandPlay: Start Playlist size '" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + "'");
Object[] PlaylistItems = sagex.api.PlaylistAPI.GetPlaylistItems(new UIContext(sagex.api.Global.GetUIContextName()), NewPlaylist);
//empty the now playing playlist if there are any items
if(PlaylistItems.length>0){
sagex.api.PlaylistAPI.RemovePlaylist(new UIContext(sagex.api.Global.GetUIContextName()),NewPlaylist);
NewPlaylist = sagex.api.PlaylistAPI.GetNowPlayingList(new UIContext(sagex.api.Global.GetUIContextName()));
}
//add the passed in list to the now playing playlist
//LOG.debug("MakeTVPlaylistandPlay: After Playlist size '" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + "'");
for ( int i=0;i<MediaList.size();i++){
LOG.debug("MakeTVPlaylistandPlay: Adding item '" + MediaList.get(i) + "'");
sagex.api.PlaylistAPI.AddToPlaylist(NewPlaylist,phoenix.media.GetMediaObject(MediaList.get(i)));
}
//tell the STV to play the nowplaying playlist
//LOG.debug("MakeTVPlaylistandPlay: End Playlist size '" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + "'");
api.AddStaticContext("CurPlaylist", NewPlaylist);
api.ExecuteWidgeChain("BASE-50293");
}
} | [
"public",
"class",
"AutoPlaylist",
"{",
"static",
"private",
"final",
"Logger",
"LOG",
"=",
"Logger",
".",
"getLogger",
"(",
"Source",
".",
"class",
")",
";",
"public",
"static",
"void",
"MakeTVPlaylistandPlay",
"(",
"List",
"MediaList",
")",
"{",
"Object",
"NewPlaylist",
"=",
"sagex",
".",
"api",
".",
"PlaylistAPI",
".",
"GetNowPlayingList",
"(",
"new",
"UIContext",
"(",
"sagex",
".",
"api",
".",
"Global",
".",
"GetUIContextName",
"(",
")",
")",
")",
";",
"Object",
"[",
"]",
"PlaylistItems",
"=",
"sagex",
".",
"api",
".",
"PlaylistAPI",
".",
"GetPlaylistItems",
"(",
"new",
"UIContext",
"(",
"sagex",
".",
"api",
".",
"Global",
".",
"GetUIContextName",
"(",
")",
")",
",",
"NewPlaylist",
")",
";",
"if",
"(",
"PlaylistItems",
".",
"length",
">",
"0",
")",
"{",
"sagex",
".",
"api",
".",
"PlaylistAPI",
".",
"RemovePlaylist",
"(",
"new",
"UIContext",
"(",
"sagex",
".",
"api",
".",
"Global",
".",
"GetUIContextName",
"(",
")",
")",
",",
"NewPlaylist",
")",
";",
"NewPlaylist",
"=",
"sagex",
".",
"api",
".",
"PlaylistAPI",
".",
"GetNowPlayingList",
"(",
"new",
"UIContext",
"(",
"sagex",
".",
"api",
".",
"Global",
".",
"GetUIContextName",
"(",
")",
")",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"MediaList",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"MakeTVPlaylistandPlay: Adding item '",
"\"",
"+",
"MediaList",
".",
"get",
"(",
"i",
")",
"+",
"\"",
"'",
"\"",
")",
";",
"sagex",
".",
"api",
".",
"PlaylistAPI",
".",
"AddToPlaylist",
"(",
"NewPlaylist",
",",
"phoenix",
".",
"media",
".",
"GetMediaObject",
"(",
"MediaList",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"api",
".",
"AddStaticContext",
"(",
"\"",
"CurPlaylist",
"\"",
",",
"NewPlaylist",
")",
";",
"api",
".",
"ExecuteWidgeChain",
"(",
"\"",
"BASE-50293",
"\"",
")",
";",
"}",
"}"
] | @author SBANTA
- 04/04/2012 - updated for Gemstone...jusjoken
- 02/29/2016 - updated to better handle a list from a View result...jusjoken | [
"@author",
"SBANTA",
"-",
"04",
"/",
"04",
"/",
"2012",
"-",
"updated",
"for",
"Gemstone",
"...",
"jusjoken",
"-",
"02",
"/",
"29",
"/",
"2016",
"-",
"updated",
"to",
"better",
"handle",
"a",
"list",
"from",
"a",
"View",
"result",
"...",
"jusjoken"
] | [
"//get the now playing playlist",
"//LOG.debug(\"MakeTVPlaylistandPlay: Start Playlist size '\" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + \"'\");",
"//empty the now playing playlist if there are any items",
"//add the passed in list to the now playing playlist",
"//LOG.debug(\"MakeTVPlaylistandPlay: After Playlist size '\" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + \"'\");",
"//tell the STV to play the nowplaying playlist",
"//LOG.debug(\"MakeTVPlaylistandPlay: End Playlist size '\" + sagex.api.PlaylistAPI.GetPlaylistItems(NewPlaylist).length + \"'\");"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13c0a7e49cb824830e7e2509e3bace6af68502a9 | jgome043/rest.li | data/src/main/java/com/linkedin/data/message/Message.java | [
"Apache-2.0"
] | Java | Message | /**
* Used to provide an error status and formattable message.
*
* {@link Message}s may be emitted as part of validating
* a Data object against a {@link com.linkedin.data.schema.DataSchema} or applying
* patches.
*/ | Used to provide an error status and formattable message.
Messages may be emitted as part of validating
a Data object against a com.linkedin.data.schema.DataSchema or applying
patches. | [
"Used",
"to",
"provide",
"an",
"error",
"status",
"and",
"formattable",
"message",
".",
"Messages",
"may",
"be",
"emitted",
"as",
"part",
"of",
"validating",
"a",
"Data",
"object",
"against",
"a",
"com",
".",
"linkedin",
".",
"data",
".",
"schema",
".",
"DataSchema",
"or",
"applying",
"patches",
"."
] | public class Message
{
public static final String MESSAGE_FIELD_SEPARATOR = " :: ";
private final Object[] _path;
private final boolean _error;
private final String _format;
private final Object[] _args;
public Message(Object[] path, String format, Object... args)
{
this(path, true, format, args);
}
public Message(Object[] path, boolean error, String format, Object... args)
{
_path = path;
_error = error;
_format = format;
_args = args;
}
public Object[] getPath()
{
return _path;
}
public String getFormat()
{
return _format;
}
public Object[] getArgs()
{
return _args;
}
public boolean isError()
{
return _error;
}
/**
* Return this {@link Message} if it is an error message
* else return copy of this {@link Message} that is an error message.
*
* @return this {@link Message} if it is an error message
* else return copy of this {@link Message}
* that is an error message.
*/
public Message asErrorMessage()
{
return _error ? this : new Message(_path, true, _format, _args);
}
/**
* Return this {@link Message} if it is an info message
* else return copy of this {@link Message} that is an info message.
*
* @return this {@link Message} if it is an info message
* else return copy of this {@link Message}
* that is an info message.
*/
public Message asInfoMessage()
{
return _error ? new Message(_path, false, _format, _args) : this;
}
/**
* Write contents of this message into the provided {@link Formatter} using
* the provided field separator.
*
* @param formatter provides the {@link Formatter} to write this {@link Message} to.
* @param fieldSeparator provides the field separator to use for separating message fields.
* @return the provided {@link Formatter}.
*/
public Formatter format(Formatter formatter, String fieldSeparator)
{
formatError(formatter);
formatSeparator(formatter, fieldSeparator);
formatPath(formatter);
formatSeparator(formatter, fieldSeparator);
formatArgs(formatter);
return formatter;
}
protected void formatSeparator(Formatter formatter, String fieldSeparator)
{
try
{
Appendable out = formatter.out();
out.append(fieldSeparator);
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
protected void formatError(Formatter formatter)
{
formatter.format(isError() ? "ERROR" : "INFO");
}
protected void formatPath(Formatter formatter)
{
Appendable appendable = formatter.out();
try
{
for (Object component : _path)
{
appendable.append(DataElement.SEPARATOR);
appendable.append(component.toString());
}
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
protected void formatArgs(Formatter formatter)
{
formatter.format(_format, _args);
}
/**
* Write contents of this message into the provided {@link Formatter} using
* the the field separator provided by {@link #getFieldSeparator()}.
*
* @param formatter provides the {@link Formatter} to write this {@link Message} to.
* @return the provided {@link Formatter}.
*/
public Formatter format(Formatter formatter)
{
return format(formatter, getFieldSeparator());
}
/**
* Allow subclasses to override the {@link Message}'s field separator.
*
* @return the {@link Message}'s field separator.
*/
public String getFieldSeparator()
{
return MESSAGE_FIELD_SEPARATOR;
}
@Override
public String toString()
{
String fieldSeparator = getFieldSeparator();
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
format(formatter, fieldSeparator);
formatter.flush();
formatter.close();
return sb.toString();
}
} | [
"public",
"class",
"Message",
"{",
"public",
"static",
"final",
"String",
"MESSAGE_FIELD_SEPARATOR",
"=",
"\"",
" :: ",
"\"",
";",
"private",
"final",
"Object",
"[",
"]",
"_path",
";",
"private",
"final",
"boolean",
"_error",
";",
"private",
"final",
"String",
"_format",
";",
"private",
"final",
"Object",
"[",
"]",
"_args",
";",
"public",
"Message",
"(",
"Object",
"[",
"]",
"path",
",",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"this",
"(",
"path",
",",
"true",
",",
"format",
",",
"args",
")",
";",
"}",
"public",
"Message",
"(",
"Object",
"[",
"]",
"path",
",",
"boolean",
"error",
",",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"_path",
"=",
"path",
";",
"_error",
"=",
"error",
";",
"_format",
"=",
"format",
";",
"_args",
"=",
"args",
";",
"}",
"public",
"Object",
"[",
"]",
"getPath",
"(",
")",
"{",
"return",
"_path",
";",
"}",
"public",
"String",
"getFormat",
"(",
")",
"{",
"return",
"_format",
";",
"}",
"public",
"Object",
"[",
"]",
"getArgs",
"(",
")",
"{",
"return",
"_args",
";",
"}",
"public",
"boolean",
"isError",
"(",
")",
"{",
"return",
"_error",
";",
"}",
"/**\n * Return this {@link Message} if it is an error message\n * else return copy of this {@link Message} that is an error message.\n *\n * @return this {@link Message} if it is an error message\n * else return copy of this {@link Message}\n * that is an error message.\n */",
"public",
"Message",
"asErrorMessage",
"(",
")",
"{",
"return",
"_error",
"?",
"this",
":",
"new",
"Message",
"(",
"_path",
",",
"true",
",",
"_format",
",",
"_args",
")",
";",
"}",
"/**\n * Return this {@link Message} if it is an info message\n * else return copy of this {@link Message} that is an info message.\n *\n * @return this {@link Message} if it is an info message\n * else return copy of this {@link Message}\n * that is an info message.\n */",
"public",
"Message",
"asInfoMessage",
"(",
")",
"{",
"return",
"_error",
"?",
"new",
"Message",
"(",
"_path",
",",
"false",
",",
"_format",
",",
"_args",
")",
":",
"this",
";",
"}",
"/**\n * Write contents of this message into the provided {@link Formatter} using\n * the provided field separator.\n *\n * @param formatter provides the {@link Formatter} to write this {@link Message} to.\n * @param fieldSeparator provides the field separator to use for separating message fields.\n * @return the provided {@link Formatter}.\n */",
"public",
"Formatter",
"format",
"(",
"Formatter",
"formatter",
",",
"String",
"fieldSeparator",
")",
"{",
"formatError",
"(",
"formatter",
")",
";",
"formatSeparator",
"(",
"formatter",
",",
"fieldSeparator",
")",
";",
"formatPath",
"(",
"formatter",
")",
";",
"formatSeparator",
"(",
"formatter",
",",
"fieldSeparator",
")",
";",
"formatArgs",
"(",
"formatter",
")",
";",
"return",
"formatter",
";",
"}",
"protected",
"void",
"formatSeparator",
"(",
"Formatter",
"formatter",
",",
"String",
"fieldSeparator",
")",
"{",
"try",
"{",
"Appendable",
"out",
"=",
"formatter",
".",
"out",
"(",
")",
";",
"out",
".",
"append",
"(",
"fieldSeparator",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}",
"protected",
"void",
"formatError",
"(",
"Formatter",
"formatter",
")",
"{",
"formatter",
".",
"format",
"(",
"isError",
"(",
")",
"?",
"\"",
"ERROR",
"\"",
":",
"\"",
"INFO",
"\"",
")",
";",
"}",
"protected",
"void",
"formatPath",
"(",
"Formatter",
"formatter",
")",
"{",
"Appendable",
"appendable",
"=",
"formatter",
".",
"out",
"(",
")",
";",
"try",
"{",
"for",
"(",
"Object",
"component",
":",
"_path",
")",
"{",
"appendable",
".",
"append",
"(",
"DataElement",
".",
"SEPARATOR",
")",
";",
"appendable",
".",
"append",
"(",
"component",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}",
"protected",
"void",
"formatArgs",
"(",
"Formatter",
"formatter",
")",
"{",
"formatter",
".",
"format",
"(",
"_format",
",",
"_args",
")",
";",
"}",
"/**\n * Write contents of this message into the provided {@link Formatter} using\n * the the field separator provided by {@link #getFieldSeparator()}.\n *\n * @param formatter provides the {@link Formatter} to write this {@link Message} to.\n * @return the provided {@link Formatter}.\n */",
"public",
"Formatter",
"format",
"(",
"Formatter",
"formatter",
")",
"{",
"return",
"format",
"(",
"formatter",
",",
"getFieldSeparator",
"(",
")",
")",
";",
"}",
"/**\n * Allow subclasses to override the {@link Message}'s field separator.\n *\n * @return the {@link Message}'s field separator.\n */",
"public",
"String",
"getFieldSeparator",
"(",
")",
"{",
"return",
"MESSAGE_FIELD_SEPARATOR",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"String",
"fieldSeparator",
"=",
"getFieldSeparator",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"Formatter",
"formatter",
"=",
"new",
"Formatter",
"(",
"sb",
")",
";",
"format",
"(",
"formatter",
",",
"fieldSeparator",
")",
";",
"formatter",
".",
"flush",
"(",
")",
";",
"formatter",
".",
"close",
"(",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Used to provide an error status and formattable message. | [
"Used",
"to",
"provide",
"an",
"error",
"status",
"and",
"formattable",
"message",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13c249ce369c47dfca844ccf1ae67ac719435751 | avaer/skia | platform_tools/android/apps/skar_java/src/main/java/com/google/skar/SkARMatrix.java | [
"BSD-3-Clause"
] | Java | SkARMatrix | /**
* Provides static methods for matrix manipulation. Input matrices are assumed to be 4x4
* android.opengl.Matrix types. Output matrices are 3x3 android.graphics.Matrix types.
* The main use of this class is to be able to get a Matrix for a Canvas that applies perspective
* to 2D objects
*/ | Provides static methods for matrix manipulation. Input matrices are assumed to be 4x4
android.opengl.Matrix types. Output matrices are 3x3 android.graphics.Matrix types.
The main use of this class is to be able to get a Matrix for a Canvas that applies perspective
to 2D objects | [
"Provides",
"static",
"methods",
"for",
"matrix",
"manipulation",
".",
"Input",
"matrices",
"are",
"assumed",
"to",
"be",
"4x4",
"android",
".",
"opengl",
".",
"Matrix",
"types",
".",
"Output",
"matrices",
"are",
"3x3",
"android",
".",
"graphics",
".",
"Matrix",
"types",
".",
"The",
"main",
"use",
"of",
"this",
"class",
"is",
"to",
"be",
"able",
"to",
"get",
"a",
"Matrix",
"for",
"a",
"Canvas",
"that",
"applies",
"perspective",
"to",
"2D",
"objects"
] | public class SkARMatrix {
/******************* PUBLIC FUNCTIONS ***********************/
/**
* Returns an android.graphics.Matrix that can be used on a Canvas to draw a 2D object in
* perspective. Object will be rotated towards the XZ plane. Undefined behavior when any of
* the matrices are not of size 16, or are null.
*
* @param model 4x4 model matrix of the object to be drawn (global/world)
* @param view 4x4 camera view matrix (brings objects to camera origin and orientation)
* @param projection 4x4 projection matrix
* @param viewPortWidth width of viewport of GLSurfaceView
* @param viewPortHeight height of viewport of GLSurfaceView
* @return 3x3 matrix that puts a 2D objects in perspective on a Canvas
*/
public static Matrix createPerspectiveMatrix(float[] model, float[] view, float[] projection,
float viewPortWidth, float viewPortHeight) {
float[] viewPort = createViewportMatrix(viewPortWidth, viewPortHeight);
float[] skiaRotation = createXYtoXZRotationMatrix();
float[][] matrices = {skiaRotation, model, view, projection, viewPort};
return createMatrixFrom4x4Array(matrices);
}
/**
* Returns a 16-float matrix in column-major order that represents a viewport matrix given
* the width and height of the viewport.
*
* @param width width of viewport
* @param height height of viewport
*/
public static float[] createViewportMatrix(float width, float height) {
float[] viewPort = new float[16];
android.opengl.Matrix.setIdentityM(viewPort, 0);
android.opengl.Matrix.translateM(viewPort, 0, width / 2, height / 2, 0);
android.opengl.Matrix.scaleM(viewPort, 0, width / 2, -height / 2, 0);
return viewPort;
}
/**
* Returns a 16-float matrix in column-major order that is used to rotate objects from the XY plane
* to the XZ plane. This is useful given that objects drawn on the Canvas are on the XY plane.
* In order to get objects to appear as if they are sticking on planes/ceilings/walls, we need
* to rotate them from the XY plane to the XZ plane.
*/
public static float[] createXYtoXZRotationMatrix() {
float[] rotation = new float[16];
android.opengl.Matrix.setIdentityM(rotation, 0);
android.opengl.Matrix.rotateM(rotation, 0, 90, 1, 0, 0);
return rotation;
}
/**
* Returns an android.graphics.Matrix resulting from a 16-float matrix array in column-major order
* Undefined behavior when the array is not of size 16 or is null.
*
* @param m4 16-float matrix in column-major order
*/
public static Matrix createMatrixFrom4x4(float[] m4) {
float[] m3 = matrix4x4ToMatrix3x3(m4);
return createMatrixFrom3x3(m3);
}
/**
* Returns an android.graphics.PointF resulting from the multiplication of a Vector of 4 floats
* with a 4x4 float Matrix. The return PointF is the (x, y) values of m4 * v4
* @param m4 16-float matrix in column-major order
* @param v4 4-float vector
* @param perspectiveDivide if true, divide return value by the w-coordinate
* @return PointF resulting from taking the (x, y) values of m4 * v4
*/
public static PointF multiplyMatrixVector(float[] m4, float[] v4, boolean perspectiveDivide) {
float[] result = new float[4];
android.opengl.Matrix.multiplyMV(result, 0, m4, 0, v4, 0);
if (perspectiveDivide) {
return new PointF(result[0] / result[3], result[1] / result[3]);
}
return new PointF(result[0], result[1]);
}
/**
* Returns a 16-float matrix in column-major order resulting from the multiplication of matrices.
* e.g: m4Array = {m1, m2, m3} --> returns m = m3 * m2 * m1
* Undefined behavior when the array is empty, null, or contains arrays not of size 9 (or null)
*
* @param m4Array array of 16-float matrices in column-major order
*/
public static float[] multiplyMatrices4x4(float[][] m4Array) {
float[] result = new float[16];
android.opengl.Matrix.setIdentityM(result, 0);
float[] rhs = result;
for (int i = 0; i < m4Array.length; i++) {
float[] lhs = m4Array[i];
android.opengl.Matrix.multiplyMM(result, 0, lhs, 0, rhs, 0);
rhs = result;
}
return result;
}
/******************* PRIVATE FUNCTIONS ***********************/
/**
* Returns an android.graphics.Matrix resulting from the concatenation of 16-float matrices
* in column-major order from left to right.
* e.g: m4Array = {m1, m2, m3} --> returns m = m3 * m2 * m1
* Undefined behavior when the array is empty, null, or contains arrays not of size 9 (or null)
*
* @param m4Array array of 16-float matrices in column-major order
*/
private static Matrix createMatrixFrom4x4Array(float[][] m4Array) {
float[] result = multiplyMatrices4x4(m4Array);
return createMatrixFrom4x4(result);
}
/**
* Returns an android.graphics.Matrix resulting from a 9-float matrix array in row-major order.
* Undefined behavior when the array is not of size 9 or is null.
*
* @param m3 9-float matrix array in row-major order
*/
private static Matrix createMatrixFrom3x3(float[] m3) {
Matrix m = new Matrix();
m.setValues(m3);
return m;
}
/**
* Returns a 9-float matrix in row-major order given a 16-float matrix in column-major order.
* This will drop the Z column and row.
* Undefined behavior when the array is not of size 9 or is null.
*
* @param m4 16-float matrix in column-major order
*/
private static float[] matrix4x4ToMatrix3x3(float[] m4) {
float[] m3 = new float[9];
int j = 0;
for (int i = 0; i < 7; i = i + 3) {
if (j == 2) {
j++; //skip row #3
}
m3[i] = m4[j];
m3[i + 1] = m4[j + 4];
m3[i + 2] = m4[j + 12];
j++;
}
return m3;
}
} | [
"public",
"class",
"SkARMatrix",
"{",
"/******************* PUBLIC FUNCTIONS ***********************/",
"/**\n * Returns an android.graphics.Matrix that can be used on a Canvas to draw a 2D object in\n * perspective. Object will be rotated towards the XZ plane. Undefined behavior when any of\n * the matrices are not of size 16, or are null.\n *\n * @param model 4x4 model matrix of the object to be drawn (global/world)\n * @param view 4x4 camera view matrix (brings objects to camera origin and orientation)\n * @param projection 4x4 projection matrix\n * @param viewPortWidth width of viewport of GLSurfaceView\n * @param viewPortHeight height of viewport of GLSurfaceView\n * @return 3x3 matrix that puts a 2D objects in perspective on a Canvas\n */",
"public",
"static",
"Matrix",
"createPerspectiveMatrix",
"(",
"float",
"[",
"]",
"model",
",",
"float",
"[",
"]",
"view",
",",
"float",
"[",
"]",
"projection",
",",
"float",
"viewPortWidth",
",",
"float",
"viewPortHeight",
")",
"{",
"float",
"[",
"]",
"viewPort",
"=",
"createViewportMatrix",
"(",
"viewPortWidth",
",",
"viewPortHeight",
")",
";",
"float",
"[",
"]",
"skiaRotation",
"=",
"createXYtoXZRotationMatrix",
"(",
")",
";",
"float",
"[",
"]",
"[",
"]",
"matrices",
"=",
"{",
"skiaRotation",
",",
"model",
",",
"view",
",",
"projection",
",",
"viewPort",
"}",
";",
"return",
"createMatrixFrom4x4Array",
"(",
"matrices",
")",
";",
"}",
"/**\n * Returns a 16-float matrix in column-major order that represents a viewport matrix given\n * the width and height of the viewport.\n *\n * @param width width of viewport\n * @param height height of viewport\n */",
"public",
"static",
"float",
"[",
"]",
"createViewportMatrix",
"(",
"float",
"width",
",",
"float",
"height",
")",
"{",
"float",
"[",
"]",
"viewPort",
"=",
"new",
"float",
"[",
"16",
"]",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"setIdentityM",
"(",
"viewPort",
",",
"0",
")",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"translateM",
"(",
"viewPort",
",",
"0",
",",
"width",
"/",
"2",
",",
"height",
"/",
"2",
",",
"0",
")",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"scaleM",
"(",
"viewPort",
",",
"0",
",",
"width",
"/",
"2",
",",
"-",
"height",
"/",
"2",
",",
"0",
")",
";",
"return",
"viewPort",
";",
"}",
"/**\n * Returns a 16-float matrix in column-major order that is used to rotate objects from the XY plane\n * to the XZ plane. This is useful given that objects drawn on the Canvas are on the XY plane.\n * In order to get objects to appear as if they are sticking on planes/ceilings/walls, we need\n * to rotate them from the XY plane to the XZ plane.\n */",
"public",
"static",
"float",
"[",
"]",
"createXYtoXZRotationMatrix",
"(",
")",
"{",
"float",
"[",
"]",
"rotation",
"=",
"new",
"float",
"[",
"16",
"]",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"setIdentityM",
"(",
"rotation",
",",
"0",
")",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"rotateM",
"(",
"rotation",
",",
"0",
",",
"90",
",",
"1",
",",
"0",
",",
"0",
")",
";",
"return",
"rotation",
";",
"}",
"/**\n * Returns an android.graphics.Matrix resulting from a 16-float matrix array in column-major order\n * Undefined behavior when the array is not of size 16 or is null.\n *\n * @param m4 16-float matrix in column-major order\n */",
"public",
"static",
"Matrix",
"createMatrixFrom4x4",
"(",
"float",
"[",
"]",
"m4",
")",
"{",
"float",
"[",
"]",
"m3",
"=",
"matrix4x4ToMatrix3x3",
"(",
"m4",
")",
";",
"return",
"createMatrixFrom3x3",
"(",
"m3",
")",
";",
"}",
"/**\n * Returns an android.graphics.PointF resulting from the multiplication of a Vector of 4 floats\n * with a 4x4 float Matrix. The return PointF is the (x, y) values of m4 * v4\n * @param m4 16-float matrix in column-major order\n * @param v4 4-float vector\n * @param perspectiveDivide if true, divide return value by the w-coordinate\n * @return PointF resulting from taking the (x, y) values of m4 * v4\n */",
"public",
"static",
"PointF",
"multiplyMatrixVector",
"(",
"float",
"[",
"]",
"m4",
",",
"float",
"[",
"]",
"v4",
",",
"boolean",
"perspectiveDivide",
")",
"{",
"float",
"[",
"]",
"result",
"=",
"new",
"float",
"[",
"4",
"]",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"multiplyMV",
"(",
"result",
",",
"0",
",",
"m4",
",",
"0",
",",
"v4",
",",
"0",
")",
";",
"if",
"(",
"perspectiveDivide",
")",
"{",
"return",
"new",
"PointF",
"(",
"result",
"[",
"0",
"]",
"/",
"result",
"[",
"3",
"]",
",",
"result",
"[",
"1",
"]",
"/",
"result",
"[",
"3",
"]",
")",
";",
"}",
"return",
"new",
"PointF",
"(",
"result",
"[",
"0",
"]",
",",
"result",
"[",
"1",
"]",
")",
";",
"}",
"/**\n * Returns a 16-float matrix in column-major order resulting from the multiplication of matrices.\n * e.g: m4Array = {m1, m2, m3} --> returns m = m3 * m2 * m1\n * Undefined behavior when the array is empty, null, or contains arrays not of size 9 (or null)\n *\n * @param m4Array array of 16-float matrices in column-major order\n */",
"public",
"static",
"float",
"[",
"]",
"multiplyMatrices4x4",
"(",
"float",
"[",
"]",
"[",
"]",
"m4Array",
")",
"{",
"float",
"[",
"]",
"result",
"=",
"new",
"float",
"[",
"16",
"]",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"setIdentityM",
"(",
"result",
",",
"0",
")",
";",
"float",
"[",
"]",
"rhs",
"=",
"result",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m4Array",
".",
"length",
";",
"i",
"++",
")",
"{",
"float",
"[",
"]",
"lhs",
"=",
"m4Array",
"[",
"i",
"]",
";",
"android",
".",
"opengl",
".",
"Matrix",
".",
"multiplyMM",
"(",
"result",
",",
"0",
",",
"lhs",
",",
"0",
",",
"rhs",
",",
"0",
")",
";",
"rhs",
"=",
"result",
";",
"}",
"return",
"result",
";",
"}",
"/******************* PRIVATE FUNCTIONS ***********************/",
"/**\n * Returns an android.graphics.Matrix resulting from the concatenation of 16-float matrices\n * in column-major order from left to right.\n * e.g: m4Array = {m1, m2, m3} --> returns m = m3 * m2 * m1\n * Undefined behavior when the array is empty, null, or contains arrays not of size 9 (or null)\n *\n * @param m4Array array of 16-float matrices in column-major order\n */",
"private",
"static",
"Matrix",
"createMatrixFrom4x4Array",
"(",
"float",
"[",
"]",
"[",
"]",
"m4Array",
")",
"{",
"float",
"[",
"]",
"result",
"=",
"multiplyMatrices4x4",
"(",
"m4Array",
")",
";",
"return",
"createMatrixFrom4x4",
"(",
"result",
")",
";",
"}",
"/**\n * Returns an android.graphics.Matrix resulting from a 9-float matrix array in row-major order.\n * Undefined behavior when the array is not of size 9 or is null.\n *\n * @param m3 9-float matrix array in row-major order\n */",
"private",
"static",
"Matrix",
"createMatrixFrom3x3",
"(",
"float",
"[",
"]",
"m3",
")",
"{",
"Matrix",
"m",
"=",
"new",
"Matrix",
"(",
")",
";",
"m",
".",
"setValues",
"(",
"m3",
")",
";",
"return",
"m",
";",
"}",
"/**\n * Returns a 9-float matrix in row-major order given a 16-float matrix in column-major order.\n * This will drop the Z column and row.\n * Undefined behavior when the array is not of size 9 or is null.\n *\n * @param m4 16-float matrix in column-major order\n */",
"private",
"static",
"float",
"[",
"]",
"matrix4x4ToMatrix3x3",
"(",
"float",
"[",
"]",
"m4",
")",
"{",
"float",
"[",
"]",
"m3",
"=",
"new",
"float",
"[",
"9",
"]",
";",
"int",
"j",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"7",
";",
"i",
"=",
"i",
"+",
"3",
")",
"{",
"if",
"(",
"j",
"==",
"2",
")",
"{",
"j",
"++",
";",
"}",
"m3",
"[",
"i",
"]",
"=",
"m4",
"[",
"j",
"]",
";",
"m3",
"[",
"i",
"+",
"1",
"]",
"=",
"m4",
"[",
"j",
"+",
"4",
"]",
";",
"m3",
"[",
"i",
"+",
"2",
"]",
"=",
"m4",
"[",
"j",
"+",
"12",
"]",
";",
"j",
"++",
";",
"}",
"return",
"m3",
";",
"}",
"}"
] | Provides static methods for matrix manipulation. | [
"Provides",
"static",
"methods",
"for",
"matrix",
"manipulation",
"."
] | [
"//skip row #3"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13c4afda152732f56625235183d5e33aa5a2b5c2 | atlarge-research/granula | granula-visualizer/src/main/java/science/atlarge/granula/visualizer/VisualizerManager.java | [
"Apache-2.0"
] | Java | VisualizerManager | /**
* Created by wlngai on 6/30/16.
*/ | Created by wlngai on 6/30/16. | [
"Created",
"by",
"wlngai",
"on",
"6",
"/",
"30",
"/",
"16",
"."
] | public class VisualizerManager {
public static final String STATIC_RESOURCES[] = new String[]{
"css/granula.css",
"js/chart.js",
"js/data.js",
"js/environmentview.js",
"js/job.js",
"js/operation-chart.js",
"js/operationview.js",
"js/view.js",
"js/util.js",
"js/overview.js",
"lib/bootstrap.css",
"lib/bootstrap.js",
"lib/jquery.js",
"lib/d3.min.js",
"lib/nv.d3.css",
"lib/nv.d3.js",
"lib/snap.svg-min.js",
"lib/underscore-min.js",
"visualizer.htm"
};
public static void addVisualizerResource(Execution execution) {
for (String resource : VisualizerManager.STATIC_RESOURCES) {
URL resourceUrl = VisualizerManager.class.getResource("/granula/" + resource);
Path resArcPath = Paths.get(execution.getArcPath()).resolve(resource);
try {
if (!resArcPath.getParent().toFile().exists()) {
Files.createDirectories(resArcPath.getParent());
} else if (!resArcPath.getParent().toFile().isDirectory()) {
throw new IOException("Could not write static resource to \"" + resArcPath + "\": parent is not a directory.");
}
FileUtils.copyInputStreamToFile(resourceUrl.openStream(), resArcPath.toFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | [
"public",
"class",
"VisualizerManager",
"{",
"public",
"static",
"final",
"String",
"STATIC_RESOURCES",
"[",
"]",
"=",
"new",
"String",
"[",
"]",
"{",
"\"",
"css/granula.css",
"\"",
",",
"\"",
"js/chart.js",
"\"",
",",
"\"",
"js/data.js",
"\"",
",",
"\"",
"js/environmentview.js",
"\"",
",",
"\"",
"js/job.js",
"\"",
",",
"\"",
"js/operation-chart.js",
"\"",
",",
"\"",
"js/operationview.js",
"\"",
",",
"\"",
"js/view.js",
"\"",
",",
"\"",
"js/util.js",
"\"",
",",
"\"",
"js/overview.js",
"\"",
",",
"\"",
"lib/bootstrap.css",
"\"",
",",
"\"",
"lib/bootstrap.js",
"\"",
",",
"\"",
"lib/jquery.js",
"\"",
",",
"\"",
"lib/d3.min.js",
"\"",
",",
"\"",
"lib/nv.d3.css",
"\"",
",",
"\"",
"lib/nv.d3.js",
"\"",
",",
"\"",
"lib/snap.svg-min.js",
"\"",
",",
"\"",
"lib/underscore-min.js",
"\"",
",",
"\"",
"visualizer.htm",
"\"",
"}",
";",
"public",
"static",
"void",
"addVisualizerResource",
"(",
"Execution",
"execution",
")",
"{",
"for",
"(",
"String",
"resource",
":",
"VisualizerManager",
".",
"STATIC_RESOURCES",
")",
"{",
"URL",
"resourceUrl",
"=",
"VisualizerManager",
".",
"class",
".",
"getResource",
"(",
"\"",
"/granula/",
"\"",
"+",
"resource",
")",
";",
"Path",
"resArcPath",
"=",
"Paths",
".",
"get",
"(",
"execution",
".",
"getArcPath",
"(",
")",
")",
".",
"resolve",
"(",
"resource",
")",
";",
"try",
"{",
"if",
"(",
"!",
"resArcPath",
".",
"getParent",
"(",
")",
".",
"toFile",
"(",
")",
".",
"exists",
"(",
")",
")",
"{",
"Files",
".",
"createDirectories",
"(",
"resArcPath",
".",
"getParent",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"!",
"resArcPath",
".",
"getParent",
"(",
")",
".",
"toFile",
"(",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"",
"Could not write static resource to ",
"\\\"",
"\"",
"+",
"resArcPath",
"+",
"\"",
"\\\"",
": parent is not a directory.",
"\"",
")",
";",
"}",
"FileUtils",
".",
"copyInputStreamToFile",
"(",
"resourceUrl",
".",
"openStream",
"(",
")",
",",
"resArcPath",
".",
"toFile",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Created by wlngai on 6/30/16. | [
"Created",
"by",
"wlngai",
"on",
"6",
"/",
"30",
"/",
"16",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13c8880fd68b78dd7865f6da4268761b4a6fe170 | Condum/vpn-libraries | android/src/main/java/com/google/android/libraries/privacy/ppn/PpnVpnService.java | [
"Apache-2.0"
] | Java | PpnVpnService | /** Provides PPN's VpnService implementation for Android. */ | Provides PPN's VpnService implementation for Android. | [
"Provides",
"PPN",
"'",
"s",
"VpnService",
"implementation",
"for",
"Android",
"."
] | public class PpnVpnService extends VpnService {
private static final String TAG = "PpnVpnService";
@Override
public void onCreate() {
PpnLibrary.getPpn()
.onStartService(this)
.addOnFailureListener(e -> Log.e(TAG, "Failed to start PPN service.", e));
}
@Override
public void onDestroy() {
PpnLibrary.getPpn().onStopService();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return PpnLibrary.getPpn().isStickyService() ? START_STICKY : START_NOT_STICKY;
}
@Override
public void onRevoke() {
Log.w(TAG, "VPN revoked by user.");
// This callback means that the user clicked "disconnect" in the system settings or installed a
// different VPN, so treat it the same as the user turning off PPN from the UI.
PpnLibrary.getPpn().stop();
}
@Override
protected void dump(FileDescriptor fd, PrintWriter out, String[] args) {}
} | [
"public",
"class",
"PpnVpnService",
"extends",
"VpnService",
"{",
"private",
"static",
"final",
"String",
"TAG",
"=",
"\"",
"PpnVpnService",
"\"",
";",
"@",
"Override",
"public",
"void",
"onCreate",
"(",
")",
"{",
"PpnLibrary",
".",
"getPpn",
"(",
")",
".",
"onStartService",
"(",
"this",
")",
".",
"addOnFailureListener",
"(",
"e",
"->",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Failed to start PPN service.",
"\"",
",",
"e",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onDestroy",
"(",
")",
"{",
"PpnLibrary",
".",
"getPpn",
"(",
")",
".",
"onStopService",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"onStartCommand",
"(",
"Intent",
"intent",
",",
"int",
"flags",
",",
"int",
"startId",
")",
"{",
"return",
"PpnLibrary",
".",
"getPpn",
"(",
")",
".",
"isStickyService",
"(",
")",
"?",
"START_STICKY",
":",
"START_NOT_STICKY",
";",
"}",
"@",
"Override",
"public",
"void",
"onRevoke",
"(",
")",
"{",
"Log",
".",
"w",
"(",
"TAG",
",",
"\"",
"VPN revoked by user.",
"\"",
")",
";",
"PpnLibrary",
".",
"getPpn",
"(",
")",
".",
"stop",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"dump",
"(",
"FileDescriptor",
"fd",
",",
"PrintWriter",
"out",
",",
"String",
"[",
"]",
"args",
")",
"{",
"}",
"}"
] | Provides PPN's VpnService implementation for Android. | [
"Provides",
"PPN",
"'",
"s",
"VpnService",
"implementation",
"for",
"Android",
"."
] | [
"// This callback means that the user clicked \"disconnect\" in the system settings or installed a",
"// different VPN, so treat it the same as the user turning off PPN from the UI."
] | [
{
"param": "VpnService",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "VpnService",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13c92e37aa4cb80c993c0eea2466043a0d357a00 | mjazy/zadanie_kalkulator_s | server/src/main/java/mj/netearningscalculator/server/domain/nbpapi/NBPAPIRate.java | [
"Apache-2.0"
] | Java | NBPAPIRate | /**
* Data model for rate returned as part of response from NBP API.
*
* @author MJazy
*
*/ | Data model for rate returned as part of response from NBP API.
| [
"Data",
"model",
"for",
"rate",
"returned",
"as",
"part",
"of",
"response",
"from",
"NBP",
"API",
"."
] | public class NBPAPIRate {
@JsonProperty
private String no;
@JsonProperty
private Date effectiveDate;
@JsonProperty
private BigDecimal bid;
@JsonProperty
private BigDecimal ask;
/**
* Constructor for NBPRate class.
*
* @param no e.g. '233/C/NBP/2018'.
* @param effectiveDate e.g. '2018-11-30'.
* @param bid e.g. '3.7298'.
* @param ask e.g. '3.8052'.
*/
public NBPAPIRate(String no, Date effectiveDate, BigDecimal bid, BigDecimal ask) {
this.no = no;
this.effectiveDate = effectiveDate;
this.bid = bid;
this.ask = ask;
}
/**
* Constructor for NBPAPIRate class.
*/
public NBPAPIRate() {
}
public String getNo() {
return no;
}
public Date getEffectiveDate() {
return effectiveDate;
}
public BigDecimal getBid() {
return bid;
}
public BigDecimal getAsk() {
return ask;
}
public String toString() {
return String.format("no: '%s', effectiveDate: '%s', bid: '%s', ask: '%s'", this.no, this.effectiveDate,
this.bid, this.ask);
}
} | [
"public",
"class",
"NBPAPIRate",
"{",
"@",
"JsonProperty",
"private",
"String",
"no",
";",
"@",
"JsonProperty",
"private",
"Date",
"effectiveDate",
";",
"@",
"JsonProperty",
"private",
"BigDecimal",
"bid",
";",
"@",
"JsonProperty",
"private",
"BigDecimal",
"ask",
";",
"/**\n\t * Constructor for NBPRate class.\n\t * \n\t * @param no e.g. '233/C/NBP/2018'.\n\t * @param effectiveDate e.g. '2018-11-30'.\n\t * @param bid e.g. '3.7298'.\n\t * @param ask e.g. '3.8052'.\n\t */",
"public",
"NBPAPIRate",
"(",
"String",
"no",
",",
"Date",
"effectiveDate",
",",
"BigDecimal",
"bid",
",",
"BigDecimal",
"ask",
")",
"{",
"this",
".",
"no",
"=",
"no",
";",
"this",
".",
"effectiveDate",
"=",
"effectiveDate",
";",
"this",
".",
"bid",
"=",
"bid",
";",
"this",
".",
"ask",
"=",
"ask",
";",
"}",
"/**\n\t * Constructor for NBPAPIRate class.\n\t */",
"public",
"NBPAPIRate",
"(",
")",
"{",
"}",
"public",
"String",
"getNo",
"(",
")",
"{",
"return",
"no",
";",
"}",
"public",
"Date",
"getEffectiveDate",
"(",
")",
"{",
"return",
"effectiveDate",
";",
"}",
"public",
"BigDecimal",
"getBid",
"(",
")",
"{",
"return",
"bid",
";",
"}",
"public",
"BigDecimal",
"getAsk",
"(",
")",
"{",
"return",
"ask",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"",
"no: '%s', effectiveDate: '%s', bid: '%s', ask: '%s'",
"\"",
",",
"this",
".",
"no",
",",
"this",
".",
"effectiveDate",
",",
"this",
".",
"bid",
",",
"this",
".",
"ask",
")",
";",
"}",
"}"
] | Data model for rate returned as part of response from NBP API. | [
"Data",
"model",
"for",
"rate",
"returned",
"as",
"part",
"of",
"response",
"from",
"NBP",
"API",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13ca90c42c1b0c19055449462ca28cca55914126 | angcyo/iosched | android_packages_apps_Focal/src/main/java/org/cyanogenmod/focal/ui/HudRing.java | [
"Apache-2.0"
] | Java | HudRing | /**
* Represents a ring that can be dragged on the screen
*/ | Represents a ring that can be dragged on the screen | [
"Represents",
"a",
"ring",
"that",
"can",
"be",
"dragged",
"on",
"the",
"screen"
] | public class HudRing extends ImageView implements View.OnTouchListener {
private float mLastX;
private float mLastY;
private final static float IDLE_ALPHA = 0.25f;
private final static int ANIMATION_DURATION = 120;
public HudRing(Context context) {
super(context);
}
public HudRing(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HudRing(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setOnTouchListener(this);
setAlpha(IDLE_ALPHA);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getActionMasked() == MotionEvent.ACTION_DOWN) {
mLastX = motionEvent.getRawX();
mLastY = motionEvent.getRawY();
/* mOffsetX = motionEvent.getX() - motionEvent.getRawX();
mOffsetY = motionEvent.getY() - motionEvent.getRawY();*/
animatePressDown();
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
setX(getX() + (motionEvent.getRawX() - mLastX));
setY(getY() + (motionEvent.getRawY() - mLastY));
mLastX = motionEvent.getRawX();
mLastY = motionEvent.getRawY();
} else if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
animatePressUp();
}
return true;
}
public void animatePressDown() {
animate().alpha(1.0f).setDuration(ANIMATION_DURATION).start();
}
public void animatePressUp() {
animate().alpha(IDLE_ALPHA).rotation(0).setDuration(ANIMATION_DURATION).start();
}
public void animateWorking(long duration) {
animate().rotationBy(45.0f).setDuration(duration).setInterpolator(
new DecelerateInterpolator()).start();
}
} | [
"public",
"class",
"HudRing",
"extends",
"ImageView",
"implements",
"View",
".",
"OnTouchListener",
"{",
"private",
"float",
"mLastX",
";",
"private",
"float",
"mLastY",
";",
"private",
"final",
"static",
"float",
"IDLE_ALPHA",
"=",
"0.25f",
";",
"private",
"final",
"static",
"int",
"ANIMATION_DURATION",
"=",
"120",
";",
"public",
"HudRing",
"(",
"Context",
"context",
")",
"{",
"super",
"(",
"context",
")",
";",
"}",
"public",
"HudRing",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
")",
"{",
"super",
"(",
"context",
",",
"attrs",
")",
";",
"}",
"public",
"HudRing",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
",",
"int",
"defStyle",
")",
"{",
"super",
"(",
"context",
",",
"attrs",
",",
"defStyle",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onFinishInflate",
"(",
")",
"{",
"super",
".",
"onFinishInflate",
"(",
")",
";",
"setOnTouchListener",
"(",
"this",
")",
";",
"setAlpha",
"(",
"IDLE_ALPHA",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onTouch",
"(",
"View",
"view",
",",
"MotionEvent",
"motionEvent",
")",
"{",
"if",
"(",
"motionEvent",
".",
"getActionMasked",
"(",
")",
"==",
"MotionEvent",
".",
"ACTION_DOWN",
")",
"{",
"mLastX",
"=",
"motionEvent",
".",
"getRawX",
"(",
")",
";",
"mLastY",
"=",
"motionEvent",
".",
"getRawY",
"(",
")",
";",
"/* mOffsetX = motionEvent.getX() - motionEvent.getRawX();\n mOffsetY = motionEvent.getY() - motionEvent.getRawY();*/",
"animatePressDown",
"(",
")",
";",
"}",
"else",
"if",
"(",
"motionEvent",
".",
"getAction",
"(",
")",
"==",
"MotionEvent",
".",
"ACTION_MOVE",
")",
"{",
"setX",
"(",
"getX",
"(",
")",
"+",
"(",
"motionEvent",
".",
"getRawX",
"(",
")",
"-",
"mLastX",
")",
")",
";",
"setY",
"(",
"getY",
"(",
")",
"+",
"(",
"motionEvent",
".",
"getRawY",
"(",
")",
"-",
"mLastY",
")",
")",
";",
"mLastX",
"=",
"motionEvent",
".",
"getRawX",
"(",
")",
";",
"mLastY",
"=",
"motionEvent",
".",
"getRawY",
"(",
")",
";",
"}",
"else",
"if",
"(",
"motionEvent",
".",
"getActionMasked",
"(",
")",
"==",
"MotionEvent",
".",
"ACTION_UP",
")",
"{",
"animatePressUp",
"(",
")",
";",
"}",
"return",
"true",
";",
"}",
"public",
"void",
"animatePressDown",
"(",
")",
"{",
"animate",
"(",
")",
".",
"alpha",
"(",
"1.0f",
")",
".",
"setDuration",
"(",
"ANIMATION_DURATION",
")",
".",
"start",
"(",
")",
";",
"}",
"public",
"void",
"animatePressUp",
"(",
")",
"{",
"animate",
"(",
")",
".",
"alpha",
"(",
"IDLE_ALPHA",
")",
".",
"rotation",
"(",
"0",
")",
".",
"setDuration",
"(",
"ANIMATION_DURATION",
")",
".",
"start",
"(",
")",
";",
"}",
"public",
"void",
"animateWorking",
"(",
"long",
"duration",
")",
"{",
"animate",
"(",
")",
".",
"rotationBy",
"(",
"45.0f",
")",
".",
"setDuration",
"(",
"duration",
")",
".",
"setInterpolator",
"(",
"new",
"DecelerateInterpolator",
"(",
")",
")",
".",
"start",
"(",
")",
";",
"}",
"}"
] | Represents a ring that can be dragged on the screen | [
"Represents",
"a",
"ring",
"that",
"can",
"be",
"dragged",
"on",
"the",
"screen"
] | [] | [
{
"param": "ImageView",
"type": null
},
{
"param": "View.OnTouchListener",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ImageView",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "View.OnTouchListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13ccd9b63d2cda64e87ebfe78bc6f6dd1d5c87f3 | timfel/netbeans | java/maven/src/org/netbeans/modules/maven/options/MavenGroupPanel.java | [
"Apache-2.0"
] | Java | ComboBoxRenderer | // End of variables declaration//GEN-END:variables | End of variables declaration//GEN-END:variables | [
"End",
"of",
"variables",
"declaration",
"//",
"GEN",
"-",
"END",
":",
"variables"
] | private class ComboBoxRenderer extends DefaultListCellRenderer {
private final JSeparator separator;
public ComboBoxRenderer() {
super();
separator = new JSeparator(JSeparator.HORIZONTAL);
}
@Override
@NbBundle.Messages({
"# {0} - global maven selection",
"LBL_Global_selection={0} [Global selection]"})
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (SEPARATOR.equals(value)) {
return separator;
}
if (globalMavenValue.equals(value)) {
value = LBL_Global_selection(value);
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
} | [
"private",
"class",
"ComboBoxRenderer",
"extends",
"DefaultListCellRenderer",
"{",
"private",
"final",
"JSeparator",
"separator",
";",
"public",
"ComboBoxRenderer",
"(",
")",
"{",
"super",
"(",
")",
";",
"separator",
"=",
"new",
"JSeparator",
"(",
"JSeparator",
".",
"HORIZONTAL",
")",
";",
"}",
"@",
"Override",
"@",
"NbBundle",
".",
"Messages",
"(",
"{",
"\"",
"# {0} - global maven selection",
"\"",
",",
"\"",
"LBL_Global_selection={0} [Global selection]",
"\"",
"}",
")",
"public",
"Component",
"getListCellRendererComponent",
"(",
"JList",
"list",
",",
"Object",
"value",
",",
"int",
"index",
",",
"boolean",
"isSelected",
",",
"boolean",
"cellHasFocus",
")",
"{",
"if",
"(",
"SEPARATOR",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"separator",
";",
"}",
"if",
"(",
"globalMavenValue",
".",
"equals",
"(",
"value",
")",
")",
"{",
"value",
"=",
"LBL_Global_selection",
"(",
"value",
")",
";",
"}",
"return",
"super",
".",
"getListCellRendererComponent",
"(",
"list",
",",
"value",
",",
"index",
",",
"isSelected",
",",
"cellHasFocus",
")",
";",
"}",
"}"
] | End of variables declaration//GEN-END:variables | [
"End",
"of",
"variables",
"declaration",
"//",
"GEN",
"-",
"END",
":",
"variables"
] | [] | [
{
"param": "DefaultListCellRenderer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "DefaultListCellRenderer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13d18e2a21f3ab1e32e122b7fc068e267342c7c3 | kuozhang/customized-geronimo-devtools | plugins/org.apache.geronimo.st.v30.jaxbmodel/src/main/java/org/apache/geronimo/osgi/blueprint/Tcomponent.java | [
"Apache-2.0"
] | Java | Tcomponent | /**
*
*
* The Tcomponent type is the base type for top-level
* Blueprint components. The <bean> <reference>, <service>,
* and <reference-list> elements are all derived from
* the Tcomponent type. This type defines an id attribute
* that is used create references between different components.
* Component elements can also be inlined within other component
* definitions. The id attribute is not valid when inlined.
*
*
*
* <p>Java class for Tcomponent complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Tcomponent">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="activation" type="{http://www.osgi.org/xmlns/blueprint/v1.0.0}Tactivation" />
* <attribute name="depends-on" type="{http://www.osgi.org/xmlns/blueprint/v1.0.0}TdependsOn" />
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/ | The Tcomponent type is the base type for top-level
Blueprint components. The , ,
and elements are all derived from
the Tcomponent type. This type defines an id attribute
that is used create references between different components.
Component elements can also be inlined within other component
definitions. The id attribute is not valid when inlined.
Java class for Tcomponent complex type.
The following schema fragment specifies the expected content contained within this class.
| [
"The",
"Tcomponent",
"type",
"is",
"the",
"base",
"type",
"for",
"top",
"-",
"level",
"Blueprint",
"components",
".",
"The",
"and",
"elements",
"are",
"all",
"derived",
"from",
"the",
"Tcomponent",
"type",
".",
"This",
"type",
"defines",
"an",
"id",
"attribute",
"that",
"is",
"used",
"create",
"references",
"between",
"different",
"components",
".",
"Component",
"elements",
"can",
"also",
"be",
"inlined",
"within",
"other",
"component",
"definitions",
".",
"The",
"id",
"attribute",
"is",
"not",
"valid",
"when",
"inlined",
".",
"Java",
"class",
"for",
"Tcomponent",
"complex",
"type",
".",
"The",
"following",
"schema",
"fragment",
"specifies",
"the",
"expected",
"content",
"contained",
"within",
"this",
"class",
"."
] | @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Tcomponent")
@XmlRootElement(name = "component")
public abstract class Tcomponent {
@XmlAttribute
protected Tactivation activation;
@XmlAttribute(name = "depends-on")
protected List<String> dependsOn;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
/**
* Gets the value of the activation property.
*
* @return
* possible object is
* {@link Tactivation }
*
*/
public Tactivation getActivation() {
return activation;
}
/**
* Sets the value of the activation property.
*
* @param value
* allowed object is
* {@link Tactivation }
*
*/
public void setActivation(Tactivation value) {
this.activation = value;
}
/**
* Gets the value of the dependsOn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dependsOn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDependsOn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDependsOn() {
if (dependsOn == null) {
dependsOn = new ArrayList<String>();
}
return this.dependsOn;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | [
"@",
"XmlAccessorType",
"(",
"XmlAccessType",
".",
"FIELD",
")",
"@",
"XmlType",
"(",
"name",
"=",
"\"",
"Tcomponent",
"\"",
")",
"@",
"XmlRootElement",
"(",
"name",
"=",
"\"",
"component",
"\"",
")",
"public",
"abstract",
"class",
"Tcomponent",
"{",
"@",
"XmlAttribute",
"protected",
"Tactivation",
"activation",
";",
"@",
"XmlAttribute",
"(",
"name",
"=",
"\"",
"depends-on",
"\"",
")",
"protected",
"List",
"<",
"String",
">",
"dependsOn",
";",
"@",
"XmlAttribute",
"@",
"XmlJavaTypeAdapter",
"(",
"CollapsedStringAdapter",
".",
"class",
")",
"@",
"XmlID",
"protected",
"String",
"id",
";",
"/**\n * Gets the value of the activation property.\n * \n * @return\n * possible object is\n * {@link Tactivation }\n * \n */",
"public",
"Tactivation",
"getActivation",
"(",
")",
"{",
"return",
"activation",
";",
"}",
"/**\n * Sets the value of the activation property.\n * \n * @param value\n * allowed object is\n * {@link Tactivation }\n * \n */",
"public",
"void",
"setActivation",
"(",
"Tactivation",
"value",
")",
"{",
"this",
".",
"activation",
"=",
"value",
";",
"}",
"/**\n * Gets the value of the dependsOn property. \n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the dependsOn property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getDependsOn().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link String }\n * \n * \n */",
"public",
"List",
"<",
"String",
">",
"getDependsOn",
"(",
")",
"{",
"if",
"(",
"dependsOn",
"==",
"null",
")",
"{",
"dependsOn",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"}",
"return",
"this",
".",
"dependsOn",
";",
"}",
"/**\n * Gets the value of the id property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */",
"public",
"String",
"getId",
"(",
")",
"{",
"return",
"id",
";",
"}",
"/**\n * Sets the value of the id property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */",
"public",
"void",
"setId",
"(",
"String",
"value",
")",
"{",
"this",
".",
"id",
"=",
"value",
";",
"}",
"}"
] | [] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
|
13d39117b01cb177a9143a446fc37cce11e4a858 | gmelius/cordova-plugin-google-api | src/android/BatchRequestPojo.java | [
"MIT"
] | Java | BatchRequestPojo | /**
* Created by Raphael on 17.04.18.
*/ | Created by Raphael on 17.04.18. | [
"Created",
"by",
"Raphael",
"on",
"17",
".",
"04",
".",
"18",
"."
] | public class BatchRequestPojo {
private String requestMethod;
private String requestUrl;
private String jsonObject;
private Map<String,Object> urlParams;
public BatchRequestPojo(String requestMethod, String requestUrl, String jsonObject, Map<String, Object> urlParams) {
this.requestMethod = requestMethod;
this.requestUrl = requestUrl;
this.jsonObject = jsonObject;
this.urlParams = urlParams;
}
public String getRequestMethod() {
return requestMethod;
}
public String getRequestUrl() {
return requestUrl;
}
public Map<String, Object> getUrlParams() {
return urlParams;
}
public String getJsonObject() {
return jsonObject;
}
} | [
"public",
"class",
"BatchRequestPojo",
"{",
"private",
"String",
"requestMethod",
";",
"private",
"String",
"requestUrl",
";",
"private",
"String",
"jsonObject",
";",
"private",
"Map",
"<",
"String",
",",
"Object",
">",
"urlParams",
";",
"public",
"BatchRequestPojo",
"(",
"String",
"requestMethod",
",",
"String",
"requestUrl",
",",
"String",
"jsonObject",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"urlParams",
")",
"{",
"this",
".",
"requestMethod",
"=",
"requestMethod",
";",
"this",
".",
"requestUrl",
"=",
"requestUrl",
";",
"this",
".",
"jsonObject",
"=",
"jsonObject",
";",
"this",
".",
"urlParams",
"=",
"urlParams",
";",
"}",
"public",
"String",
"getRequestMethod",
"(",
")",
"{",
"return",
"requestMethod",
";",
"}",
"public",
"String",
"getRequestUrl",
"(",
")",
"{",
"return",
"requestUrl",
";",
"}",
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"getUrlParams",
"(",
")",
"{",
"return",
"urlParams",
";",
"}",
"public",
"String",
"getJsonObject",
"(",
")",
"{",
"return",
"jsonObject",
";",
"}",
"}"
] | Created by Raphael on 17.04.18. | [
"Created",
"by",
"Raphael",
"on",
"17",
".",
"04",
".",
"18",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13da6c2c976ced1d804ae5b1b890b845c8eda446 | rdsea/idac | prototype/ac.at.tuwien.mt.model/src/main/java/ac/at/tuwien/mt/model/thing/message/Property.java | [
"Apache-2.0"
] | Java | Property | /**
* Each attribute can have further properties. One of them would be if the
* attribute is used as an identifier.
*
* @author Florin Bogdan Balint
*
*/ | Each attribute can have further properties. One of them would be if the
attribute is used as an identifier.
@author Florin Bogdan Balint | [
"Each",
"attribute",
"can",
"have",
"further",
"properties",
".",
"One",
"of",
"them",
"would",
"be",
"if",
"the",
"attribute",
"is",
"used",
"as",
"an",
"identifier",
".",
"@author",
"Florin",
"Bogdan",
"Balint"
] | @SuppressWarnings("serial")
public class Property implements Serializable {
/**
* If an attribute has this flag set to TRUE, it acts as an identifier.
*/
private boolean identifier;
/**
* If an attribute has this flag set to TRUE, it means that the attribute is
* a date which represents the date of the recording. E.g., If a thing
* records a temperature, than the attribute which describes the temperature
* date will have this flag set to true.
*/
private boolean recordingDate;
/**
* If an attribute has the data type DATE, the date representation can be
* specified in this field.
*/
private String dateFormat;
public Property() {
// empty constructor
}
public Property(Document document) {
this.identifier = document.getBoolean("identifier");
this.recordingDate = document.getBoolean("recordingDate");
this.dateFormat = document.getString("dateFormat");
}
@JsonIgnore
public Document getDocument() {
Document document = new Document();
document.put("identifier", getIdentifier());
document.put("recordingDate", getRecordingDate());
if (getDateFormat() != null) {
document.put("dateFormat", getDateFormat());
}
return document;
}
/**
* If an attribute has this flag set to TRUE, it acts as an identifier.
*
* @return Boolean
*/
public boolean getIdentifier() {
return identifier;
}
/**
* @param identifier
* the identifier to set
*/
public void setIdentifier(boolean identifier) {
this.identifier = identifier;
}
/**
* If an attribute has this flag set to TRUE, it means that the attribute is
* a date which represents the date of the recording. E.g., If a thing
* records a temperature, than the attribute which describes the temperature
* date will have this flag set to true.
*
* @return the recordingDate
*/
public boolean getRecordingDate() {
return recordingDate;
}
/**
* @param recordingDate
* the recordingDate to set
*/
public void setRecordingDate(boolean recordingDate) {
this.recordingDate = recordingDate;
}
/**
* @return the dateFormat
*/
public String getDateFormat() {
return dateFormat;
}
/**
* If an attribute has the data type DATE, the date representation can be
* specified in this field.
*
* @param dateFormat
* the dateFormat to set
*/
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"",
"serial",
"\"",
")",
"public",
"class",
"Property",
"implements",
"Serializable",
"{",
"/**\n\t * If an attribute has this flag set to TRUE, it acts as an identifier.\n\t */",
"private",
"boolean",
"identifier",
";",
"/**\n\t * If an attribute has this flag set to TRUE, it means that the attribute is\n\t * a date which represents the date of the recording. E.g., If a thing\n\t * records a temperature, than the attribute which describes the temperature\n\t * date will have this flag set to true.\n\t */",
"private",
"boolean",
"recordingDate",
";",
"/**\n\t * If an attribute has the data type DATE, the date representation can be\n\t * specified in this field.\n\t */",
"private",
"String",
"dateFormat",
";",
"public",
"Property",
"(",
")",
"{",
"}",
"public",
"Property",
"(",
"Document",
"document",
")",
"{",
"this",
".",
"identifier",
"=",
"document",
".",
"getBoolean",
"(",
"\"",
"identifier",
"\"",
")",
";",
"this",
".",
"recordingDate",
"=",
"document",
".",
"getBoolean",
"(",
"\"",
"recordingDate",
"\"",
")",
";",
"this",
".",
"dateFormat",
"=",
"document",
".",
"getString",
"(",
"\"",
"dateFormat",
"\"",
")",
";",
"}",
"@",
"JsonIgnore",
"public",
"Document",
"getDocument",
"(",
")",
"{",
"Document",
"document",
"=",
"new",
"Document",
"(",
")",
";",
"document",
".",
"put",
"(",
"\"",
"identifier",
"\"",
",",
"getIdentifier",
"(",
")",
")",
";",
"document",
".",
"put",
"(",
"\"",
"recordingDate",
"\"",
",",
"getRecordingDate",
"(",
")",
")",
";",
"if",
"(",
"getDateFormat",
"(",
")",
"!=",
"null",
")",
"{",
"document",
".",
"put",
"(",
"\"",
"dateFormat",
"\"",
",",
"getDateFormat",
"(",
")",
")",
";",
"}",
"return",
"document",
";",
"}",
"/**\n\t * If an attribute has this flag set to TRUE, it acts as an identifier.\n\t * \n\t * @return Boolean\n\t */",
"public",
"boolean",
"getIdentifier",
"(",
")",
"{",
"return",
"identifier",
";",
"}",
"/**\n\t * @param identifier\n\t * the identifier to set\n\t */",
"public",
"void",
"setIdentifier",
"(",
"boolean",
"identifier",
")",
"{",
"this",
".",
"identifier",
"=",
"identifier",
";",
"}",
"/**\n\t * If an attribute has this flag set to TRUE, it means that the attribute is\n\t * a date which represents the date of the recording. E.g., If a thing\n\t * records a temperature, than the attribute which describes the temperature\n\t * date will have this flag set to true.\n\t * \n\t * @return the recordingDate\n\t */",
"public",
"boolean",
"getRecordingDate",
"(",
")",
"{",
"return",
"recordingDate",
";",
"}",
"/**\n\t * @param recordingDate\n\t * the recordingDate to set\n\t */",
"public",
"void",
"setRecordingDate",
"(",
"boolean",
"recordingDate",
")",
"{",
"this",
".",
"recordingDate",
"=",
"recordingDate",
";",
"}",
"/**\n\t * @return the dateFormat\n\t */",
"public",
"String",
"getDateFormat",
"(",
")",
"{",
"return",
"dateFormat",
";",
"}",
"/**\n\t * If an attribute has the data type DATE, the date representation can be\n\t * specified in this field.\n\t * \n\t * @param dateFormat\n\t * the dateFormat to set\n\t */",
"public",
"void",
"setDateFormat",
"(",
"String",
"dateFormat",
")",
"{",
"this",
".",
"dateFormat",
"=",
"dateFormat",
";",
"}",
"}"
] | Each attribute can have further properties. | [
"Each",
"attribute",
"can",
"have",
"further",
"properties",
"."
] | [
"// empty constructor"
] | [
{
"param": "Serializable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13e246a3470429a857a9e58ce796cede71c578b3 | carstenartur/gitblit | src/main/java/com/gitblit/wicket/GitblitRedirectException.java | [
"Apache-2.0"
] | Java | GitblitRedirectException | /**
* This exception bypasses the servlet container rewriting relative redirect
* urls. The container can and does decode the carefully crafted %2F path
* separators on a redirect. :( Bad, bad servlet container.
*
* org.eclipse.jetty.server.Response#L447: String path=uri.getDecodedPath();
*
* @author James Moger
*/ | This exception bypasses the servlet container rewriting relative redirect
urls. The container can and does decode the carefully crafted %2F path
separators on a redirect. :( Bad, bad servlet container.
@author James Moger | [
"This",
"exception",
"bypasses",
"the",
"servlet",
"container",
"rewriting",
"relative",
"redirect",
"urls",
".",
"The",
"container",
"can",
"and",
"does",
"decode",
"the",
"carefully",
"crafted",
"%2F",
"path",
"separators",
"on",
"a",
"redirect",
".",
":",
"(",
"Bad",
"bad",
"servlet",
"container",
".",
"@author",
"James",
"Moger"
] | public class GitblitRedirectException extends RestartResponseException {
private static final long serialVersionUID = 1L;
public <C extends Page> GitblitRedirectException(Class<C> pageClass) {
this(pageClass, null);
}
public <C extends Page> GitblitRedirectException(Class<C> pageClass, PageParameters params) {
super(pageClass, params);
RequestCycle cycle = RequestCycle.get();
String absoluteUrl = GitBlitRequestUtils.toAbsoluteUrl(pageClass,params);
cycle.scheduleRequestHandlerAfterCurrent(new RedirectRequestHandler(absoluteUrl));
}
} | [
"public",
"class",
"GitblitRedirectException",
"extends",
"RestartResponseException",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"public",
"<",
"C",
"extends",
"Page",
">",
"GitblitRedirectException",
"(",
"Class",
"<",
"C",
">",
"pageClass",
")",
"{",
"this",
"(",
"pageClass",
",",
"null",
")",
";",
"}",
"public",
"<",
"C",
"extends",
"Page",
">",
"GitblitRedirectException",
"(",
"Class",
"<",
"C",
">",
"pageClass",
",",
"PageParameters",
"params",
")",
"{",
"super",
"(",
"pageClass",
",",
"params",
")",
";",
"RequestCycle",
"cycle",
"=",
"RequestCycle",
".",
"get",
"(",
")",
";",
"String",
"absoluteUrl",
"=",
"GitBlitRequestUtils",
".",
"toAbsoluteUrl",
"(",
"pageClass",
",",
"params",
")",
";",
"cycle",
".",
"scheduleRequestHandlerAfterCurrent",
"(",
"new",
"RedirectRequestHandler",
"(",
"absoluteUrl",
")",
")",
";",
"}",
"}"
] | This exception bypasses the servlet container rewriting relative redirect
urls. | [
"This",
"exception",
"bypasses",
"the",
"servlet",
"container",
"rewriting",
"relative",
"redirect",
"urls",
"."
] | [] | [
{
"param": "RestartResponseException",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "RestartResponseException",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13e3fbbaeb2bd4f3b7482231698576084a5a0a69 | cowtowncoder/jackson-dataformats-binary | ion/src/main/java/com/fasterxml/jackson/dataformat/ion/jsr310/IonJavaTimeModule.java | [
"Apache-2.0"
] | Java | IonJavaTimeModule | /**
* A module that installs a collection of serializers and deserializers for java.time classes.
*/ | A module that installs a collection of serializers and deserializers for java.time classes. | [
"A",
"module",
"that",
"installs",
"a",
"collection",
"of",
"serializers",
"and",
"deserializers",
"for",
"java",
".",
"time",
"classes",
"."
] | public class IonJavaTimeModule extends SimpleModule
{
private static final long serialVersionUID = 1L;
public IonJavaTimeModule() {
super(IonJavaTimeModule.class.getName(), PackageVersion.VERSION);
addSerializer(Instant.class, IonTimestampInstantSerializer.INSTANT);
addSerializer(OffsetDateTime.class, IonTimestampInstantSerializer.OFFSET_DATE_TIME);
addSerializer(ZonedDateTime.class, IonTimestampInstantSerializer.ZONED_DATE_TIME);
addDeserializer(Instant.class, IonTimestampInstantDeserializer.INSTANT);
addDeserializer(OffsetDateTime.class, IonTimestampInstantDeserializer.OFFSET_DATE_TIME);
addDeserializer(ZonedDateTime.class, IonTimestampInstantDeserializer.ZONED_DATE_TIME);
}
} | [
"public",
"class",
"IonJavaTimeModule",
"extends",
"SimpleModule",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"public",
"IonJavaTimeModule",
"(",
")",
"{",
"super",
"(",
"IonJavaTimeModule",
".",
"class",
".",
"getName",
"(",
")",
",",
"PackageVersion",
".",
"VERSION",
")",
";",
"addSerializer",
"(",
"Instant",
".",
"class",
",",
"IonTimestampInstantSerializer",
".",
"INSTANT",
")",
";",
"addSerializer",
"(",
"OffsetDateTime",
".",
"class",
",",
"IonTimestampInstantSerializer",
".",
"OFFSET_DATE_TIME",
")",
";",
"addSerializer",
"(",
"ZonedDateTime",
".",
"class",
",",
"IonTimestampInstantSerializer",
".",
"ZONED_DATE_TIME",
")",
";",
"addDeserializer",
"(",
"Instant",
".",
"class",
",",
"IonTimestampInstantDeserializer",
".",
"INSTANT",
")",
";",
"addDeserializer",
"(",
"OffsetDateTime",
".",
"class",
",",
"IonTimestampInstantDeserializer",
".",
"OFFSET_DATE_TIME",
")",
";",
"addDeserializer",
"(",
"ZonedDateTime",
".",
"class",
",",
"IonTimestampInstantDeserializer",
".",
"ZONED_DATE_TIME",
")",
";",
"}",
"}"
] | A module that installs a collection of serializers and deserializers for java.time classes. | [
"A",
"module",
"that",
"installs",
"a",
"collection",
"of",
"serializers",
"and",
"deserializers",
"for",
"java",
".",
"time",
"classes",
"."
] | [] | [
{
"param": "SimpleModule",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "SimpleModule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13e40e7a98bb95adbc44e5b281c641bcb9811f19 | maricaantonacci/alien4cloud | alien4cloud-core/src/main/java/org/alien4cloud/tosca/editor/processors/policies/DeletePolicyProcessor.java | [
"Apache-2.0"
] | Java | DeletePolicyProcessor | /**
* Delete a policy from the topology.
*/ | Delete a policy from the topology. | [
"Delete",
"a",
"policy",
"from",
"the",
"topology",
"."
] | @Slf4j
@Component
public class DeletePolicyProcessor extends AbstractPolicyProcessor<DeletePolicyOperation> {
@Inject
private TopologyService topologyService;
@Override
protected void process(Csar csar, Topology topology, DeletePolicyOperation operation, PolicyTemplate policyTemplate) {
log.debug("Removing policy template <" + operation.getPolicyName() + "> of type <" + policyTemplate.getType() + "> from the topology <"
+ topology.getId() + "> .");
topology.getPolicies().remove(operation.getPolicyName());
topologyService.unloadType(topology, policyTemplate.getType());
}
} | [
"@",
"Slf4j",
"@",
"Component",
"public",
"class",
"DeletePolicyProcessor",
"extends",
"AbstractPolicyProcessor",
"<",
"DeletePolicyOperation",
">",
"{",
"@",
"Inject",
"private",
"TopologyService",
"topologyService",
";",
"@",
"Override",
"protected",
"void",
"process",
"(",
"Csar",
"csar",
",",
"Topology",
"topology",
",",
"DeletePolicyOperation",
"operation",
",",
"PolicyTemplate",
"policyTemplate",
")",
"{",
"log",
".",
"debug",
"(",
"\"",
"Removing policy template <",
"\"",
"+",
"operation",
".",
"getPolicyName",
"(",
")",
"+",
"\"",
"> of type <",
"\"",
"+",
"policyTemplate",
".",
"getType",
"(",
")",
"+",
"\"",
"> from the topology <",
"\"",
"+",
"topology",
".",
"getId",
"(",
")",
"+",
"\"",
"> .",
"\"",
")",
";",
"topology",
".",
"getPolicies",
"(",
")",
".",
"remove",
"(",
"operation",
".",
"getPolicyName",
"(",
")",
")",
";",
"topologyService",
".",
"unloadType",
"(",
"topology",
",",
"policyTemplate",
".",
"getType",
"(",
")",
")",
";",
"}",
"}"
] | Delete a policy from the topology. | [
"Delete",
"a",
"policy",
"from",
"the",
"topology",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13e40fce7792a716b0e6754da5158fb9cd4788a9 | ImRa35/WinExpert | WinXpert/src/winexpert/Rules.java | [
"Apache-2.0"
] | Java | Rules | /**
*
* @author Ragu Balagi Karuppaiah
*/ | @author Ragu Balagi Karuppaiah | [
"@author",
"Ragu",
"Balagi",
"Karuppaiah"
] | public class Rules extends JFrame{
private static JPanel rulePanel,tech1;
private static JLabel rule1,rule2,rule3,rule4,rule5,tech;
private static JButton LetsGo;
public Rules(){
tech1=new JPanel();
tech=new JLabel("TezFueRza'18");
tech.setFont(new Font("Segoe Print", Font.BOLD, 60));
rulePanel=new JPanel(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
rule1=new JLabel("Individual participation");
rule2=new JLabel("Participants will be given the task and they have to complete it within 15 minutes");
rule3=new JLabel("No Internet access will be provided");
rule4=new JLabel("Windows XP machine will be provided without mouse");
rule5=new JLabel("Common Participation ID will be sent to your mail and this id can be used as access key for participation.");
rule1.setFont(new Font("Kristen ITC", Font.BOLD+Font.ITALIC, 20));
rule2.setFont(new Font("Kristen ITC", Font.BOLD+Font.ITALIC, 20));
rule3.setFont(new Font("Kristen ITC", Font.BOLD+Font.ITALIC, 20));
rule4.setFont(new Font("Kristen ITC", Font.BOLD+Font.ITALIC, 20));
rule5.setFont(new Font("Kristen ITC", Font.BOLD+Font.ITALIC, 20));
//L
LetsGo=new JButton("LetsGo");
c.gridx=1;
c.gridy=3;
c.insets=new Insets(10,10,10,10);
rulePanel.add(rule5,c);
c.gridx=1;
c.gridy=4;
c.insets=new Insets(10,10,10,10);
rulePanel.add(rule2,c);
c.gridx=1;
c.gridy=5;
c.insets=new Insets(10,10,10,10);
rulePanel.add(rule4,c);
c.gridx=1;
c.gridy=6;
c.insets=new Insets(10,10,10,10);
rulePanel.add(rule3,c);
c.gridx=1;
c.gridy=7;
c.insets=new Insets(10,10,10,10);
rulePanel.add(rule1,c);
c.gridx=1;
c.gridy=8;
c.insets=new Insets(10,10,10,10);
rulePanel.add(LetsGo,c);
rule1.setForeground(Color.WHITE);
rule2.setForeground(Color.WHITE);
rule3.setForeground(Color.WHITE);
rule4.setForeground(Color.WHITE);
rule5.setForeground(Color.WHITE);
rulePanel.setBackground(Color.BLACK);
tech1.setBackground(Color.BLACK);
tech.setForeground(Color.WHITE);
tech1.add(tech);
LetsGo.setFont(new Font("MV Boli", Font.BOLD, 25));
LetsGo.setBackground(Color.BLACK);
LetsGo.setForeground(Color.WHITE);
LetsGo.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
}
public void keyTyped (KeyEvent e){
}
public void keyReleased (KeyEvent e){
if (e.getKeyCode() == 10) {
new UserId();
setVisible(false);
dispose();
}
}
});
add(tech1,BorderLayout.NORTH);
add(rulePanel);
setSize(Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height);
setCursor(getToolkit().createCustomCursor(new BufferedImage( 1, 1, BufferedImage.TYPE_INT_ARGB ),new Point(),null ) );
setUndecorated(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
}
} | [
"public",
"class",
"Rules",
"extends",
"JFrame",
"{",
"private",
"static",
"JPanel",
"rulePanel",
",",
"tech1",
";",
"private",
"static",
"JLabel",
"rule1",
",",
"rule2",
",",
"rule3",
",",
"rule4",
",",
"rule5",
",",
"tech",
";",
"private",
"static",
"JButton",
"LetsGo",
";",
"public",
"Rules",
"(",
")",
"{",
"tech1",
"=",
"new",
"JPanel",
"(",
")",
";",
"tech",
"=",
"new",
"JLabel",
"(",
"\"",
"TezFueRza'18",
"\"",
")",
";",
"tech",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Segoe Print",
"\"",
",",
"Font",
".",
"BOLD",
",",
"60",
")",
")",
";",
"rulePanel",
"=",
"new",
"JPanel",
"(",
"new",
"GridBagLayout",
"(",
")",
")",
";",
"GridBagConstraints",
"c",
"=",
"new",
"GridBagConstraints",
"(",
")",
";",
"rule1",
"=",
"new",
"JLabel",
"(",
"\"",
"Individual participation",
"\"",
")",
";",
"rule2",
"=",
"new",
"JLabel",
"(",
"\"",
"Participants will be given the task and they have to complete it within 15 minutes",
"\"",
")",
";",
"rule3",
"=",
"new",
"JLabel",
"(",
"\"",
"No Internet access will be provided",
"\"",
")",
";",
"rule4",
"=",
"new",
"JLabel",
"(",
"\"",
"Windows XP machine will be provided without mouse",
"\"",
")",
";",
"rule5",
"=",
"new",
"JLabel",
"(",
"\"",
"Common Participation ID will be sent to your mail and this id can be used as access key for participation.",
"\"",
")",
";",
"rule1",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Kristen ITC",
"\"",
",",
"Font",
".",
"BOLD",
"+",
"Font",
".",
"ITALIC",
",",
"20",
")",
")",
";",
"rule2",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Kristen ITC",
"\"",
",",
"Font",
".",
"BOLD",
"+",
"Font",
".",
"ITALIC",
",",
"20",
")",
")",
";",
"rule3",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Kristen ITC",
"\"",
",",
"Font",
".",
"BOLD",
"+",
"Font",
".",
"ITALIC",
",",
"20",
")",
")",
";",
"rule4",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Kristen ITC",
"\"",
",",
"Font",
".",
"BOLD",
"+",
"Font",
".",
"ITALIC",
",",
"20",
")",
")",
";",
"rule5",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"Kristen ITC",
"\"",
",",
"Font",
".",
"BOLD",
"+",
"Font",
".",
"ITALIC",
",",
"20",
")",
")",
";",
"LetsGo",
"=",
"new",
"JButton",
"(",
"\"",
"LetsGo",
"\"",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"3",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"rule5",
",",
"c",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"4",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"rule2",
",",
"c",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"5",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"rule4",
",",
"c",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"6",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"rule3",
",",
"c",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"7",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"rule1",
",",
"c",
")",
";",
"c",
".",
"gridx",
"=",
"1",
";",
"c",
".",
"gridy",
"=",
"8",
";",
"c",
".",
"insets",
"=",
"new",
"Insets",
"(",
"10",
",",
"10",
",",
"10",
",",
"10",
")",
";",
"rulePanel",
".",
"add",
"(",
"LetsGo",
",",
"c",
")",
";",
"rule1",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"rule2",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"rule3",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"rule4",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"rule5",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"rulePanel",
".",
"setBackground",
"(",
"Color",
".",
"BLACK",
")",
";",
"tech1",
".",
"setBackground",
"(",
"Color",
".",
"BLACK",
")",
";",
"tech",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"tech1",
".",
"add",
"(",
"tech",
")",
";",
"LetsGo",
".",
"setFont",
"(",
"new",
"Font",
"(",
"\"",
"MV Boli",
"\"",
",",
"Font",
".",
"BOLD",
",",
"25",
")",
")",
";",
"LetsGo",
".",
"setBackground",
"(",
"Color",
".",
"BLACK",
")",
";",
"LetsGo",
".",
"setForeground",
"(",
"Color",
".",
"WHITE",
")",
";",
"LetsGo",
".",
"addKeyListener",
"(",
"new",
"KeyListener",
"(",
")",
"{",
"public",
"void",
"keyPressed",
"(",
"KeyEvent",
"e",
")",
"{",
"}",
"public",
"void",
"keyTyped",
"(",
"KeyEvent",
"e",
")",
"{",
"}",
"public",
"void",
"keyReleased",
"(",
"KeyEvent",
"e",
")",
"{",
"if",
"(",
"e",
".",
"getKeyCode",
"(",
")",
"==",
"10",
")",
"{",
"new",
"UserId",
"(",
")",
";",
"setVisible",
"(",
"false",
")",
";",
"dispose",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"add",
"(",
"tech1",
",",
"BorderLayout",
".",
"NORTH",
")",
";",
"add",
"(",
"rulePanel",
")",
";",
"setSize",
"(",
"Toolkit",
".",
"getDefaultToolkit",
"(",
")",
".",
"getScreenSize",
"(",
")",
".",
"width",
",",
"Toolkit",
".",
"getDefaultToolkit",
"(",
")",
".",
"getScreenSize",
"(",
")",
".",
"height",
")",
";",
"setCursor",
"(",
"getToolkit",
"(",
")",
".",
"createCustomCursor",
"(",
"new",
"BufferedImage",
"(",
"1",
",",
"1",
",",
"BufferedImage",
".",
"TYPE_INT_ARGB",
")",
",",
"new",
"Point",
"(",
")",
",",
"null",
")",
")",
";",
"setUndecorated",
"(",
"true",
")",
";",
"setDefaultCloseOperation",
"(",
"JFrame",
".",
"DO_NOTHING_ON_CLOSE",
")",
";",
"setVisible",
"(",
"true",
")",
";",
"}",
"}"
] | @author Ragu Balagi Karuppaiah | [
"@author",
"Ragu",
"Balagi",
"Karuppaiah"
] | [
"//L\r"
] | [
{
"param": "JFrame",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "JFrame",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13e744a8ee3102c4a339fdfde7f3ec8e435dd2ea | Yujiao001/demo | src/com/cn/leecode/Permutations.java | [
"Apache-2.0"
] | Java | Permutations | /*
* Given a collection of numbers, return all possible permutations.
* For example,
* [1,2,3] have the following permutations:
* [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
*/ | Given a collection of numbers, return all possible permutations. | [
"Given",
"a",
"collection",
"of",
"numbers",
"return",
"all",
"possible",
"permutations",
"."
] | public class Permutations {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
List<List<Integer>> tmp = new ArrayList<List<Integer>>();
for (List<Integer> list : result) {
for (int j = 0; j <= list.size(); j++) {
List<Integer> item = new ArrayList<Integer>(list);
item.add(j, num[i]);
tmp.add(item);
}
}
result = tmp;
}
return result;
}
/*****************************************************************************/
// This method cannot handle cases that the array of num has same elements;
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
dfs(result, new ArrayList<Integer>(), num);
return result;
}
public void dfs(List<List<Integer>> result, List<Integer> list, int[] num) {
if (list.size() == num.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < num.length; i++) {
if (list.indexOf(num[i]) == -1) {
list.add(num[i]);
dfs(result, list, num);
list.remove(list.size() - 1);
}
}
}
} | [
"public",
"class",
"Permutations",
"{",
"public",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"permute",
"(",
"int",
"[",
"]",
"num",
")",
"{",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"List",
"<",
"Integer",
">",
">",
"(",
")",
";",
"result",
".",
"add",
"(",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"num",
".",
"length",
";",
"i",
"++",
")",
"{",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"tmp",
"=",
"new",
"ArrayList",
"<",
"List",
"<",
"Integer",
">",
">",
"(",
")",
";",
"for",
"(",
"List",
"<",
"Integer",
">",
"list",
":",
"result",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<=",
"list",
".",
"size",
"(",
")",
";",
"j",
"++",
")",
"{",
"List",
"<",
"Integer",
">",
"item",
"=",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
"list",
")",
";",
"item",
".",
"add",
"(",
"j",
",",
"num",
"[",
"i",
"]",
")",
";",
"tmp",
".",
"add",
"(",
"item",
")",
";",
"}",
"}",
"result",
"=",
"tmp",
";",
"}",
"return",
"result",
";",
"}",
"/*****************************************************************************/",
"public",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"permute",
"(",
"int",
"[",
"]",
"num",
")",
"{",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"List",
"<",
"Integer",
">",
">",
"(",
")",
";",
"dfs",
"(",
"result",
",",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
")",
",",
"num",
")",
";",
"return",
"result",
";",
"}",
"public",
"void",
"dfs",
"(",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"result",
",",
"List",
"<",
"Integer",
">",
"list",
",",
"int",
"[",
"]",
"num",
")",
"{",
"if",
"(",
"list",
".",
"size",
"(",
")",
"==",
"num",
".",
"length",
")",
"{",
"result",
".",
"add",
"(",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
"list",
")",
")",
";",
"return",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"num",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"list",
".",
"indexOf",
"(",
"num",
"[",
"i",
"]",
")",
"==",
"-",
"1",
")",
"{",
"list",
".",
"add",
"(",
"num",
"[",
"i",
"]",
")",
";",
"dfs",
"(",
"result",
",",
"list",
",",
"num",
")",
";",
"list",
".",
"remove",
"(",
"list",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"}",
"}",
"}"
] | Given a collection of numbers, return all possible permutations. | [
"Given",
"a",
"collection",
"of",
"numbers",
"return",
"all",
"possible",
"permutations",
"."
] | [
"// This method cannot handle cases that the array of num has same elements;"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13e9f5e7bf98cffb291c82e10da99455baa7cf4d | tjs4571/ker | native/demo/ker/src/main/java/cn/kkmofang/ker/Native.java | [
"MIT"
] | Java | Native | /**
* Created by zhanghailong on 2018/12/11.
*/ | Created by zhanghailong on 2018/12/11. | [
"Created",
"by",
"zhanghailong",
"on",
"2018",
"/",
"12",
"/",
"11",
"."
] | public final class Native {
public static String getPrototype(Class<?> isa) {
if(isa == null) {
return null;
}
if(isa != Object.class) {
JSPrototype p = isa.getAnnotation(JSPrototype.class);
if(p != null) {
if("".equals(p.value())){
return isa.getName().replace(".","_");
} else {
return p.value();
}
}
}
for(Class<?> i : isa.getInterfaces()) {
JSPrototype p = i.getAnnotation(JSPrototype.class);
if(p != null) {
if("".equals(p.value())){
return i.getName().replace(".","_");
} else {
return p.value();
}
}
}
return getPrototype(isa.getSuperclass());
}
public static String getPrototype(Object object) {
if(object == null) {
return null;
}
return getPrototype(object.getClass());
}
public static JSObject allocJSObject(long kerObject) {
return new JSObject(kerObject);
}
public static void pushObject(long jsContext,Object object) {
if(object == null) {
JSContext.PushUndefined(jsContext);
} else if(object instanceof Integer || object instanceof Short){
JSContext.PushInt(jsContext,((Number) object).intValue());
} else if(object instanceof Double || object instanceof Float){
JSContext.PushNumber(jsContext,((Number) object).doubleValue());
} else if(object instanceof Long){
if(((Number) object).intValue() == ((Number) object).longValue()) {
JSContext.PushInt(jsContext,((Number) object).intValue());
} else {
JSContext.PushString(jsContext,object.toString());
}
} else if(object instanceof String) {
JSContext.PushString(jsContext, (String) object);
} else if(object instanceof Boolean) {
JSContext.PushBoolean(jsContext, (boolean) object);
} else if(object instanceof byte[]) {
JSContext.PushBytes(jsContext, (byte[]) object);
} else if(object instanceof Iterable) {
JSContext.PushArray(jsContext);
int i = 0;
for (Object v : (Iterable) object) {
JSContext.PushInt(jsContext, i);
pushObject(jsContext,v);
JSContext.PutProp(jsContext, -3);
i++;
}
} else if(object.getClass().isArray()) {
JSContext.PushArray(jsContext);
int n = Array.getLength(object);
for (int i = 0; i < n; i++) {
Object v = Array.get(object, i);
JSContext.PushInt(jsContext, i);
pushObject(jsContext,v);
JSContext.PutProp(jsContext, -3);
}
} else if(object instanceof Map) {
JSContext.PushObject(jsContext);
Map m = (Map) object;
for (Object key : m.keySet()) {
JSContext.PushString(jsContext, JSContext.stringValue(key, ""));
pushObject(jsContext, m.get(key));
JSContext.PutProp(jsContext, -3);
}
} else if(object instanceof JSONString) {
JSContext.PushJSONString(jsContext, ((JSONString) object).string);
} else if(object instanceof JSObject) {
JSContext.PushJSObject(jsContext,(JSObject) object);
} else {
String name = Native.getPrototype(object);
if(name == null) {
JSContext.PushObject(jsContext);
for(Field fd : object.getClass().getFields()) {
try {
Object v = fd.get(object);
if(v != null) {
JSContext.PushString(jsContext, fd.getName());
Native.pushObject(jsContext, v);
JSContext.PutProp(jsContext,-3);
}
} catch (IllegalAccessException e) {
Log.e("ker",Log.getStackTraceString(e));
}
}
} else {
JSContext.PushObject(jsContext, object,name);
}
}
}
public static Object toObject(long jsContext,int idx) {
if(idx >= 0) {
return null;
}
switch (JSContext.GetType(jsContext,idx)) {
case JSContext.TYPE_BOOLEAN:
return JSContext.ToBoolean(jsContext,idx);
case JSContext.TYPE_NUMBER:
return JSContext.ToNumber(jsContext,idx);
case JSContext.TYPE_STRING:
return JSContext.ToString(jsContext,idx);
case JSContext.TYPE_BUFFER:
return JSContext.ToBytes(jsContext,idx);
case JSContext.TYPE_OBJECT:
if(JSContext.IsArray(jsContext,idx)) {
List<Object> m = new LinkedList<>();
JSContext.EnumArray(jsContext,idx);
while(JSContext.Next(jsContext,-1,true)) {
Object value = toObject(jsContext,-1);
if(value != null) {
m.add(value);
}
JSContext.Pop(jsContext,2);
}
JSContext.Pop(jsContext);
return m;
} else {
Object v = JSContext.ToObject(jsContext,idx);
if(v == null) {
Map<String,Object> m = new TreeMap<>();
JSContext.EnumObject(jsContext,idx);
while(JSContext.Next(jsContext,-1,true)) {
String key = JSContext.ToString(jsContext,-2);
Object value = toObject(jsContext,-1);
if(key != null && value != null) {
m.put(key,value);
}
JSContext.Pop(jsContext,2);
}
JSContext.Pop(jsContext);
return m;
} else {
return v;
}
}
case JSContext.TYPE_LIGHTFUNC:
return JSContext.ToJSObject(jsContext,idx);
}
return null;
}
public static int getImageWidth(Object object) {
if(object instanceof BitmapDrawable) {
return ((BitmapDrawable) object).getBitmap().getWidth();
}
if(object instanceof Image) {
return ((Image) object).getBitmap().getWidth();
}
return 0;
}
public static int getImageHeight(Object object) {
if(object instanceof BitmapDrawable) {
return ((BitmapDrawable) object).getBitmap().getHeight();
}
if(object instanceof Image) {
return ((Image) object).getBitmap().getHeight();
}
return 0;
}
public static byte[] getImageData(Object object) {
Bitmap bitmap = null;
if(object instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) object).getBitmap();
}
if(object instanceof Image) {
bitmap = ((Image) object).getBitmap();
}
if(bitmap != null) {
if(bitmap.getConfig() == Bitmap.Config.ARGB_8888) {
ByteBuffer data = ByteBuffer.allocate(bitmap.getWidth() * bitmap.getHeight() * 4);
bitmap.copyPixelsToBuffer(data);
return data.array();
} else {
Bitmap b = bitmap.copy(Bitmap.Config.ARGB_8888,false);
ByteBuffer data = ByteBuffer.allocate(bitmap.getWidth() * bitmap.getHeight() * 4);
b.copyPixelsToBuffer(data);
b.recycle();
return data.array();
}
}
return null;
}
public static Object getImageWithCache(String URI,String basePath) {
return null;
}
public static void getImage(App app, long imageObject,String URI,String basePath,long queuePtr) {
final KerObject object = new KerObject(imageObject);
final KerQueue queue = new KerQueue(queuePtr);
final Context context = app.activity().getApplicationContext();
if(!URI.contains("://")) {
URI = basePath + "/" + URI;
}
final Drawable image = ImageCache.getDefaultImageCache().getImageWithCache(URI);
if(image != null) {
queue.async(new Runnable() {
@Override
public void run() {
Native.setImage(object.ptr(),image);
queue.recycle();
object.recycle();
}
});
} else {
ImageCache.getDefaultImageCache().getImage(context, URI, new ImageCache.Callback() {
@Override
public void onError(Throwable ex) {
Log.e("ker",Log.getStackTraceString(ex));
queue.async(new Runnable() {
@Override
public void run() {
Native.setImage(object.ptr(),null);
queue.recycle();
object.recycle();
}
});
}
@Override
public void onImage(final Drawable image) {
queue.async(new Runnable() {
@Override
public void run() {
Native.setImage(object.ptr(),image);
queue.recycle();
object.recycle();
}
});
}
});
}
}
public static void viewObtain(Object view,long viewObject) {
if(view instanceof IKerView) {
((IKerView) view).obtain(viewObject);
}
}
public static void viewRecycle(Object view,long viewObject) {
if(view instanceof IKerView) {
((IKerView) view).recycle(viewObject);
}
}
public static void viewSetAttribute(Object view,long viewObject,String key,String value) {
if(view instanceof IKerView) {
((IKerView) view).setAttributeValue(viewObject,key,value);
}
}
public static void viewSetFrame(Object view,long viewObject,float x,float y,float width,float height) {
if(view instanceof View) {
Rect frame = new Rect();
frame.x = (int) (x);
frame.y = (int) (y);
frame.width = (int) Math.ceil(width);
frame.height = (int) Math.ceil(height);
((View) view).setTag(R.id.ker_frame,frame);
ViewParent p = ((View) view).getParent();
if(p != null) {
p.requestLayout();
}
}
}
public static void viewSetContentSize(Object view,long viewObject,float width,float height) {
}
public static void viewSetContentOffset(Object view,long viewObject,float x,float y,boolean animated) {
if(view instanceof View) {
Context context = ((View) view).getContext();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
((View) view).scrollTo((int) (x * metrics.density),(int) (y * metrics.density));
}
}
public static float viewGetContentOffsetX(Object view,long viewObject) {
if(view instanceof View) {
Context context = ((View) view).getContext();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return ((View) view).getScrollX() / metrics.density;
}
return 0;
}
public static float viewGetContentOffsetY(Object view,long viewObject) {
if(view instanceof View) {
Context context = ((View) view).getContext();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return ((View) view).getScrollY() / metrics.density;
}
return 0;
}
public static void viewAddSubview(Object view,long viewObject,Object subview,int position) {
ViewGroup contentView = null;
if(view instanceof IKerView) {
contentView = ((IKerView) view).contentView();
} else if(view instanceof View) {
contentView = ((View) view).findViewById(R.id.ker_contentView);
}
if(contentView == null && view instanceof ViewGroup) {
contentView = (ViewGroup) view;
}
if(subview instanceof View) {
ViewParent p = ((View) subview).getParent();
if(p != null) {
if(p == view) {
return ;
}
if(p instanceof ViewGroup) {
((ViewGroup) p).removeView((View) subview);
}
}
if(contentView != null) {
if(position ==1) {
contentView.addView((View) subview,0);
} else {
contentView.addView((View) subview);
}
}
}
}
public static void viewRemoveView(Object view,long viewObject) {
if(view instanceof View) {
ViewParent p = ((View) view).getParent();
if(p != null && p instanceof ViewGroup) {
((ViewGroup) p).removeView((View) view);
}
}
}
public static void viewEvaluateJavaScript(Object view,long viewObject,String code) {
if(view instanceof IKerView) {
((IKerView) view).evaluateJavaScript(viewObject,code);
}
}
public static void appendText(SpannableStringBuilder string,String text,String family,float size,boolean bold,boolean italic,int color) {
if(text == null){
return;
}
SpannableString span = new SpannableString(text);
int length = text.length();
span.setSpan(new AbsoluteSizeSpan((int) Math.ceil( size)), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new ForegroundColorSpan(color), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if(bold) {
span.setSpan(new StyleSpan(Typeface.BOLD), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if(italic) {
span.setSpan(new StyleSpan(Typeface.ITALIC), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if(family != null && !"".equals(family)) {
Typeface f = Typeface.create(family,Typeface.NORMAL);
if(f != null) {
span.setSpan(new StyleSpan(f.getStyle()), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
string.append(span);
}
public static void appendImage(SpannableStringBuilder string, final Object image, final int width, final int height, final int left, int top, int right, int bottom) {
if(image == null) {
return ;
}
if(image instanceof Drawable || image instanceof Image) {
SpannableString span = new SpannableString("...");
span.setSpan(new DynamicDrawableSpan() {
@Override
public Drawable getDrawable() {
Drawable drawable = null;
if(image instanceof Drawable) {
drawable = (Drawable) image;
} else if(image instanceof Image) {
drawable = ((Image) image).getDrawable();
}
android.graphics.Rect bounds = drawable.getBounds();
if(width != 0) {
bounds.right = width;
}
if(height != 0) {
bounds.bottom = height;
}
drawable.setBounds(bounds);
return drawable;
}
},0,3,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
string.append(span);
}
}
public static void viewSetAttributedText(Object view,long viewObject, CharSequence string) {
if(view instanceof IKerView) {
((IKerView) view).setAttributedText(viewObject,string);
} else if(view instanceof TextView) {
((TextView) view).setText(string);
}
}
public static float[] getAttributedTextSize(CharSequence string,float maxWidth) {
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
paint.setLetterSpacing(0);
}
StaticLayout v = new StaticLayout(
string,
0,
string.length(),
paint,
(int) Math.ceil(maxWidth),
Layout.Alignment.ALIGN_NORMAL,
1.0f,
0f,
false);
float[] r = new float[]{0,v.getHeight()};
for(int i=0;i<v.getLineCount();i++) {
float vv = v.getLineWidth(i);
if(vv > r[0]) {
r[0] = vv;
}
}
return r;
}
public static void viewSetImage(Object view,long viewObject, Object image) {
if(view instanceof IKerView) {
if(image instanceof Drawable) {
((IKerView) view).setImage((Drawable) image);
} else {
((IKerView) view).setImage(null);
}
} else if(view instanceof View) {
if(image instanceof Drawable) {
((View) view).setBackground((Drawable) image);
} else {
((View) view).setBackground(null);
}
}
}
public static void viewSetGravity(Object view,long viewObject,String gravity) {
}
public static void viewSetContent(Object view,long viewObject,String content,String contentType,String basePath) {
if(view instanceof IKerView) {
((IKerView) view).setContent(viewObject,content,contentType,basePath);
}
}
public static int getViewWidth(Object view) {
if(view instanceof View) {
Rect frame = (Rect) ((View) view).getTag(R.id.ker_frame);
if(frame != null) {
return frame.width;
}
return Math.max(((View) view).getWidth(),((View) view).getMeasuredWidth());
}
return 0;
}
public static int getViewHeight(Object view) {
if(view instanceof View) {
Rect frame = (Rect) ((View) view).getTag(R.id.ker_frame);
if(frame != null) {
return frame.height;
}
return Math.max(((View) view).getHeight(),((View) view).getMeasuredHeight());
}
return 0;
}
public static Object createView(App app,String name,long viewConfiguration) {
View view = null;
if(name != null && _viewClasss.containsKey(name)) {
Class<?> isa = _viewClasss.get(name);
try {
Constructor<?> init = isa.getConstructor(Context.class);
view = (View ) init.newInstance(app.activity().getApplicationContext());
} catch (Throwable e) {
Log.d("ker",Log.getStackTraceString(e));
}
}
if(view == null) {
view = new KerView(app.activity().getApplicationContext());
}
if(view instanceof IKerView){
((IKerView) view).setViewConfiguration(viewConfiguration);
}
return view;
}
public static void runApp(final App app,String URI,final Object query) {
Package.getPackage(app.activity(), URI, new Package.Callback() {
@Override
public void onError(Throwable ex) {
}
@Override
public void onLoad(Package pkg) {
App.open(app.activity(),pkg.basePath,pkg.appkey,query);
}
@Override
public void onProgress(long bytes, long total) {
}
});
}
private static Map<String,Class<?>> _viewClasss = new TreeMap<>();
public static void addViewClass(String name,Class<?> viewClass) {
_viewClasss.put(name,viewClass);
}
static {
_viewClasss.put("UILabel",KerTextView.class);
_viewClasss.put("UIView",KerView.class);
_viewClasss.put("KerButton",KerButton.class);
_viewClasss.put("WKWebView",KerWebView.class);
_viewClasss.put("UICanvasView",KerCanvasView.class);
}
public static void openlib() {
final Handler v = new Handler();
v.post(new Runnable() {
@Override
public void run() {
loop();
v.postDelayed(this,17);
}
});
}
public static void getPackage(App app, final long ptr, String URI) {
retain(ptr);
Package.getPackage(app.activity(), URI, new Package.Callback() {
@Override
public void onError(Throwable ex) {
Map<String,Object> data = new TreeMap<>();
data.put("error",ex.getLocalizedMessage());
emit(ptr,"error",data);
release(ptr);
}
@Override
public void onLoad(Package pkg) {
emit(ptr,"load",new TreeMap<>());
release(ptr);
}
@Override
public void onProgress(long bytes, long total) {
}
});
}
public static KerCanvas createCanvas(int width, int height) {
return new KerCanvas(width,height);
}
public static void displayCanvas(KerCanvas canvas,Object view) {
if(view instanceof KerCanvasView) {
((KerCanvasView) view).post(canvas.getDrawable());
} else if(view instanceof View) {
((View) view).setBackground(canvas.getDrawable());
}
}
public static void gc() {
System.gc();
}
public native static void retain(long kerObject);
public native static void release(long kerObject);
public native static void setImage(long imageObject,Object image);
public native static void loop();
public native static void emit(long ptr,String name,Object data);
public native static WebViewConfiguration getWebViewConfiguration(long kerObject);
public native static String absolutePath(long ptr,String path);
} | [
"public",
"final",
"class",
"Native",
"{",
"public",
"static",
"String",
"getPrototype",
"(",
"Class",
"<",
"?",
">",
"isa",
")",
"{",
"if",
"(",
"isa",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"isa",
"!=",
"Object",
".",
"class",
")",
"{",
"JSPrototype",
"p",
"=",
"isa",
".",
"getAnnotation",
"(",
"JSPrototype",
".",
"class",
")",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"if",
"(",
"\"",
"\"",
".",
"equals",
"(",
"p",
".",
"value",
"(",
")",
")",
")",
"{",
"return",
"isa",
".",
"getName",
"(",
")",
".",
"replace",
"(",
"\"",
".",
"\"",
",",
"\"",
"_",
"\"",
")",
";",
"}",
"else",
"{",
"return",
"p",
".",
"value",
"(",
")",
";",
"}",
"}",
"}",
"for",
"(",
"Class",
"<",
"?",
">",
"i",
":",
"isa",
".",
"getInterfaces",
"(",
")",
")",
"{",
"JSPrototype",
"p",
"=",
"i",
".",
"getAnnotation",
"(",
"JSPrototype",
".",
"class",
")",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"if",
"(",
"\"",
"\"",
".",
"equals",
"(",
"p",
".",
"value",
"(",
")",
")",
")",
"{",
"return",
"i",
".",
"getName",
"(",
")",
".",
"replace",
"(",
"\"",
".",
"\"",
",",
"\"",
"_",
"\"",
")",
";",
"}",
"else",
"{",
"return",
"p",
".",
"value",
"(",
")",
";",
"}",
"}",
"}",
"return",
"getPrototype",
"(",
"isa",
".",
"getSuperclass",
"(",
")",
")",
";",
"}",
"public",
"static",
"String",
"getPrototype",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"getPrototype",
"(",
"object",
".",
"getClass",
"(",
")",
")",
";",
"}",
"public",
"static",
"JSObject",
"allocJSObject",
"(",
"long",
"kerObject",
")",
"{",
"return",
"new",
"JSObject",
"(",
"kerObject",
")",
";",
"}",
"public",
"static",
"void",
"pushObject",
"(",
"long",
"jsContext",
",",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"JSContext",
".",
"PushUndefined",
"(",
"jsContext",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Integer",
"||",
"object",
"instanceof",
"Short",
")",
"{",
"JSContext",
".",
"PushInt",
"(",
"jsContext",
",",
"(",
"(",
"Number",
")",
"object",
")",
".",
"intValue",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Double",
"||",
"object",
"instanceof",
"Float",
")",
"{",
"JSContext",
".",
"PushNumber",
"(",
"jsContext",
",",
"(",
"(",
"Number",
")",
"object",
")",
".",
"doubleValue",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Long",
")",
"{",
"if",
"(",
"(",
"(",
"Number",
")",
"object",
")",
".",
"intValue",
"(",
")",
"==",
"(",
"(",
"Number",
")",
"object",
")",
".",
"longValue",
"(",
")",
")",
"{",
"JSContext",
".",
"PushInt",
"(",
"jsContext",
",",
"(",
"(",
"Number",
")",
"object",
")",
".",
"intValue",
"(",
")",
")",
";",
"}",
"else",
"{",
"JSContext",
".",
"PushString",
"(",
"jsContext",
",",
"object",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"String",
")",
"{",
"JSContext",
".",
"PushString",
"(",
"jsContext",
",",
"(",
"String",
")",
"object",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Boolean",
")",
"{",
"JSContext",
".",
"PushBoolean",
"(",
"jsContext",
",",
"(",
"boolean",
")",
"object",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"byte",
"[",
"]",
")",
"{",
"JSContext",
".",
"PushBytes",
"(",
"jsContext",
",",
"(",
"byte",
"[",
"]",
")",
"object",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Iterable",
")",
"{",
"JSContext",
".",
"PushArray",
"(",
"jsContext",
")",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"Object",
"v",
":",
"(",
"Iterable",
")",
"object",
")",
"{",
"JSContext",
".",
"PushInt",
"(",
"jsContext",
",",
"i",
")",
";",
"pushObject",
"(",
"jsContext",
",",
"v",
")",
";",
"JSContext",
".",
"PutProp",
"(",
"jsContext",
",",
"-",
"3",
")",
";",
"i",
"++",
";",
"}",
"}",
"else",
"if",
"(",
"object",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"JSContext",
".",
"PushArray",
"(",
"jsContext",
")",
";",
"int",
"n",
"=",
"Array",
".",
"getLength",
"(",
"object",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"Object",
"v",
"=",
"Array",
".",
"get",
"(",
"object",
",",
"i",
")",
";",
"JSContext",
".",
"PushInt",
"(",
"jsContext",
",",
"i",
")",
";",
"pushObject",
"(",
"jsContext",
",",
"v",
")",
";",
"JSContext",
".",
"PutProp",
"(",
"jsContext",
",",
"-",
"3",
")",
";",
"}",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"Map",
")",
"{",
"JSContext",
".",
"PushObject",
"(",
"jsContext",
")",
";",
"Map",
"m",
"=",
"(",
"Map",
")",
"object",
";",
"for",
"(",
"Object",
"key",
":",
"m",
".",
"keySet",
"(",
")",
")",
"{",
"JSContext",
".",
"PushString",
"(",
"jsContext",
",",
"JSContext",
".",
"stringValue",
"(",
"key",
",",
"\"",
"\"",
")",
")",
";",
"pushObject",
"(",
"jsContext",
",",
"m",
".",
"get",
"(",
"key",
")",
")",
";",
"JSContext",
".",
"PutProp",
"(",
"jsContext",
",",
"-",
"3",
")",
";",
"}",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"JSONString",
")",
"{",
"JSContext",
".",
"PushJSONString",
"(",
"jsContext",
",",
"(",
"(",
"JSONString",
")",
"object",
")",
".",
"string",
")",
";",
"}",
"else",
"if",
"(",
"object",
"instanceof",
"JSObject",
")",
"{",
"JSContext",
".",
"PushJSObject",
"(",
"jsContext",
",",
"(",
"JSObject",
")",
"object",
")",
";",
"}",
"else",
"{",
"String",
"name",
"=",
"Native",
".",
"getPrototype",
"(",
"object",
")",
";",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"JSContext",
".",
"PushObject",
"(",
"jsContext",
")",
";",
"for",
"(",
"Field",
"fd",
":",
"object",
".",
"getClass",
"(",
")",
".",
"getFields",
"(",
")",
")",
"{",
"try",
"{",
"Object",
"v",
"=",
"fd",
".",
"get",
"(",
"object",
")",
";",
"if",
"(",
"v",
"!=",
"null",
")",
"{",
"JSContext",
".",
"PushString",
"(",
"jsContext",
",",
"fd",
".",
"getName",
"(",
")",
")",
";",
"Native",
".",
"pushObject",
"(",
"jsContext",
",",
"v",
")",
";",
"JSContext",
".",
"PutProp",
"(",
"jsContext",
",",
"-",
"3",
")",
";",
"}",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"ker",
"\"",
",",
"Log",
".",
"getStackTraceString",
"(",
"e",
")",
")",
";",
"}",
"}",
"}",
"else",
"{",
"JSContext",
".",
"PushObject",
"(",
"jsContext",
",",
"object",
",",
"name",
")",
";",
"}",
"}",
"}",
"public",
"static",
"Object",
"toObject",
"(",
"long",
"jsContext",
",",
"int",
"idx",
")",
"{",
"if",
"(",
"idx",
">=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"JSContext",
".",
"GetType",
"(",
"jsContext",
",",
"idx",
")",
")",
"{",
"case",
"JSContext",
".",
"TYPE_BOOLEAN",
":",
"return",
"JSContext",
".",
"ToBoolean",
"(",
"jsContext",
",",
"idx",
")",
";",
"case",
"JSContext",
".",
"TYPE_NUMBER",
":",
"return",
"JSContext",
".",
"ToNumber",
"(",
"jsContext",
",",
"idx",
")",
";",
"case",
"JSContext",
".",
"TYPE_STRING",
":",
"return",
"JSContext",
".",
"ToString",
"(",
"jsContext",
",",
"idx",
")",
";",
"case",
"JSContext",
".",
"TYPE_BUFFER",
":",
"return",
"JSContext",
".",
"ToBytes",
"(",
"jsContext",
",",
"idx",
")",
";",
"case",
"JSContext",
".",
"TYPE_OBJECT",
":",
"if",
"(",
"JSContext",
".",
"IsArray",
"(",
"jsContext",
",",
"idx",
")",
")",
"{",
"List",
"<",
"Object",
">",
"m",
"=",
"new",
"LinkedList",
"<",
">",
"(",
")",
";",
"JSContext",
".",
"EnumArray",
"(",
"jsContext",
",",
"idx",
")",
";",
"while",
"(",
"JSContext",
".",
"Next",
"(",
"jsContext",
",",
"-",
"1",
",",
"true",
")",
")",
"{",
"Object",
"value",
"=",
"toObject",
"(",
"jsContext",
",",
"-",
"1",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"m",
".",
"add",
"(",
"value",
")",
";",
"}",
"JSContext",
".",
"Pop",
"(",
"jsContext",
",",
"2",
")",
";",
"}",
"JSContext",
".",
"Pop",
"(",
"jsContext",
")",
";",
"return",
"m",
";",
"}",
"else",
"{",
"Object",
"v",
"=",
"JSContext",
".",
"ToObject",
"(",
"jsContext",
",",
"idx",
")",
";",
"if",
"(",
"v",
"==",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"m",
"=",
"new",
"TreeMap",
"<",
">",
"(",
")",
";",
"JSContext",
".",
"EnumObject",
"(",
"jsContext",
",",
"idx",
")",
";",
"while",
"(",
"JSContext",
".",
"Next",
"(",
"jsContext",
",",
"-",
"1",
",",
"true",
")",
")",
"{",
"String",
"key",
"=",
"JSContext",
".",
"ToString",
"(",
"jsContext",
",",
"-",
"2",
")",
";",
"Object",
"value",
"=",
"toObject",
"(",
"jsContext",
",",
"-",
"1",
")",
";",
"if",
"(",
"key",
"!=",
"null",
"&&",
"value",
"!=",
"null",
")",
"{",
"m",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"JSContext",
".",
"Pop",
"(",
"jsContext",
",",
"2",
")",
";",
"}",
"JSContext",
".",
"Pop",
"(",
"jsContext",
")",
";",
"return",
"m",
";",
"}",
"else",
"{",
"return",
"v",
";",
"}",
"}",
"case",
"JSContext",
".",
"TYPE_LIGHTFUNC",
":",
"return",
"JSContext",
".",
"ToJSObject",
"(",
"jsContext",
",",
"idx",
")",
";",
"}",
"return",
"null",
";",
"}",
"public",
"static",
"int",
"getImageWidth",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"BitmapDrawable",
")",
"{",
"return",
"(",
"(",
"BitmapDrawable",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
".",
"getWidth",
"(",
")",
";",
"}",
"if",
"(",
"object",
"instanceof",
"Image",
")",
"{",
"return",
"(",
"(",
"Image",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
".",
"getWidth",
"(",
")",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"int",
"getImageHeight",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"BitmapDrawable",
")",
"{",
"return",
"(",
"(",
"BitmapDrawable",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
".",
"getHeight",
"(",
")",
";",
"}",
"if",
"(",
"object",
"instanceof",
"Image",
")",
"{",
"return",
"(",
"(",
"Image",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
".",
"getHeight",
"(",
")",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"byte",
"[",
"]",
"getImageData",
"(",
"Object",
"object",
")",
"{",
"Bitmap",
"bitmap",
"=",
"null",
";",
"if",
"(",
"object",
"instanceof",
"BitmapDrawable",
")",
"{",
"bitmap",
"=",
"(",
"(",
"BitmapDrawable",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
";",
"}",
"if",
"(",
"object",
"instanceof",
"Image",
")",
"{",
"bitmap",
"=",
"(",
"(",
"Image",
")",
"object",
")",
".",
"getBitmap",
"(",
")",
";",
"}",
"if",
"(",
"bitmap",
"!=",
"null",
")",
"{",
"if",
"(",
"bitmap",
".",
"getConfig",
"(",
")",
"==",
"Bitmap",
".",
"Config",
".",
"ARGB_8888",
")",
"{",
"ByteBuffer",
"data",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"bitmap",
".",
"getWidth",
"(",
")",
"*",
"bitmap",
".",
"getHeight",
"(",
")",
"*",
"4",
")",
";",
"bitmap",
".",
"copyPixelsToBuffer",
"(",
"data",
")",
";",
"return",
"data",
".",
"array",
"(",
")",
";",
"}",
"else",
"{",
"Bitmap",
"b",
"=",
"bitmap",
".",
"copy",
"(",
"Bitmap",
".",
"Config",
".",
"ARGB_8888",
",",
"false",
")",
";",
"ByteBuffer",
"data",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"bitmap",
".",
"getWidth",
"(",
")",
"*",
"bitmap",
".",
"getHeight",
"(",
")",
"*",
"4",
")",
";",
"b",
".",
"copyPixelsToBuffer",
"(",
"data",
")",
";",
"b",
".",
"recycle",
"(",
")",
";",
"return",
"data",
".",
"array",
"(",
")",
";",
"}",
"}",
"return",
"null",
";",
"}",
"public",
"static",
"Object",
"getImageWithCache",
"(",
"String",
"URI",
",",
"String",
"basePath",
")",
"{",
"return",
"null",
";",
"}",
"public",
"static",
"void",
"getImage",
"(",
"App",
"app",
",",
"long",
"imageObject",
",",
"String",
"URI",
",",
"String",
"basePath",
",",
"long",
"queuePtr",
")",
"{",
"final",
"KerObject",
"object",
"=",
"new",
"KerObject",
"(",
"imageObject",
")",
";",
"final",
"KerQueue",
"queue",
"=",
"new",
"KerQueue",
"(",
"queuePtr",
")",
";",
"final",
"Context",
"context",
"=",
"app",
".",
"activity",
"(",
")",
".",
"getApplicationContext",
"(",
")",
";",
"if",
"(",
"!",
"URI",
".",
"contains",
"(",
"\"",
"://",
"\"",
")",
")",
"{",
"URI",
"=",
"basePath",
"+",
"\"",
"/",
"\"",
"+",
"URI",
";",
"}",
"final",
"Drawable",
"image",
"=",
"ImageCache",
".",
"getDefaultImageCache",
"(",
")",
".",
"getImageWithCache",
"(",
"URI",
")",
";",
"if",
"(",
"image",
"!=",
"null",
")",
"{",
"queue",
".",
"async",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"Native",
".",
"setImage",
"(",
"object",
".",
"ptr",
"(",
")",
",",
"image",
")",
";",
"queue",
".",
"recycle",
"(",
")",
";",
"object",
".",
"recycle",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"ImageCache",
".",
"getDefaultImageCache",
"(",
")",
".",
"getImage",
"(",
"context",
",",
"URI",
",",
"new",
"ImageCache",
".",
"Callback",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onError",
"(",
"Throwable",
"ex",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"ker",
"\"",
",",
"Log",
".",
"getStackTraceString",
"(",
"ex",
")",
")",
";",
"queue",
".",
"async",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"Native",
".",
"setImage",
"(",
"object",
".",
"ptr",
"(",
")",
",",
"null",
")",
";",
"queue",
".",
"recycle",
"(",
")",
";",
"object",
".",
"recycle",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onImage",
"(",
"final",
"Drawable",
"image",
")",
"{",
"queue",
".",
"async",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"Native",
".",
"setImage",
"(",
"object",
".",
"ptr",
"(",
")",
",",
"image",
")",
";",
"queue",
".",
"recycle",
"(",
")",
";",
"object",
".",
"recycle",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"public",
"static",
"void",
"viewObtain",
"(",
"Object",
"view",
",",
"long",
"viewObject",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"obtain",
"(",
"viewObject",
")",
";",
"}",
"}",
"public",
"static",
"void",
"viewRecycle",
"(",
"Object",
"view",
",",
"long",
"viewObject",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"recycle",
"(",
"viewObject",
")",
";",
"}",
"}",
"public",
"static",
"void",
"viewSetAttribute",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setAttributeValue",
"(",
"viewObject",
",",
"key",
",",
"value",
")",
";",
"}",
"}",
"public",
"static",
"void",
"viewSetFrame",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"width",
",",
"float",
"height",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Rect",
"frame",
"=",
"new",
"Rect",
"(",
")",
";",
"frame",
".",
"x",
"=",
"(",
"int",
")",
"(",
"x",
")",
";",
"frame",
".",
"y",
"=",
"(",
"int",
")",
"(",
"y",
")",
";",
"frame",
".",
"width",
"=",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"width",
")",
";",
"frame",
".",
"height",
"=",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"height",
")",
";",
"(",
"(",
"View",
")",
"view",
")",
".",
"setTag",
"(",
"R",
".",
"id",
".",
"ker_frame",
",",
"frame",
")",
";",
"ViewParent",
"p",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"p",
".",
"requestLayout",
"(",
")",
";",
"}",
"}",
"}",
"public",
"static",
"void",
"viewSetContentSize",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"float",
"width",
",",
"float",
"height",
")",
"{",
"}",
"public",
"static",
"void",
"viewSetContentOffset",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"float",
"x",
",",
"float",
"y",
",",
"boolean",
"animated",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Context",
"context",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"getContext",
"(",
")",
";",
"DisplayMetrics",
"metrics",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getDisplayMetrics",
"(",
")",
";",
"(",
"(",
"View",
")",
"view",
")",
".",
"scrollTo",
"(",
"(",
"int",
")",
"(",
"x",
"*",
"metrics",
".",
"density",
")",
",",
"(",
"int",
")",
"(",
"y",
"*",
"metrics",
".",
"density",
")",
")",
";",
"}",
"}",
"public",
"static",
"float",
"viewGetContentOffsetX",
"(",
"Object",
"view",
",",
"long",
"viewObject",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Context",
"context",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"getContext",
"(",
")",
";",
"DisplayMetrics",
"metrics",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getDisplayMetrics",
"(",
")",
";",
"return",
"(",
"(",
"View",
")",
"view",
")",
".",
"getScrollX",
"(",
")",
"/",
"metrics",
".",
"density",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"float",
"viewGetContentOffsetY",
"(",
"Object",
"view",
",",
"long",
"viewObject",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Context",
"context",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"getContext",
"(",
")",
";",
"DisplayMetrics",
"metrics",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getDisplayMetrics",
"(",
")",
";",
"return",
"(",
"(",
"View",
")",
"view",
")",
".",
"getScrollY",
"(",
")",
"/",
"metrics",
".",
"density",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"void",
"viewAddSubview",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"Object",
"subview",
",",
"int",
"position",
")",
"{",
"ViewGroup",
"contentView",
"=",
"null",
";",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"contentView",
"=",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"contentView",
"(",
")",
";",
"}",
"else",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"contentView",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"ker_contentView",
")",
";",
"}",
"if",
"(",
"contentView",
"==",
"null",
"&&",
"view",
"instanceof",
"ViewGroup",
")",
"{",
"contentView",
"=",
"(",
"ViewGroup",
")",
"view",
";",
"}",
"if",
"(",
"subview",
"instanceof",
"View",
")",
"{",
"ViewParent",
"p",
"=",
"(",
"(",
"View",
")",
"subview",
")",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"if",
"(",
"p",
"==",
"view",
")",
"{",
"return",
";",
"}",
"if",
"(",
"p",
"instanceof",
"ViewGroup",
")",
"{",
"(",
"(",
"ViewGroup",
")",
"p",
")",
".",
"removeView",
"(",
"(",
"View",
")",
"subview",
")",
";",
"}",
"}",
"if",
"(",
"contentView",
"!=",
"null",
")",
"{",
"if",
"(",
"position",
"==",
"1",
")",
"{",
"contentView",
".",
"addView",
"(",
"(",
"View",
")",
"subview",
",",
"0",
")",
";",
"}",
"else",
"{",
"contentView",
".",
"addView",
"(",
"(",
"View",
")",
"subview",
")",
";",
"}",
"}",
"}",
"}",
"public",
"static",
"void",
"viewRemoveView",
"(",
"Object",
"view",
",",
"long",
"viewObject",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"ViewParent",
"p",
"=",
"(",
"(",
"View",
")",
"view",
")",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"p",
"!=",
"null",
"&&",
"p",
"instanceof",
"ViewGroup",
")",
"{",
"(",
"(",
"ViewGroup",
")",
"p",
")",
".",
"removeView",
"(",
"(",
"View",
")",
"view",
")",
";",
"}",
"}",
"}",
"public",
"static",
"void",
"viewEvaluateJavaScript",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"String",
"code",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"evaluateJavaScript",
"(",
"viewObject",
",",
"code",
")",
";",
"}",
"}",
"public",
"static",
"void",
"appendText",
"(",
"SpannableStringBuilder",
"string",
",",
"String",
"text",
",",
"String",
"family",
",",
"float",
"size",
",",
"boolean",
"bold",
",",
"boolean",
"italic",
",",
"int",
"color",
")",
"{",
"if",
"(",
"text",
"==",
"null",
")",
"{",
"return",
";",
"}",
"SpannableString",
"span",
"=",
"new",
"SpannableString",
"(",
"text",
")",
";",
"int",
"length",
"=",
"text",
".",
"length",
"(",
")",
";",
"span",
".",
"setSpan",
"(",
"new",
"AbsoluteSizeSpan",
"(",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"size",
")",
")",
",",
"0",
",",
"length",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"span",
".",
"setSpan",
"(",
"new",
"ForegroundColorSpan",
"(",
"color",
")",
",",
"0",
",",
"length",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"if",
"(",
"bold",
")",
"{",
"span",
".",
"setSpan",
"(",
"new",
"StyleSpan",
"(",
"Typeface",
".",
"BOLD",
")",
",",
"0",
",",
"length",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"}",
"else",
"if",
"(",
"italic",
")",
"{",
"span",
".",
"setSpan",
"(",
"new",
"StyleSpan",
"(",
"Typeface",
".",
"ITALIC",
")",
",",
"0",
",",
"length",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"}",
"else",
"if",
"(",
"family",
"!=",
"null",
"&&",
"!",
"\"",
"\"",
".",
"equals",
"(",
"family",
")",
")",
"{",
"Typeface",
"f",
"=",
"Typeface",
".",
"create",
"(",
"family",
",",
"Typeface",
".",
"NORMAL",
")",
";",
"if",
"(",
"f",
"!=",
"null",
")",
"{",
"span",
".",
"setSpan",
"(",
"new",
"StyleSpan",
"(",
"f",
".",
"getStyle",
"(",
")",
")",
",",
"0",
",",
"length",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"}",
"}",
"string",
".",
"append",
"(",
"span",
")",
";",
"}",
"public",
"static",
"void",
"appendImage",
"(",
"SpannableStringBuilder",
"string",
",",
"final",
"Object",
"image",
",",
"final",
"int",
"width",
",",
"final",
"int",
"height",
",",
"final",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
")",
"{",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"image",
"instanceof",
"Drawable",
"||",
"image",
"instanceof",
"Image",
")",
"{",
"SpannableString",
"span",
"=",
"new",
"SpannableString",
"(",
"\"",
"...",
"\"",
")",
";",
"span",
".",
"setSpan",
"(",
"new",
"DynamicDrawableSpan",
"(",
")",
"{",
"@",
"Override",
"public",
"Drawable",
"getDrawable",
"(",
")",
"{",
"Drawable",
"drawable",
"=",
"null",
";",
"if",
"(",
"image",
"instanceof",
"Drawable",
")",
"{",
"drawable",
"=",
"(",
"Drawable",
")",
"image",
";",
"}",
"else",
"if",
"(",
"image",
"instanceof",
"Image",
")",
"{",
"drawable",
"=",
"(",
"(",
"Image",
")",
"image",
")",
".",
"getDrawable",
"(",
")",
";",
"}",
"android",
".",
"graphics",
".",
"Rect",
"bounds",
"=",
"drawable",
".",
"getBounds",
"(",
")",
";",
"if",
"(",
"width",
"!=",
"0",
")",
"{",
"bounds",
".",
"right",
"=",
"width",
";",
"}",
"if",
"(",
"height",
"!=",
"0",
")",
"{",
"bounds",
".",
"bottom",
"=",
"height",
";",
"}",
"drawable",
".",
"setBounds",
"(",
"bounds",
")",
";",
"return",
"drawable",
";",
"}",
"}",
",",
"0",
",",
"3",
",",
"Spanned",
".",
"SPAN_EXCLUSIVE_EXCLUSIVE",
")",
";",
"string",
".",
"append",
"(",
"span",
")",
";",
"}",
"}",
"public",
"static",
"void",
"viewSetAttributedText",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"CharSequence",
"string",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setAttributedText",
"(",
"viewObject",
",",
"string",
")",
";",
"}",
"else",
"if",
"(",
"view",
"instanceof",
"TextView",
")",
"{",
"(",
"(",
"TextView",
")",
"view",
")",
".",
"setText",
"(",
"string",
")",
";",
"}",
"}",
"public",
"static",
"float",
"[",
"]",
"getAttributedTextSize",
"(",
"CharSequence",
"string",
",",
"float",
"maxWidth",
")",
"{",
"TextPaint",
"paint",
"=",
"new",
"TextPaint",
"(",
"Paint",
".",
"ANTI_ALIAS_FLAG",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"{",
"paint",
".",
"setLetterSpacing",
"(",
"0",
")",
";",
"}",
"StaticLayout",
"v",
"=",
"new",
"StaticLayout",
"(",
"string",
",",
"0",
",",
"string",
".",
"length",
"(",
")",
",",
"paint",
",",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"maxWidth",
")",
",",
"Layout",
".",
"Alignment",
".",
"ALIGN_NORMAL",
",",
"1.0f",
",",
"0f",
",",
"false",
")",
";",
"float",
"[",
"]",
"r",
"=",
"new",
"float",
"[",
"]",
"{",
"0",
",",
"v",
".",
"getHeight",
"(",
")",
"}",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"v",
".",
"getLineCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"float",
"vv",
"=",
"v",
".",
"getLineWidth",
"(",
"i",
")",
";",
"if",
"(",
"vv",
">",
"r",
"[",
"0",
"]",
")",
"{",
"r",
"[",
"0",
"]",
"=",
"vv",
";",
"}",
"}",
"return",
"r",
";",
"}",
"public",
"static",
"void",
"viewSetImage",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"Object",
"image",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"if",
"(",
"image",
"instanceof",
"Drawable",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setImage",
"(",
"(",
"Drawable",
")",
"image",
")",
";",
"}",
"else",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setImage",
"(",
"null",
")",
";",
"}",
"}",
"else",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"if",
"(",
"image",
"instanceof",
"Drawable",
")",
"{",
"(",
"(",
"View",
")",
"view",
")",
".",
"setBackground",
"(",
"(",
"Drawable",
")",
"image",
")",
";",
"}",
"else",
"{",
"(",
"(",
"View",
")",
"view",
")",
".",
"setBackground",
"(",
"null",
")",
";",
"}",
"}",
"}",
"public",
"static",
"void",
"viewSetGravity",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"String",
"gravity",
")",
"{",
"}",
"public",
"static",
"void",
"viewSetContent",
"(",
"Object",
"view",
",",
"long",
"viewObject",
",",
"String",
"content",
",",
"String",
"contentType",
",",
"String",
"basePath",
")",
"{",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setContent",
"(",
"viewObject",
",",
"content",
",",
"contentType",
",",
"basePath",
")",
";",
"}",
"}",
"public",
"static",
"int",
"getViewWidth",
"(",
"Object",
"view",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Rect",
"frame",
"=",
"(",
"Rect",
")",
"(",
"(",
"View",
")",
"view",
")",
".",
"getTag",
"(",
"R",
".",
"id",
".",
"ker_frame",
")",
";",
"if",
"(",
"frame",
"!=",
"null",
")",
"{",
"return",
"frame",
".",
"width",
";",
"}",
"return",
"Math",
".",
"max",
"(",
"(",
"(",
"View",
")",
"view",
")",
".",
"getWidth",
"(",
")",
",",
"(",
"(",
"View",
")",
"view",
")",
".",
"getMeasuredWidth",
"(",
")",
")",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"int",
"getViewHeight",
"(",
"Object",
"view",
")",
"{",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"Rect",
"frame",
"=",
"(",
"Rect",
")",
"(",
"(",
"View",
")",
"view",
")",
".",
"getTag",
"(",
"R",
".",
"id",
".",
"ker_frame",
")",
";",
"if",
"(",
"frame",
"!=",
"null",
")",
"{",
"return",
"frame",
".",
"height",
";",
"}",
"return",
"Math",
".",
"max",
"(",
"(",
"(",
"View",
")",
"view",
")",
".",
"getHeight",
"(",
")",
",",
"(",
"(",
"View",
")",
"view",
")",
".",
"getMeasuredHeight",
"(",
")",
")",
";",
"}",
"return",
"0",
";",
"}",
"public",
"static",
"Object",
"createView",
"(",
"App",
"app",
",",
"String",
"name",
",",
"long",
"viewConfiguration",
")",
"{",
"View",
"view",
"=",
"null",
";",
"if",
"(",
"name",
"!=",
"null",
"&&",
"_viewClasss",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"Class",
"<",
"?",
">",
"isa",
"=",
"_viewClasss",
".",
"get",
"(",
"name",
")",
";",
"try",
"{",
"Constructor",
"<",
"?",
">",
"init",
"=",
"isa",
".",
"getConstructor",
"(",
"Context",
".",
"class",
")",
";",
"view",
"=",
"(",
"View",
")",
"init",
".",
"newInstance",
"(",
"app",
".",
"activity",
"(",
")",
".",
"getApplicationContext",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"Log",
".",
"d",
"(",
"\"",
"ker",
"\"",
",",
"Log",
".",
"getStackTraceString",
"(",
"e",
")",
")",
";",
"}",
"}",
"if",
"(",
"view",
"==",
"null",
")",
"{",
"view",
"=",
"new",
"KerView",
"(",
"app",
".",
"activity",
"(",
")",
".",
"getApplicationContext",
"(",
")",
")",
";",
"}",
"if",
"(",
"view",
"instanceof",
"IKerView",
")",
"{",
"(",
"(",
"IKerView",
")",
"view",
")",
".",
"setViewConfiguration",
"(",
"viewConfiguration",
")",
";",
"}",
"return",
"view",
";",
"}",
"public",
"static",
"void",
"runApp",
"(",
"final",
"App",
"app",
",",
"String",
"URI",
",",
"final",
"Object",
"query",
")",
"{",
"Package",
".",
"getPackage",
"(",
"app",
".",
"activity",
"(",
")",
",",
"URI",
",",
"new",
"Package",
".",
"Callback",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onError",
"(",
"Throwable",
"ex",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onLoad",
"(",
"Package",
"pkg",
")",
"{",
"App",
".",
"open",
"(",
"app",
".",
"activity",
"(",
")",
",",
"pkg",
".",
"basePath",
",",
"pkg",
".",
"appkey",
",",
"query",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onProgress",
"(",
"long",
"bytes",
",",
"long",
"total",
")",
"{",
"}",
"}",
")",
";",
"}",
"private",
"static",
"Map",
"<",
"String",
",",
"Class",
"<",
"?",
">",
">",
"_viewClasss",
"=",
"new",
"TreeMap",
"<",
">",
"(",
")",
";",
"public",
"static",
"void",
"addViewClass",
"(",
"String",
"name",
",",
"Class",
"<",
"?",
">",
"viewClass",
")",
"{",
"_viewClasss",
".",
"put",
"(",
"name",
",",
"viewClass",
")",
";",
"}",
"static",
"{",
"_viewClasss",
".",
"put",
"(",
"\"",
"UILabel",
"\"",
",",
"KerTextView",
".",
"class",
")",
";",
"_viewClasss",
".",
"put",
"(",
"\"",
"UIView",
"\"",
",",
"KerView",
".",
"class",
")",
";",
"_viewClasss",
".",
"put",
"(",
"\"",
"KerButton",
"\"",
",",
"KerButton",
".",
"class",
")",
";",
"_viewClasss",
".",
"put",
"(",
"\"",
"WKWebView",
"\"",
",",
"KerWebView",
".",
"class",
")",
";",
"_viewClasss",
".",
"put",
"(",
"\"",
"UICanvasView",
"\"",
",",
"KerCanvasView",
".",
"class",
")",
";",
"}",
"public",
"static",
"void",
"openlib",
"(",
")",
"{",
"final",
"Handler",
"v",
"=",
"new",
"Handler",
"(",
")",
";",
"v",
".",
"post",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"loop",
"(",
")",
";",
"v",
".",
"postDelayed",
"(",
"this",
",",
"17",
")",
";",
"}",
"}",
")",
";",
"}",
"public",
"static",
"void",
"getPackage",
"(",
"App",
"app",
",",
"final",
"long",
"ptr",
",",
"String",
"URI",
")",
"{",
"retain",
"(",
"ptr",
")",
";",
"Package",
".",
"getPackage",
"(",
"app",
".",
"activity",
"(",
")",
",",
"URI",
",",
"new",
"Package",
".",
"Callback",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onError",
"(",
"Throwable",
"ex",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"TreeMap",
"<",
">",
"(",
")",
";",
"data",
".",
"put",
"(",
"\"",
"error",
"\"",
",",
"ex",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"emit",
"(",
"ptr",
",",
"\"",
"error",
"\"",
",",
"data",
")",
";",
"release",
"(",
"ptr",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onLoad",
"(",
"Package",
"pkg",
")",
"{",
"emit",
"(",
"ptr",
",",
"\"",
"load",
"\"",
",",
"new",
"TreeMap",
"<",
">",
"(",
")",
")",
";",
"release",
"(",
"ptr",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onProgress",
"(",
"long",
"bytes",
",",
"long",
"total",
")",
"{",
"}",
"}",
")",
";",
"}",
"public",
"static",
"KerCanvas",
"createCanvas",
"(",
"int",
"width",
",",
"int",
"height",
")",
"{",
"return",
"new",
"KerCanvas",
"(",
"width",
",",
"height",
")",
";",
"}",
"public",
"static",
"void",
"displayCanvas",
"(",
"KerCanvas",
"canvas",
",",
"Object",
"view",
")",
"{",
"if",
"(",
"view",
"instanceof",
"KerCanvasView",
")",
"{",
"(",
"(",
"KerCanvasView",
")",
"view",
")",
".",
"post",
"(",
"canvas",
".",
"getDrawable",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"view",
"instanceof",
"View",
")",
"{",
"(",
"(",
"View",
")",
"view",
")",
".",
"setBackground",
"(",
"canvas",
".",
"getDrawable",
"(",
")",
")",
";",
"}",
"}",
"public",
"static",
"void",
"gc",
"(",
")",
"{",
"System",
".",
"gc",
"(",
")",
";",
"}",
"public",
"native",
"static",
"void",
"retain",
"(",
"long",
"kerObject",
")",
";",
"public",
"native",
"static",
"void",
"release",
"(",
"long",
"kerObject",
")",
";",
"public",
"native",
"static",
"void",
"setImage",
"(",
"long",
"imageObject",
",",
"Object",
"image",
")",
";",
"public",
"native",
"static",
"void",
"loop",
"(",
")",
";",
"public",
"native",
"static",
"void",
"emit",
"(",
"long",
"ptr",
",",
"String",
"name",
",",
"Object",
"data",
")",
";",
"public",
"native",
"static",
"WebViewConfiguration",
"getWebViewConfiguration",
"(",
"long",
"kerObject",
")",
";",
"public",
"native",
"static",
"String",
"absolutePath",
"(",
"long",
"ptr",
",",
"String",
"path",
")",
";",
"}"
] | Created by zhanghailong on 2018/12/11. | [
"Created",
"by",
"zhanghailong",
"on",
"2018",
"/",
"12",
"/",
"11",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13eaac97efd7198e75223af8bea1e4bd57391507 | PKOfficial/incubator-carbondata | processing/src/main/java/org/apache/carbondata/processing/store/TablePageStatistics.java | [
"Apache-2.0"
] | Java | TablePageStatistics | // Statistics of dimension and measure column in a TablePage | Statistics of dimension and measure column in a TablePage | [
"Statistics",
"of",
"dimension",
"and",
"measure",
"column",
"in",
"a",
"TablePage"
] | public class TablePageStatistics {
// number of dimension after complex column expanded
private int numDimensionsExpanded;
// min of each dimension column
private byte[][] dimensionMinValue;
// max of each dimension column
private byte[][] dimensionMaxValue;
// min of each measure column
private byte[][] measureMinValue;
// max os each measure column
private byte[][] measureMaxValue;
// null bit set for each measure column
private BitSet[] nullBitSet;
// measure stats
// TODO: there are redundant stats
private MeasurePageStatsVO measurePageStatistics;
private TableSpec tableSpec;
TablePageStatistics(TableSpec tableSpec, TablePage tablePage,
EncodedData encodedData, MeasurePageStatsVO measurePageStatistics) {
this.numDimensionsExpanded = tableSpec.getDimensionSpec().getNumExpandedDimensions();
int numMeasures = tableSpec.getMeasureSpec().getNumMeasures();
this.dimensionMinValue = new byte[numDimensionsExpanded][];
this.dimensionMaxValue = new byte[numDimensionsExpanded][];
this.measureMinValue = new byte[numMeasures][];
this.measureMaxValue = new byte[numMeasures][];
this.nullBitSet = new BitSet[numMeasures];
this.tableSpec = tableSpec;
this.measurePageStatistics = measurePageStatistics;
updateMinMax(tablePage, encodedData);
updateNullBitSet(tablePage);
}
private void updateMinMax(TablePage tablePage, EncodedData encodedData) {
IndexStorage[] keyStorageArray = encodedData.indexStorages;
byte[][] measureArray = encodedData.measures;
for (int i = 0; i < numDimensionsExpanded; i++) {
switch (tableSpec.getDimensionSpec().getType(i)) {
case GLOBAL_DICTIONARY:
case DIRECT_DICTIONARY:
case COLUMN_GROUP:
case COMPLEX:
dimensionMinValue[i] = keyStorageArray[i].getMin();
dimensionMaxValue[i] = keyStorageArray[i].getMax();
break;
case PLAIN_VALUE:
dimensionMinValue[i] = updateMinMaxForNoDictionary(keyStorageArray[i].getMin());
dimensionMaxValue[i] = updateMinMaxForNoDictionary(keyStorageArray[i].getMax());
break;
}
}
for (int i = 0; i < measureArray.length; i++) {
ColumnPageStatsVO stats = tablePage.getMeasurePage()[i].getStatistics();
measureMaxValue[i] = stats.minBytes();
measureMinValue[i] = stats.maxBytes();
}
}
private void updateNullBitSet(TablePage tablePage) {
nullBitSet = new BitSet[tablePage.getMeasurePage().length];
ColumnPage[] measurePages = tablePage.getMeasurePage();
for (int i = 0; i < nullBitSet.length; i++) {
nullBitSet[i] = measurePages[i].getNullBitSet();
}
}
/**
* Below method will be used to update the min or max value
* by removing the length from it
*
* @return min max value without length
*/
private byte[] updateMinMaxForNoDictionary(byte[] valueWithLength) {
ByteBuffer buffer = ByteBuffer.wrap(valueWithLength);
byte[] actualValue = new byte[buffer.getShort()];
buffer.get(actualValue);
return actualValue;
}
public byte[][] getDimensionMinValue() {
return dimensionMinValue;
}
public byte[][] getDimensionMaxValue() {
return dimensionMaxValue;
}
public byte[][] getMeasureMinValue() {
return measureMinValue;
}
public byte[][] getMeasureMaxValue() {
return measureMaxValue;
}
public BitSet[] getNullBitSet() {
return nullBitSet;
}
public MeasurePageStatsVO getMeasurePageStatistics() {
return measurePageStatistics;
}
} | [
"public",
"class",
"TablePageStatistics",
"{",
"private",
"int",
"numDimensionsExpanded",
";",
"private",
"byte",
"[",
"]",
"[",
"]",
"dimensionMinValue",
";",
"private",
"byte",
"[",
"]",
"[",
"]",
"dimensionMaxValue",
";",
"private",
"byte",
"[",
"]",
"[",
"]",
"measureMinValue",
";",
"private",
"byte",
"[",
"]",
"[",
"]",
"measureMaxValue",
";",
"private",
"BitSet",
"[",
"]",
"nullBitSet",
";",
"private",
"MeasurePageStatsVO",
"measurePageStatistics",
";",
"private",
"TableSpec",
"tableSpec",
";",
"TablePageStatistics",
"(",
"TableSpec",
"tableSpec",
",",
"TablePage",
"tablePage",
",",
"EncodedData",
"encodedData",
",",
"MeasurePageStatsVO",
"measurePageStatistics",
")",
"{",
"this",
".",
"numDimensionsExpanded",
"=",
"tableSpec",
".",
"getDimensionSpec",
"(",
")",
".",
"getNumExpandedDimensions",
"(",
")",
";",
"int",
"numMeasures",
"=",
"tableSpec",
".",
"getMeasureSpec",
"(",
")",
".",
"getNumMeasures",
"(",
")",
";",
"this",
".",
"dimensionMinValue",
"=",
"new",
"byte",
"[",
"numDimensionsExpanded",
"]",
"[",
"]",
";",
"this",
".",
"dimensionMaxValue",
"=",
"new",
"byte",
"[",
"numDimensionsExpanded",
"]",
"[",
"]",
";",
"this",
".",
"measureMinValue",
"=",
"new",
"byte",
"[",
"numMeasures",
"]",
"[",
"]",
";",
"this",
".",
"measureMaxValue",
"=",
"new",
"byte",
"[",
"numMeasures",
"]",
"[",
"]",
";",
"this",
".",
"nullBitSet",
"=",
"new",
"BitSet",
"[",
"numMeasures",
"]",
";",
"this",
".",
"tableSpec",
"=",
"tableSpec",
";",
"this",
".",
"measurePageStatistics",
"=",
"measurePageStatistics",
";",
"updateMinMax",
"(",
"tablePage",
",",
"encodedData",
")",
";",
"updateNullBitSet",
"(",
"tablePage",
")",
";",
"}",
"private",
"void",
"updateMinMax",
"(",
"TablePage",
"tablePage",
",",
"EncodedData",
"encodedData",
")",
"{",
"IndexStorage",
"[",
"]",
"keyStorageArray",
"=",
"encodedData",
".",
"indexStorages",
";",
"byte",
"[",
"]",
"[",
"]",
"measureArray",
"=",
"encodedData",
".",
"measures",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numDimensionsExpanded",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"tableSpec",
".",
"getDimensionSpec",
"(",
")",
".",
"getType",
"(",
"i",
")",
")",
"{",
"case",
"GLOBAL_DICTIONARY",
":",
"case",
"DIRECT_DICTIONARY",
":",
"case",
"COLUMN_GROUP",
":",
"case",
"COMPLEX",
":",
"dimensionMinValue",
"[",
"i",
"]",
"=",
"keyStorageArray",
"[",
"i",
"]",
".",
"getMin",
"(",
")",
";",
"dimensionMaxValue",
"[",
"i",
"]",
"=",
"keyStorageArray",
"[",
"i",
"]",
".",
"getMax",
"(",
")",
";",
"break",
";",
"case",
"PLAIN_VALUE",
":",
"dimensionMinValue",
"[",
"i",
"]",
"=",
"updateMinMaxForNoDictionary",
"(",
"keyStorageArray",
"[",
"i",
"]",
".",
"getMin",
"(",
")",
")",
";",
"dimensionMaxValue",
"[",
"i",
"]",
"=",
"updateMinMaxForNoDictionary",
"(",
"keyStorageArray",
"[",
"i",
"]",
".",
"getMax",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"measureArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"ColumnPageStatsVO",
"stats",
"=",
"tablePage",
".",
"getMeasurePage",
"(",
")",
"[",
"i",
"]",
".",
"getStatistics",
"(",
")",
";",
"measureMaxValue",
"[",
"i",
"]",
"=",
"stats",
".",
"minBytes",
"(",
")",
";",
"measureMinValue",
"[",
"i",
"]",
"=",
"stats",
".",
"maxBytes",
"(",
")",
";",
"}",
"}",
"private",
"void",
"updateNullBitSet",
"(",
"TablePage",
"tablePage",
")",
"{",
"nullBitSet",
"=",
"new",
"BitSet",
"[",
"tablePage",
".",
"getMeasurePage",
"(",
")",
".",
"length",
"]",
";",
"ColumnPage",
"[",
"]",
"measurePages",
"=",
"tablePage",
".",
"getMeasurePage",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nullBitSet",
".",
"length",
";",
"i",
"++",
")",
"{",
"nullBitSet",
"[",
"i",
"]",
"=",
"measurePages",
"[",
"i",
"]",
".",
"getNullBitSet",
"(",
")",
";",
"}",
"}",
"/**\n * Below method will be used to update the min or max value\n * by removing the length from it\n *\n * @return min max value without length\n */",
"private",
"byte",
"[",
"]",
"updateMinMaxForNoDictionary",
"(",
"byte",
"[",
"]",
"valueWithLength",
")",
"{",
"ByteBuffer",
"buffer",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"valueWithLength",
")",
";",
"byte",
"[",
"]",
"actualValue",
"=",
"new",
"byte",
"[",
"buffer",
".",
"getShort",
"(",
")",
"]",
";",
"buffer",
".",
"get",
"(",
"actualValue",
")",
";",
"return",
"actualValue",
";",
"}",
"public",
"byte",
"[",
"]",
"[",
"]",
"getDimensionMinValue",
"(",
")",
"{",
"return",
"dimensionMinValue",
";",
"}",
"public",
"byte",
"[",
"]",
"[",
"]",
"getDimensionMaxValue",
"(",
")",
"{",
"return",
"dimensionMaxValue",
";",
"}",
"public",
"byte",
"[",
"]",
"[",
"]",
"getMeasureMinValue",
"(",
")",
"{",
"return",
"measureMinValue",
";",
"}",
"public",
"byte",
"[",
"]",
"[",
"]",
"getMeasureMaxValue",
"(",
")",
"{",
"return",
"measureMaxValue",
";",
"}",
"public",
"BitSet",
"[",
"]",
"getNullBitSet",
"(",
")",
"{",
"return",
"nullBitSet",
";",
"}",
"public",
"MeasurePageStatsVO",
"getMeasurePageStatistics",
"(",
")",
"{",
"return",
"measurePageStatistics",
";",
"}",
"}"
] | Statistics of dimension and measure column in a TablePage | [
"Statistics",
"of",
"dimension",
"and",
"measure",
"column",
"in",
"a",
"TablePage"
] | [
"// number of dimension after complex column expanded",
"// min of each dimension column",
"// max of each dimension column",
"// min of each measure column",
"// max os each measure column",
"// null bit set for each measure column",
"// measure stats",
"// TODO: there are redundant stats"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13f28a3346b778fe87e863f4fcdf69e1f6f3a97d | mehmetpekdemir/Spring-Boot-Youtube | backend/src/main/java/com/example/backend/dto/UserUpdateDTO.java | [
"Apache-2.0"
] | Java | UserUpdateDTO | /**
*
* @author MEHMET PEKDEMIR
* @since 1.0
*/ | @author MEHMET PEKDEMIR
@since 1.0 | [
"@author",
"MEHMET",
"PEKDEMIR",
"@since",
"1",
".",
"0"
] | @Data
public class UserUpdateDTO {
@NotNull(message = "{backend.constraints.firstname.NotNull.message}")
@Size(min = 2, max = 32, message = "{backend.constraints.firstname.Size.message}")
private String firstName;
@NotNull(message = "{backend.constraints.lastname.NotNull.message}")
@Size(min = 3, max = 32, message = "{backend.constraints.lastname.Size.message}")
private String lastName;
} | [
"@",
"Data",
"public",
"class",
"UserUpdateDTO",
"{",
"@",
"NotNull",
"(",
"message",
"=",
"\"",
"{backend.constraints.firstname.NotNull.message}",
"\"",
")",
"@",
"Size",
"(",
"min",
"=",
"2",
",",
"max",
"=",
"32",
",",
"message",
"=",
"\"",
"{backend.constraints.firstname.Size.message}",
"\"",
")",
"private",
"String",
"firstName",
";",
"@",
"NotNull",
"(",
"message",
"=",
"\"",
"{backend.constraints.lastname.NotNull.message}",
"\"",
")",
"@",
"Size",
"(",
"min",
"=",
"3",
",",
"max",
"=",
"32",
",",
"message",
"=",
"\"",
"{backend.constraints.lastname.Size.message}",
"\"",
")",
"private",
"String",
"lastName",
";",
"}"
] | @author MEHMET PEKDEMIR
@since 1.0 | [
"@author",
"MEHMET",
"PEKDEMIR",
"@since",
"1",
".",
"0"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
13f592a4ccf6541c6a31fdc05d03e9966e9e8c52 | jfrommann/picturesafe-search | src/main/java/de/picturesafe/search/parameter/aggregation/AbstractAggregation.java | [
"Apache-2.0"
] | Java | AbstractAggregation | /**
* Abstract implementation of an aggregation definition
*
* @param <A> Type of the aggregation
*/ | Abstract implementation of an aggregation definition
@param Type of the aggregation | [
"Abstract",
"implementation",
"of",
"an",
"aggregation",
"definition",
"@param",
"Type",
"of",
"the",
"aggregation"
] | public abstract class AbstractAggregation<A extends AbstractAggregation<A>> implements SearchAggregation {
protected String field;
protected String name;
/**
* Sets the name of the aggregation.
*
* @param name Name of the aggregation
* @return The aggregation
*/
public A name(String name) {
this.name = name;
return self();
}
protected abstract A self();
@Override
public String getField() {
return field;
}
@Override
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final AbstractAggregation<?> that = (AbstractAggregation<?>) o;
return new EqualsBuilder()
.append(field, that.field)
.append(name, that.name)
.isEquals();
}
@Override
public int hashCode() {
return field.hashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this, new CustomJsonToStringStyle()) //--
.append("field", field) //--
.append("name", name) //--
.toString();
}
} | [
"public",
"abstract",
"class",
"AbstractAggregation",
"<",
"A",
"extends",
"AbstractAggregation",
"<",
"A",
">",
">",
"implements",
"SearchAggregation",
"{",
"protected",
"String",
"field",
";",
"protected",
"String",
"name",
";",
"/**\n * Sets the name of the aggregation.\n *\n * @param name Name of the aggregation\n * @return The aggregation\n */",
"public",
"A",
"name",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"return",
"self",
"(",
")",
";",
"}",
"protected",
"abstract",
"A",
"self",
"(",
")",
";",
"@",
"Override",
"public",
"String",
"getField",
"(",
")",
"{",
"return",
"field",
";",
"}",
"@",
"Override",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"name",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"AbstractAggregation",
"<",
"?",
">",
"that",
"=",
"(",
"AbstractAggregation",
"<",
"?",
">",
")",
"o",
";",
"return",
"new",
"EqualsBuilder",
"(",
")",
".",
"append",
"(",
"field",
",",
"that",
".",
"field",
")",
".",
"append",
"(",
"name",
",",
"that",
".",
"name",
")",
".",
"isEquals",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"field",
".",
"hashCode",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"new",
"ToStringBuilder",
"(",
"this",
",",
"new",
"CustomJsonToStringStyle",
"(",
")",
")",
".",
"append",
"(",
"\"",
"field",
"\"",
",",
"field",
")",
".",
"append",
"(",
"\"",
"name",
"\"",
",",
"name",
")",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Abstract implementation of an aggregation definition
@param <A> Type of the aggregation | [
"Abstract",
"implementation",
"of",
"an",
"aggregation",
"definition",
"@param",
"<A",
">",
"Type",
"of",
"the",
"aggregation"
] | [
"//--",
"//--",
"//--"
] | [
{
"param": "SearchAggregation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "SearchAggregation",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13f98cc8c47de68a76edf6b6cb6a5df9028df041 | sword-huang/custom-maps | app/src/main/java/com/custommapsapp/android/create/SelectPdfPageActivity.java | [
"Apache-2.0",
"BSD-3-Clause"
] | Java | SelectPdfPageActivity | // PDF rendering requires API 21 (Android 5.0, Lollipop), don't use this Activity in older devices | PDF rendering requires API 21 (Android 5.0, Lollipop), don't use this Activity in older devices | [
"PDF",
"rendering",
"requires",
"API",
"21",
"(",
"Android",
"5",
".",
"0",
"Lollipop",
")",
"don",
"'",
"t",
"use",
"this",
"Activity",
"in",
"older",
"devices"
] | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class SelectPdfPageActivity extends AppCompatActivity {
private static final String EXTRA_PREFIX = "com.custommapsapp.android";
private static final String CURRENT_PAGE = EXTRA_PREFIX + ".CurrentPage";
public static final String PDF_FILENAME = EXTRA_PREFIX + ".PdfFile";
private ImageView pageDisplay;
private TextView pageNumber;
private Linguist linguist;
private String pdfFilename;
private int currentPageNum = 0;
private int lastPage = 9;
private PdfRendererFragment pdfRendererFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// PDF rendering is only supported on SDK 21 (Lollipop) and later
if (Build.VERSION.SDK_INT < 21) {
// No PDF support available, return immediately from activity
finish();
return;
}
setContentView(R.layout.selectpdfpage);
linguist = ((CustomMapsApp) getApplication()).getLinguist();
linguist.translateView(findViewById(R.id.root_view));
ImageHelper.initializePreferredBitmapConfig(this);
prepareUI();
setSupportActionBar(findViewById(R.id.toolbar));
if (savedInstanceState != null) {
getSupportActionBar().setTitle(linguist.getString(R.string.select_map_page));
pdfRendererFragment = (PdfRendererFragment) getSupportFragmentManager()
.findFragmentByTag(CustomMaps.PDF_RENDERER_FRAGMENT_TAG);
pdfFilename = savedInstanceState.getString(PDF_FILENAME);
currentPageNum = savedInstanceState.getInt(CURRENT_PAGE);
} else {
getSupportActionBar().setTitle(linguist.getString(R.string.preparing_pdf_file));
displayScrim(true);
pdfFilename = getIntent().getStringExtra(PDF_FILENAME);
currentPageNum = 0;
}
if (pdfRendererFragment == null) {
pdfRendererFragment = new PdfRendererFragment();
pdfRendererFragment.setRetainInstance(true);
getSupportFragmentManager().beginTransaction()
.add(pdfRendererFragment, CustomMaps.PDF_RENDERER_FRAGMENT_TAG)
.commit();
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_PAGE, currentPageNum);
outState.putString(PDF_FILENAME, pdfFilename);
}
@Override
protected void onResume() {
super.onResume();
Uri pdfUri = Uri.fromFile(new File(pdfFilename));
pdfRendererFragment.setPdfFile(pdfUri, this::pdfRendererReady);
}
private void pdfRendererReady() {
lastPage = pdfRendererFragment.getPageCount() - 1;
if (lastPage < 0) {
Log.e(LOG_TAG, "SelectPdfPageActivity - Failed to open PDF: " + pdfFilename);
finish();
return;
} else {
Log.i(LOG_TAG, "SelectPdfPageActivity - PDF opened, page count: " + (lastPage + 1));
}
// Document has been opened, update activity title and render the first page
getSupportActionBar().setTitle(linguist.getString(R.string.select_map_page));
findViewById(R.id.blank).setVisibility(View.INVISIBLE);
displayScrim(false);
updateCurrentPage();
}
private void updateCurrentPage() {
pageNumber.setText(String.format(Locale.US, "%d/%d", currentPageNum+1, lastPage+1));
pdfRendererFragment.requestPreviewPage(currentPageNum, previewPageReceiver);
}
/** Moves to the previous page of the PDF document, if not already on the first page. */
private void prevPage(View button) {
if (currentPageNum <= 0) {
currentPageNum = 0;
return;
}
currentPageNum--;
updateCurrentPage();
}
/** Moves to the next page of the PDF document, if not already on the last page */
private void nextPage(View button) {
if (currentPageNum >= lastPage) {
currentPageNum = lastPage;
return;
}
currentPageNum++;
updateCurrentPage();
}
/** Rotate page image 90 degrees in clockwise direction. */
private void rotateCw(View button) {
pdfRendererFragment.rotateImage(PdfRendererFragment.Rotate.CW);
updateCurrentPage();
}
/** Rotate page image 90 degrees in counter-clockwise direction. */
private void rotateCcw(View button) {
pdfRendererFragment.rotateImage(PdfRendererFragment.Rotate.CCW);
updateCurrentPage();
}
private String generatePdfImageName() {
File pdfFile = new File(pdfFilename);
String filename = pdfFile.getName();
// Replace spaces in the PDF filename with underscores
filename = filename.replace(' ', '_');
// Drop suffix, and replace it with ".jpg"
if (filename.lastIndexOf('.') > 0) {
filename = filename.substring(0, filename.lastIndexOf('.'));
}
return filename + ".jpg";
}
/**
* Selects current PDF page to be used for a map. Executed when "Select"
* menu item is clicked.
*/
private boolean selectCurrentPage(MenuItem item) {
// Disable the only menu item on screen
Toolbar bottomBar = findViewById(R.id.bottombar);
bottomBar.getMenu().getItem(0).setEnabled(false);
// Start rendering full resolution version of the page
String imageName = generatePdfImageName();
pdfRendererFragment.requestFinalPage(currentPageNum, imageName, finalPageReceiver);
return true;
}
/** Returns the high quality rendered selected page file to invoking activity. */
private void returnSelectedPage() {
String imageName = generatePdfImageName();
File imageFile = pdfRendererFragment.getFinalPageFile(imageName);
if (imageFile == null || !imageFile.exists()) {
// Do not exit, since the selected page image file does not exist
return;
}
Log.i(LOG_TAG, "Returning selected page image: " + imageFile);
getSupportFragmentManager().beginTransaction().remove(pdfRendererFragment).commit();
Intent result = getIntent().setData(Uri.fromFile(imageFile));
setResult(RESULT_OK, result);
finish();
}
@Override
public void onBackPressed() {
pdfRendererFragment.setPdfFile(null);
getSupportFragmentManager().beginTransaction().remove(pdfRendererFragment).commit();
setResult(RESULT_CANCELED);
super.onBackPressed();
}
private void displayScrim(boolean makeVisible) {
int mode = makeVisible ? View.VISIBLE : View.GONE;
findViewById(R.id.scrim).setVisibility(mode);
}
private void prepareUI() {
pageDisplay = findViewById(R.id.pageImage);
pageNumber = findViewById(R.id.pageNumber);
findViewById(R.id.prevPage).setOnClickListener(this::prevPage);
findViewById(R.id.nextPage).setOnClickListener(this::nextPage);
findViewById(R.id.rotateCw).setOnClickListener(this::rotateCw);
findViewById(R.id.rotateCcw).setOnClickListener(this::rotateCcw);
// Add "Select" action to bottom bar
Toolbar bottomBar = findViewById(R.id.bottombar);
bottomBar.getMenu()
.add(1, 1, 1, linguist.getString(R.string.select_action))
.setOnMenuItemClickListener(this::selectCurrentPage)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
private PdfRendererFragment.PageReceiver previewPageReceiver = new PdfRendererFragment.PageReceiver() {
@Override
public void pageRendering(int pageNum) {
displayScrim(true);
}
@Override
public void pageRendered(int pageNum, Bitmap pageImage) {
displayScrim(false);
if (pageNum == currentPageNum) {
int pageRotation = pdfRendererFragment.getCurrentPageRotation();
if (pageRotation == 0) {
pageDisplay.setScaleType(ImageView.ScaleType.FIT_CENTER);
} else {
Matrix m = computePageDisplayMatrix(pageDisplay, pageImage, pageRotation);
pageDisplay.setScaleType(ImageView.ScaleType.MATRIX);
pageDisplay.setImageMatrix(m);
}
pageDisplay.setImageBitmap(pageImage);
pageDisplay.invalidate();
}
}
private Matrix computePageDisplayMatrix(ImageView display, Bitmap image, int rotation) {
Matrix m = new Matrix();
// Find out image width and height after rotation
boolean isImageSideways = (rotation % 180) != 0;
int imageW = isImageSideways ? image.getHeight() : image.getWidth();
int imageH = isImageSideways ? image.getWidth() : image.getHeight();
// Scale image to fully fit in display
float xScale = display.getWidth() / (float) imageW;
float yScale = display.getHeight() / (float) imageH;
float scale = Math.min(xScale, yScale);
m.postScale(scale, scale);
// Center image in display area
float dx = (display.getWidth() - scale * image.getWidth()) / 2f;
float dy = (display.getHeight() - scale * image.getHeight()) / 2f;
m.postTranslate(dx, dy);
// Rotate image to requested orientation
m.postRotate(rotation, display.getWidth() / 2f, display.getHeight() / 2f);
return m;
}
};
private PdfRendererFragment.PageReceiver finalPageReceiver = new PdfRendererFragment.PageReceiver() {
@Override
public void pageRendering(int pageNum) {
displayScrim(true);
}
@Override
public void pageRendered(int pageNum, Bitmap pageImage) {
displayScrim(false);
returnSelectedPage();
}
};
} | [
"@",
"TargetApi",
"(",
"Build",
".",
"VERSION_CODES",
".",
"LOLLIPOP",
")",
"public",
"class",
"SelectPdfPageActivity",
"extends",
"AppCompatActivity",
"{",
"private",
"static",
"final",
"String",
"EXTRA_PREFIX",
"=",
"\"",
"com.custommapsapp.android",
"\"",
";",
"private",
"static",
"final",
"String",
"CURRENT_PAGE",
"=",
"EXTRA_PREFIX",
"+",
"\"",
".CurrentPage",
"\"",
";",
"public",
"static",
"final",
"String",
"PDF_FILENAME",
"=",
"EXTRA_PREFIX",
"+",
"\"",
".PdfFile",
"\"",
";",
"private",
"ImageView",
"pageDisplay",
";",
"private",
"TextView",
"pageNumber",
";",
"private",
"Linguist",
"linguist",
";",
"private",
"String",
"pdfFilename",
";",
"private",
"int",
"currentPageNum",
"=",
"0",
";",
"private",
"int",
"lastPage",
"=",
"9",
";",
"private",
"PdfRendererFragment",
"pdfRendererFragment",
";",
"@",
"Override",
"protected",
"void",
"onCreate",
"(",
"Bundle",
"savedInstanceState",
")",
"{",
"super",
".",
"onCreate",
"(",
"savedInstanceState",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
"<",
"21",
")",
"{",
"finish",
"(",
")",
";",
"return",
";",
"}",
"setContentView",
"(",
"R",
".",
"layout",
".",
"selectpdfpage",
")",
";",
"linguist",
"=",
"(",
"(",
"CustomMapsApp",
")",
"getApplication",
"(",
")",
")",
".",
"getLinguist",
"(",
")",
";",
"linguist",
".",
"translateView",
"(",
"findViewById",
"(",
"R",
".",
"id",
".",
"root_view",
")",
")",
";",
"ImageHelper",
".",
"initializePreferredBitmapConfig",
"(",
"this",
")",
";",
"prepareUI",
"(",
")",
";",
"setSupportActionBar",
"(",
"findViewById",
"(",
"R",
".",
"id",
".",
"toolbar",
")",
")",
";",
"if",
"(",
"savedInstanceState",
"!=",
"null",
")",
"{",
"getSupportActionBar",
"(",
")",
".",
"setTitle",
"(",
"linguist",
".",
"getString",
"(",
"R",
".",
"string",
".",
"select_map_page",
")",
")",
";",
"pdfRendererFragment",
"=",
"(",
"PdfRendererFragment",
")",
"getSupportFragmentManager",
"(",
")",
".",
"findFragmentByTag",
"(",
"CustomMaps",
".",
"PDF_RENDERER_FRAGMENT_TAG",
")",
";",
"pdfFilename",
"=",
"savedInstanceState",
".",
"getString",
"(",
"PDF_FILENAME",
")",
";",
"currentPageNum",
"=",
"savedInstanceState",
".",
"getInt",
"(",
"CURRENT_PAGE",
")",
";",
"}",
"else",
"{",
"getSupportActionBar",
"(",
")",
".",
"setTitle",
"(",
"linguist",
".",
"getString",
"(",
"R",
".",
"string",
".",
"preparing_pdf_file",
")",
")",
";",
"displayScrim",
"(",
"true",
")",
";",
"pdfFilename",
"=",
"getIntent",
"(",
")",
".",
"getStringExtra",
"(",
"PDF_FILENAME",
")",
";",
"currentPageNum",
"=",
"0",
";",
"}",
"if",
"(",
"pdfRendererFragment",
"==",
"null",
")",
"{",
"pdfRendererFragment",
"=",
"new",
"PdfRendererFragment",
"(",
")",
";",
"pdfRendererFragment",
".",
"setRetainInstance",
"(",
"true",
")",
";",
"getSupportFragmentManager",
"(",
")",
".",
"beginTransaction",
"(",
")",
".",
"add",
"(",
"pdfRendererFragment",
",",
"CustomMaps",
".",
"PDF_RENDERER_FRAGMENT_TAG",
")",
".",
"commit",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onSaveInstanceState",
"(",
"@",
"NonNull",
"Bundle",
"outState",
")",
"{",
"super",
".",
"onSaveInstanceState",
"(",
"outState",
")",
";",
"outState",
".",
"putInt",
"(",
"CURRENT_PAGE",
",",
"currentPageNum",
")",
";",
"outState",
".",
"putString",
"(",
"PDF_FILENAME",
",",
"pdfFilename",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onResume",
"(",
")",
"{",
"super",
".",
"onResume",
"(",
")",
";",
"Uri",
"pdfUri",
"=",
"Uri",
".",
"fromFile",
"(",
"new",
"File",
"(",
"pdfFilename",
")",
")",
";",
"pdfRendererFragment",
".",
"setPdfFile",
"(",
"pdfUri",
",",
"this",
"::",
"pdfRendererReady",
")",
";",
"}",
"private",
"void",
"pdfRendererReady",
"(",
")",
"{",
"lastPage",
"=",
"pdfRendererFragment",
".",
"getPageCount",
"(",
")",
"-",
"1",
";",
"if",
"(",
"lastPage",
"<",
"0",
")",
"{",
"Log",
".",
"e",
"(",
"LOG_TAG",
",",
"\"",
"SelectPdfPageActivity - Failed to open PDF: ",
"\"",
"+",
"pdfFilename",
")",
";",
"finish",
"(",
")",
";",
"return",
";",
"}",
"else",
"{",
"Log",
".",
"i",
"(",
"LOG_TAG",
",",
"\"",
"SelectPdfPageActivity - PDF opened, page count: ",
"\"",
"+",
"(",
"lastPage",
"+",
"1",
")",
")",
";",
"}",
"getSupportActionBar",
"(",
")",
".",
"setTitle",
"(",
"linguist",
".",
"getString",
"(",
"R",
".",
"string",
".",
"select_map_page",
")",
")",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"blank",
")",
".",
"setVisibility",
"(",
"View",
".",
"INVISIBLE",
")",
";",
"displayScrim",
"(",
"false",
")",
";",
"updateCurrentPage",
"(",
")",
";",
"}",
"private",
"void",
"updateCurrentPage",
"(",
")",
"{",
"pageNumber",
".",
"setText",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"",
"%d/%d",
"\"",
",",
"currentPageNum",
"+",
"1",
",",
"lastPage",
"+",
"1",
")",
")",
";",
"pdfRendererFragment",
".",
"requestPreviewPage",
"(",
"currentPageNum",
",",
"previewPageReceiver",
")",
";",
"}",
"/** Moves to the previous page of the PDF document, if not already on the first page. */",
"private",
"void",
"prevPage",
"(",
"View",
"button",
")",
"{",
"if",
"(",
"currentPageNum",
"<=",
"0",
")",
"{",
"currentPageNum",
"=",
"0",
";",
"return",
";",
"}",
"currentPageNum",
"--",
";",
"updateCurrentPage",
"(",
")",
";",
"}",
"/** Moves to the next page of the PDF document, if not already on the last page */",
"private",
"void",
"nextPage",
"(",
"View",
"button",
")",
"{",
"if",
"(",
"currentPageNum",
">=",
"lastPage",
")",
"{",
"currentPageNum",
"=",
"lastPage",
";",
"return",
";",
"}",
"currentPageNum",
"++",
";",
"updateCurrentPage",
"(",
")",
";",
"}",
"/** Rotate page image 90 degrees in clockwise direction. */",
"private",
"void",
"rotateCw",
"(",
"View",
"button",
")",
"{",
"pdfRendererFragment",
".",
"rotateImage",
"(",
"PdfRendererFragment",
".",
"Rotate",
".",
"CW",
")",
";",
"updateCurrentPage",
"(",
")",
";",
"}",
"/** Rotate page image 90 degrees in counter-clockwise direction. */",
"private",
"void",
"rotateCcw",
"(",
"View",
"button",
")",
"{",
"pdfRendererFragment",
".",
"rotateImage",
"(",
"PdfRendererFragment",
".",
"Rotate",
".",
"CCW",
")",
";",
"updateCurrentPage",
"(",
")",
";",
"}",
"private",
"String",
"generatePdfImageName",
"(",
")",
"{",
"File",
"pdfFile",
"=",
"new",
"File",
"(",
"pdfFilename",
")",
";",
"String",
"filename",
"=",
"pdfFile",
".",
"getName",
"(",
")",
";",
"filename",
"=",
"filename",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
";",
"if",
"(",
"filename",
".",
"lastIndexOf",
"(",
"'.'",
")",
">",
"0",
")",
"{",
"filename",
"=",
"filename",
".",
"substring",
"(",
"0",
",",
"filename",
".",
"lastIndexOf",
"(",
"'.'",
")",
")",
";",
"}",
"return",
"filename",
"+",
"\"",
".jpg",
"\"",
";",
"}",
"/**\n * Selects current PDF page to be used for a map. Executed when \"Select\"\n * menu item is clicked.\n */",
"private",
"boolean",
"selectCurrentPage",
"(",
"MenuItem",
"item",
")",
"{",
"Toolbar",
"bottomBar",
"=",
"findViewById",
"(",
"R",
".",
"id",
".",
"bottombar",
")",
";",
"bottomBar",
".",
"getMenu",
"(",
")",
".",
"getItem",
"(",
"0",
")",
".",
"setEnabled",
"(",
"false",
")",
";",
"String",
"imageName",
"=",
"generatePdfImageName",
"(",
")",
";",
"pdfRendererFragment",
".",
"requestFinalPage",
"(",
"currentPageNum",
",",
"imageName",
",",
"finalPageReceiver",
")",
";",
"return",
"true",
";",
"}",
"/** Returns the high quality rendered selected page file to invoking activity. */",
"private",
"void",
"returnSelectedPage",
"(",
")",
"{",
"String",
"imageName",
"=",
"generatePdfImageName",
"(",
")",
";",
"File",
"imageFile",
"=",
"pdfRendererFragment",
".",
"getFinalPageFile",
"(",
"imageName",
")",
";",
"if",
"(",
"imageFile",
"==",
"null",
"||",
"!",
"imageFile",
".",
"exists",
"(",
")",
")",
"{",
"return",
";",
"}",
"Log",
".",
"i",
"(",
"LOG_TAG",
",",
"\"",
"Returning selected page image: ",
"\"",
"+",
"imageFile",
")",
";",
"getSupportFragmentManager",
"(",
")",
".",
"beginTransaction",
"(",
")",
".",
"remove",
"(",
"pdfRendererFragment",
")",
".",
"commit",
"(",
")",
";",
"Intent",
"result",
"=",
"getIntent",
"(",
")",
".",
"setData",
"(",
"Uri",
".",
"fromFile",
"(",
"imageFile",
")",
")",
";",
"setResult",
"(",
"RESULT_OK",
",",
"result",
")",
";",
"finish",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onBackPressed",
"(",
")",
"{",
"pdfRendererFragment",
".",
"setPdfFile",
"(",
"null",
")",
";",
"getSupportFragmentManager",
"(",
")",
".",
"beginTransaction",
"(",
")",
".",
"remove",
"(",
"pdfRendererFragment",
")",
".",
"commit",
"(",
")",
";",
"setResult",
"(",
"RESULT_CANCELED",
")",
";",
"super",
".",
"onBackPressed",
"(",
")",
";",
"}",
"private",
"void",
"displayScrim",
"(",
"boolean",
"makeVisible",
")",
"{",
"int",
"mode",
"=",
"makeVisible",
"?",
"View",
".",
"VISIBLE",
":",
"View",
".",
"GONE",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"scrim",
")",
".",
"setVisibility",
"(",
"mode",
")",
";",
"}",
"private",
"void",
"prepareUI",
"(",
")",
"{",
"pageDisplay",
"=",
"findViewById",
"(",
"R",
".",
"id",
".",
"pageImage",
")",
";",
"pageNumber",
"=",
"findViewById",
"(",
"R",
".",
"id",
".",
"pageNumber",
")",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"prevPage",
")",
".",
"setOnClickListener",
"(",
"this",
"::",
"prevPage",
")",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"nextPage",
")",
".",
"setOnClickListener",
"(",
"this",
"::",
"nextPage",
")",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"rotateCw",
")",
".",
"setOnClickListener",
"(",
"this",
"::",
"rotateCw",
")",
";",
"findViewById",
"(",
"R",
".",
"id",
".",
"rotateCcw",
")",
".",
"setOnClickListener",
"(",
"this",
"::",
"rotateCcw",
")",
";",
"Toolbar",
"bottomBar",
"=",
"findViewById",
"(",
"R",
".",
"id",
".",
"bottombar",
")",
";",
"bottomBar",
".",
"getMenu",
"(",
")",
".",
"add",
"(",
"1",
",",
"1",
",",
"1",
",",
"linguist",
".",
"getString",
"(",
"R",
".",
"string",
".",
"select_action",
")",
")",
".",
"setOnMenuItemClickListener",
"(",
"this",
"::",
"selectCurrentPage",
")",
".",
"setShowAsAction",
"(",
"MenuItem",
".",
"SHOW_AS_ACTION_ALWAYS",
")",
";",
"}",
"private",
"PdfRendererFragment",
".",
"PageReceiver",
"previewPageReceiver",
"=",
"new",
"PdfRendererFragment",
".",
"PageReceiver",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"pageRendering",
"(",
"int",
"pageNum",
")",
"{",
"displayScrim",
"(",
"true",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"pageRendered",
"(",
"int",
"pageNum",
",",
"Bitmap",
"pageImage",
")",
"{",
"displayScrim",
"(",
"false",
")",
";",
"if",
"(",
"pageNum",
"==",
"currentPageNum",
")",
"{",
"int",
"pageRotation",
"=",
"pdfRendererFragment",
".",
"getCurrentPageRotation",
"(",
")",
";",
"if",
"(",
"pageRotation",
"==",
"0",
")",
"{",
"pageDisplay",
".",
"setScaleType",
"(",
"ImageView",
".",
"ScaleType",
".",
"FIT_CENTER",
")",
";",
"}",
"else",
"{",
"Matrix",
"m",
"=",
"computePageDisplayMatrix",
"(",
"pageDisplay",
",",
"pageImage",
",",
"pageRotation",
")",
";",
"pageDisplay",
".",
"setScaleType",
"(",
"ImageView",
".",
"ScaleType",
".",
"MATRIX",
")",
";",
"pageDisplay",
".",
"setImageMatrix",
"(",
"m",
")",
";",
"}",
"pageDisplay",
".",
"setImageBitmap",
"(",
"pageImage",
")",
";",
"pageDisplay",
".",
"invalidate",
"(",
")",
";",
"}",
"}",
"private",
"Matrix",
"computePageDisplayMatrix",
"(",
"ImageView",
"display",
",",
"Bitmap",
"image",
",",
"int",
"rotation",
")",
"{",
"Matrix",
"m",
"=",
"new",
"Matrix",
"(",
")",
";",
"boolean",
"isImageSideways",
"=",
"(",
"rotation",
"%",
"180",
")",
"!=",
"0",
";",
"int",
"imageW",
"=",
"isImageSideways",
"?",
"image",
".",
"getHeight",
"(",
")",
":",
"image",
".",
"getWidth",
"(",
")",
";",
"int",
"imageH",
"=",
"isImageSideways",
"?",
"image",
".",
"getWidth",
"(",
")",
":",
"image",
".",
"getHeight",
"(",
")",
";",
"float",
"xScale",
"=",
"display",
".",
"getWidth",
"(",
")",
"/",
"(",
"float",
")",
"imageW",
";",
"float",
"yScale",
"=",
"display",
".",
"getHeight",
"(",
")",
"/",
"(",
"float",
")",
"imageH",
";",
"float",
"scale",
"=",
"Math",
".",
"min",
"(",
"xScale",
",",
"yScale",
")",
";",
"m",
".",
"postScale",
"(",
"scale",
",",
"scale",
")",
";",
"float",
"dx",
"=",
"(",
"display",
".",
"getWidth",
"(",
")",
"-",
"scale",
"*",
"image",
".",
"getWidth",
"(",
")",
")",
"/",
"2f",
";",
"float",
"dy",
"=",
"(",
"display",
".",
"getHeight",
"(",
")",
"-",
"scale",
"*",
"image",
".",
"getHeight",
"(",
")",
")",
"/",
"2f",
";",
"m",
".",
"postTranslate",
"(",
"dx",
",",
"dy",
")",
";",
"m",
".",
"postRotate",
"(",
"rotation",
",",
"display",
".",
"getWidth",
"(",
")",
"/",
"2f",
",",
"display",
".",
"getHeight",
"(",
")",
"/",
"2f",
")",
";",
"return",
"m",
";",
"}",
"}",
";",
"private",
"PdfRendererFragment",
".",
"PageReceiver",
"finalPageReceiver",
"=",
"new",
"PdfRendererFragment",
".",
"PageReceiver",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"pageRendering",
"(",
"int",
"pageNum",
")",
"{",
"displayScrim",
"(",
"true",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"pageRendered",
"(",
"int",
"pageNum",
",",
"Bitmap",
"pageImage",
")",
"{",
"displayScrim",
"(",
"false",
")",
";",
"returnSelectedPage",
"(",
")",
";",
"}",
"}",
";",
"}"
] | PDF rendering requires API 21 (Android 5.0, Lollipop), don't use this Activity in older devices | [
"PDF",
"rendering",
"requires",
"API",
"21",
"(",
"Android",
"5",
".",
"0",
"Lollipop",
")",
"don",
"'",
"t",
"use",
"this",
"Activity",
"in",
"older",
"devices"
] | [
"// PDF rendering is only supported on SDK 21 (Lollipop) and later",
"// No PDF support available, return immediately from activity",
"// Document has been opened, update activity title and render the first page",
"// Replace spaces in the PDF filename with underscores",
"// Drop suffix, and replace it with \".jpg\"",
"// Disable the only menu item on screen",
"// Start rendering full resolution version of the page",
"// Do not exit, since the selected page image file does not exist",
"// Add \"Select\" action to bottom bar",
"// Find out image width and height after rotation",
"// Scale image to fully fit in display",
"// Center image in display area",
"// Rotate image to requested orientation"
] | [
{
"param": "AppCompatActivity",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AppCompatActivity",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
13fe2add88062824b2c0d2118667bd2bdc614bc7 | Minionguyjpro/Ghostly-Skills | sources/com/onesignal/OSDynamicTriggerController.java | [
"MIT"
] | Java | AnonymousClass2 | /* renamed from: com.onesignal.OSDynamicTriggerController$2 reason: invalid class name */ | renamed from: com.onesignal.OSDynamicTriggerController$2 reason: invalid class name | [
"renamed",
"from",
":",
"com",
".",
"onesignal",
".",
"OSDynamicTriggerController$2",
"reason",
":",
"invalid",
"class",
"name"
] | static /* synthetic */ class AnonymousClass2 {
static final /* synthetic */ int[] $SwitchMap$com$onesignal$OSTrigger$OSTriggerKind;
static final /* synthetic */ int[] $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator;
/* JADX WARNING: Can't wrap try/catch for region: R(17:0|(2:1|2)|3|5|6|7|8|9|10|11|12|13|14|15|17|18|(3:19|20|22)) */
/* JADX WARNING: Can't wrap try/catch for region: R(20:0|1|2|3|5|6|7|8|9|10|11|12|13|14|15|17|18|19|20|22) */
/* JADX WARNING: Failed to process nested try/catch */
/* JADX WARNING: Missing exception handler attribute for start block: B:11:0x0033 */
/* JADX WARNING: Missing exception handler attribute for start block: B:13:0x003e */
/* JADX WARNING: Missing exception handler attribute for start block: B:19:0x005a */
/* JADX WARNING: Missing exception handler attribute for start block: B:7:0x001d */
/* JADX WARNING: Missing exception handler attribute for start block: B:9:0x0028 */
static {
/*
com.onesignal.OSTrigger$OSTriggerOperator[] r0 = com.onesignal.OSTrigger.OSTriggerOperator.values()
int r0 = r0.length
int[] r0 = new int[r0]
$SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator = r0
r1 = 1
com.onesignal.OSTrigger$OSTriggerOperator r2 = com.onesignal.OSTrigger.OSTriggerOperator.LESS_THAN // Catch:{ NoSuchFieldError -> 0x0012 }
int r2 = r2.ordinal() // Catch:{ NoSuchFieldError -> 0x0012 }
r0[r2] = r1 // Catch:{ NoSuchFieldError -> 0x0012 }
L_0x0012:
r0 = 2
int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x001d }
com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.LESS_THAN_OR_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x001d }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x001d }
r2[r3] = r0 // Catch:{ NoSuchFieldError -> 0x001d }
L_0x001d:
int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0028 }
com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.GREATER_THAN // Catch:{ NoSuchFieldError -> 0x0028 }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0028 }
r4 = 3
r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0028 }
L_0x0028:
int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0033 }
com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.GREATER_THAN_OR_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x0033 }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0033 }
r4 = 4
r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0033 }
L_0x0033:
int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x003e }
com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.EQUAL_TO // Catch:{ NoSuchFieldError -> 0x003e }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x003e }
r4 = 5
r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x003e }
L_0x003e:
int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0049 }
com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.NOT_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x0049 }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0049 }
r4 = 6
r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0049 }
L_0x0049:
com.onesignal.OSTrigger$OSTriggerKind[] r2 = com.onesignal.OSTrigger.OSTriggerKind.values()
int r2 = r2.length
int[] r2 = new int[r2]
$SwitchMap$com$onesignal$OSTrigger$OSTriggerKind = r2
com.onesignal.OSTrigger$OSTriggerKind r3 = com.onesignal.OSTrigger.OSTriggerKind.SESSION_TIME // Catch:{ NoSuchFieldError -> 0x005a }
int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x005a }
r2[r3] = r1 // Catch:{ NoSuchFieldError -> 0x005a }
L_0x005a:
int[] r1 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerKind // Catch:{ NoSuchFieldError -> 0x0064 }
com.onesignal.OSTrigger$OSTriggerKind r2 = com.onesignal.OSTrigger.OSTriggerKind.TIME_SINCE_LAST_IN_APP // Catch:{ NoSuchFieldError -> 0x0064 }
int r2 = r2.ordinal() // Catch:{ NoSuchFieldError -> 0x0064 }
r1[r2] = r0 // Catch:{ NoSuchFieldError -> 0x0064 }
L_0x0064:
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.onesignal.OSDynamicTriggerController.AnonymousClass2.<clinit>():void");
}
} | [
"static",
"/* synthetic */",
"class",
"AnonymousClass2",
"{",
"static",
"final",
"/* synthetic */",
"int",
"[",
"]",
"$SwitchMap$com$onesignal$OSTrigger$OSTriggerKind",
";",
"static",
"final",
"/* synthetic */",
"int",
"[",
"]",
"$SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator",
";",
"/* JADX WARNING: Can't wrap try/catch for region: R(17:0|(2:1|2)|3|5|6|7|8|9|10|11|12|13|14|15|17|18|(3:19|20|22)) */",
"/* JADX WARNING: Can't wrap try/catch for region: R(20:0|1|2|3|5|6|7|8|9|10|11|12|13|14|15|17|18|19|20|22) */",
"/* JADX WARNING: Failed to process nested try/catch */",
"/* JADX WARNING: Missing exception handler attribute for start block: B:11:0x0033 */",
"/* JADX WARNING: Missing exception handler attribute for start block: B:13:0x003e */",
"/* JADX WARNING: Missing exception handler attribute for start block: B:19:0x005a */",
"/* JADX WARNING: Missing exception handler attribute for start block: B:7:0x001d */",
"/* JADX WARNING: Missing exception handler attribute for start block: B:9:0x0028 */",
"static",
"{",
"/*\n com.onesignal.OSTrigger$OSTriggerOperator[] r0 = com.onesignal.OSTrigger.OSTriggerOperator.values()\n int r0 = r0.length\n int[] r0 = new int[r0]\n $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator = r0\n r1 = 1\n com.onesignal.OSTrigger$OSTriggerOperator r2 = com.onesignal.OSTrigger.OSTriggerOperator.LESS_THAN // Catch:{ NoSuchFieldError -> 0x0012 }\n int r2 = r2.ordinal() // Catch:{ NoSuchFieldError -> 0x0012 }\n r0[r2] = r1 // Catch:{ NoSuchFieldError -> 0x0012 }\n L_0x0012:\n r0 = 2\n int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x001d }\n com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.LESS_THAN_OR_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x001d }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x001d }\n r2[r3] = r0 // Catch:{ NoSuchFieldError -> 0x001d }\n L_0x001d:\n int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0028 }\n com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.GREATER_THAN // Catch:{ NoSuchFieldError -> 0x0028 }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0028 }\n r4 = 3\n r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0028 }\n L_0x0028:\n int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0033 }\n com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.GREATER_THAN_OR_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x0033 }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0033 }\n r4 = 4\n r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0033 }\n L_0x0033:\n int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x003e }\n com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.EQUAL_TO // Catch:{ NoSuchFieldError -> 0x003e }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x003e }\n r4 = 5\n r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x003e }\n L_0x003e:\n int[] r2 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerOperator // Catch:{ NoSuchFieldError -> 0x0049 }\n com.onesignal.OSTrigger$OSTriggerOperator r3 = com.onesignal.OSTrigger.OSTriggerOperator.NOT_EQUAL_TO // Catch:{ NoSuchFieldError -> 0x0049 }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x0049 }\n r4 = 6\n r2[r3] = r4 // Catch:{ NoSuchFieldError -> 0x0049 }\n L_0x0049:\n com.onesignal.OSTrigger$OSTriggerKind[] r2 = com.onesignal.OSTrigger.OSTriggerKind.values()\n int r2 = r2.length\n int[] r2 = new int[r2]\n $SwitchMap$com$onesignal$OSTrigger$OSTriggerKind = r2\n com.onesignal.OSTrigger$OSTriggerKind r3 = com.onesignal.OSTrigger.OSTriggerKind.SESSION_TIME // Catch:{ NoSuchFieldError -> 0x005a }\n int r3 = r3.ordinal() // Catch:{ NoSuchFieldError -> 0x005a }\n r2[r3] = r1 // Catch:{ NoSuchFieldError -> 0x005a }\n L_0x005a:\n int[] r1 = $SwitchMap$com$onesignal$OSTrigger$OSTriggerKind // Catch:{ NoSuchFieldError -> 0x0064 }\n com.onesignal.OSTrigger$OSTriggerKind r2 = com.onesignal.OSTrigger.OSTriggerKind.TIME_SINCE_LAST_IN_APP // Catch:{ NoSuchFieldError -> 0x0064 }\n int r2 = r2.ordinal() // Catch:{ NoSuchFieldError -> 0x0064 }\n r1[r2] = r0 // Catch:{ NoSuchFieldError -> 0x0064 }\n L_0x0064:\n return\n */",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"Method not decompiled: com.onesignal.OSDynamicTriggerController.AnonymousClass2.<clinit>():void",
"\"",
")",
";",
"}",
"}"
] | renamed from: com.onesignal.OSDynamicTriggerController$2 reason: invalid class name | [
"renamed",
"from",
":",
"com",
".",
"onesignal",
".",
"OSDynamicTriggerController$2",
"reason",
":",
"invalid",
"class",
"name"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd011c938a345486f74d1735a0dcaa59987ad44c | ntruchsess/tractusx | semantics/framework/src/main/java/net/catenax/semantics/framework/auth/BearerTokenIncomingInterceptor.java | [
"Apache-2.0"
] | Java | BearerTokenIncomingInterceptor | /**
* A Spring Web Interceptor to save the bearer token for routing to delegation
*/ | A Spring Web Interceptor to save the bearer token for routing to delegation | [
"A",
"Spring",
"Web",
"Interceptor",
"to",
"save",
"the",
"bearer",
"token",
"for",
"routing",
"to",
"delegation"
] | @RequiredArgsConstructor
public class BearerTokenIncomingInterceptor implements AsyncHandlerInterceptor {
private final BearerTokenWrapper tokenWrapper;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
final String authorizationHeaderValue = request.getHeader("Authorization");
if (authorizationHeaderValue != null && authorizationHeaderValue.startsWith("Bearer")) {
String token = authorizationHeaderValue.substring(7, authorizationHeaderValue.length());
tokenWrapper.setToken(token);
}
return true;
}
} | [
"@",
"RequiredArgsConstructor",
"public",
"class",
"BearerTokenIncomingInterceptor",
"implements",
"AsyncHandlerInterceptor",
"{",
"private",
"final",
"BearerTokenWrapper",
"tokenWrapper",
";",
"@",
"Override",
"public",
"boolean",
"preHandle",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"Object",
"handler",
")",
"throws",
"Exception",
"{",
"final",
"String",
"authorizationHeaderValue",
"=",
"request",
".",
"getHeader",
"(",
"\"",
"Authorization",
"\"",
")",
";",
"if",
"(",
"authorizationHeaderValue",
"!=",
"null",
"&&",
"authorizationHeaderValue",
".",
"startsWith",
"(",
"\"",
"Bearer",
"\"",
")",
")",
"{",
"String",
"token",
"=",
"authorizationHeaderValue",
".",
"substring",
"(",
"7",
",",
"authorizationHeaderValue",
".",
"length",
"(",
")",
")",
";",
"tokenWrapper",
".",
"setToken",
"(",
"token",
")",
";",
"}",
"return",
"true",
";",
"}",
"}"
] | A Spring Web Interceptor to save the bearer token for routing to delegation | [
"A",
"Spring",
"Web",
"Interceptor",
"to",
"save",
"the",
"bearer",
"token",
"for",
"routing",
"to",
"delegation"
] | [] | [
{
"param": "AsyncHandlerInterceptor",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AsyncHandlerInterceptor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd02a7e0e906ecd5c09ed537d935885526ba217a | brettdavidson3/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/dynamic/simple/sequencing/BaseSequencingTestSuite.java | [
"BSD-3-Clause"
] | Java | BaseSequencingTestSuite | //domain-specific (testing) imports
| domain-specific (testing) imports | [
"domain",
"-",
"specific",
"(",
"testing",
")",
"imports"
] | public abstract class BaseSequencingTestSuite {
static final String TABLE_NAME = "SIMPLE_TABLE_SEQ";
public static final String SEQ_TABLE_NAME = "TEST_SEQ";
static final String ENTITY_TYPE = "Simple";
//test fixtures
static EntityManagerFactory emf;
static JPADynamicHelper helper;
@Test
public void verifyConfig() throws Exception {
Server session = JpaHelper.getServerSession(emf);
ClassDescriptor descriptor = session.getClassDescriptorForAlias(ENTITY_TYPE);
assertNotNull("No descriptor found for alias: " + ENTITY_TYPE, descriptor);
DynamicTypeImpl simpleType = (DynamicTypeImpl)helper.getType(ENTITY_TYPE);
assertNotNull("EntityType not found for alias: " + ENTITY_TYPE, simpleType);
assertEquals(descriptor, simpleType.getDescriptor());
}
@Test
public void createSingleInstances() {
Server session = JpaHelper.getServerSession(emf);
DynamicTypeImpl simpleType = (DynamicTypeImpl)helper.getType(ENTITY_TYPE);
EntityManager em = emf.createEntityManager();
DynamicEntity simpleInstance = createSimpleInstance(1);
int simpleCount = ((Number)em.createQuery("SELECT COUNT(o) FROM " + ENTITY_TYPE + " o").getSingleResult()).intValue();
assertEquals(1, simpleCount);
IdentityMapAccessor cache = session.getIdentityMapAccessor();
assertTrue(cache.containsObjectInIdentityMap(simpleInstance));
em.clear();
cache.initializeAllIdentityMaps();
DynamicEntity findResult = (DynamicEntity)em.find(simpleType.getJavaClass(), 1);
assertNotNull(findResult);
assertEquals(simpleInstance.get("id"), findResult.get("id"));
assertEquals(simpleInstance.get("value1"), findResult.get("value1"));
em.close();
}
@Test
public void createTwoInstances() {
EntityManager em = emf.createEntityManager();
DynamicTypeImpl simpleType = (DynamicTypeImpl)helper.getType(ENTITY_TYPE);
DynamicEntity simpleInstance1 = createSimpleInstance(1);
DynamicEntity simpleInstance2 = createSimpleInstance(2);
int simpleCount =
((Number)em.createQuery("SELECT COUNT(o) FROM " + ENTITY_TYPE + " o").getSingleResult()).intValue();
assertEquals(2, simpleCount);
IdentityMapAccessor cache = helper.getSession().getIdentityMapAccessor();
assertTrue(cache.containsObjectInIdentityMap(simpleInstance1));
assertTrue(cache.containsObjectInIdentityMap(simpleInstance2));
em.clear();
cache.initializeAllIdentityMaps();
DynamicEntity findResult1 = (DynamicEntity)em.find(simpleType.getJavaClass(), 1);
DynamicEntity findResult2 = (DynamicEntity)em.find(simpleType.getJavaClass(), 2);
assertNotNull(findResult1);
assertNotNull(findResult2);
assertEquals(simpleInstance1.get("id"), findResult1.get("id"));
assertEquals(simpleInstance2.get("value1"), findResult2.get("value1"));
em.close();
}
public DynamicEntity createSimpleInstance(int expectedId) {
EntityManager em = emf.createEntityManager();
DynamicType simpleEntityType = helper.getType(ENTITY_TYPE);
Assert.assertNotNull(simpleEntityType);
DynamicEntity simpleInstance = simpleEntityType.newDynamicEntity();
simpleInstance.set("value1", TABLE_NAME);
em.getTransaction().begin();
assertEquals(0, simpleInstance.get("id"));
em.persist(simpleInstance);
em.getTransaction().commit();
// test after commit - in case sequencing involves round-trip to DB
assertEquals(expectedId, simpleInstance.get("id"));
em.close();
return simpleInstance;
}
} | [
"public",
"abstract",
"class",
"BaseSequencingTestSuite",
"{",
"static",
"final",
"String",
"TABLE_NAME",
"=",
"\"",
"SIMPLE_TABLE_SEQ",
"\"",
";",
"public",
"static",
"final",
"String",
"SEQ_TABLE_NAME",
"=",
"\"",
"TEST_SEQ",
"\"",
";",
"static",
"final",
"String",
"ENTITY_TYPE",
"=",
"\"",
"Simple",
"\"",
";",
"static",
"EntityManagerFactory",
"emf",
";",
"static",
"JPADynamicHelper",
"helper",
";",
"@",
"Test",
"public",
"void",
"verifyConfig",
"(",
")",
"throws",
"Exception",
"{",
"Server",
"session",
"=",
"JpaHelper",
".",
"getServerSession",
"(",
"emf",
")",
";",
"ClassDescriptor",
"descriptor",
"=",
"session",
".",
"getClassDescriptorForAlias",
"(",
"ENTITY_TYPE",
")",
";",
"assertNotNull",
"(",
"\"",
"No descriptor found for alias: ",
"\"",
"+",
"ENTITY_TYPE",
",",
"descriptor",
")",
";",
"DynamicTypeImpl",
"simpleType",
"=",
"(",
"DynamicTypeImpl",
")",
"helper",
".",
"getType",
"(",
"ENTITY_TYPE",
")",
";",
"assertNotNull",
"(",
"\"",
"EntityType not found for alias: ",
"\"",
"+",
"ENTITY_TYPE",
",",
"simpleType",
")",
";",
"assertEquals",
"(",
"descriptor",
",",
"simpleType",
".",
"getDescriptor",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"createSingleInstances",
"(",
")",
"{",
"Server",
"session",
"=",
"JpaHelper",
".",
"getServerSession",
"(",
"emf",
")",
";",
"DynamicTypeImpl",
"simpleType",
"=",
"(",
"DynamicTypeImpl",
")",
"helper",
".",
"getType",
"(",
"ENTITY_TYPE",
")",
";",
"EntityManager",
"em",
"=",
"emf",
".",
"createEntityManager",
"(",
")",
";",
"DynamicEntity",
"simpleInstance",
"=",
"createSimpleInstance",
"(",
"1",
")",
";",
"int",
"simpleCount",
"=",
"(",
"(",
"Number",
")",
"em",
".",
"createQuery",
"(",
"\"",
"SELECT COUNT(o) FROM ",
"\"",
"+",
"ENTITY_TYPE",
"+",
"\"",
" o",
"\"",
")",
".",
"getSingleResult",
"(",
")",
")",
".",
"intValue",
"(",
")",
";",
"assertEquals",
"(",
"1",
",",
"simpleCount",
")",
";",
"IdentityMapAccessor",
"cache",
"=",
"session",
".",
"getIdentityMapAccessor",
"(",
")",
";",
"assertTrue",
"(",
"cache",
".",
"containsObjectInIdentityMap",
"(",
"simpleInstance",
")",
")",
";",
"em",
".",
"clear",
"(",
")",
";",
"cache",
".",
"initializeAllIdentityMaps",
"(",
")",
";",
"DynamicEntity",
"findResult",
"=",
"(",
"DynamicEntity",
")",
"em",
".",
"find",
"(",
"simpleType",
".",
"getJavaClass",
"(",
")",
",",
"1",
")",
";",
"assertNotNull",
"(",
"findResult",
")",
";",
"assertEquals",
"(",
"simpleInstance",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
",",
"findResult",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"assertEquals",
"(",
"simpleInstance",
".",
"get",
"(",
"\"",
"value1",
"\"",
")",
",",
"findResult",
".",
"get",
"(",
"\"",
"value1",
"\"",
")",
")",
";",
"em",
".",
"close",
"(",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"createTwoInstances",
"(",
")",
"{",
"EntityManager",
"em",
"=",
"emf",
".",
"createEntityManager",
"(",
")",
";",
"DynamicTypeImpl",
"simpleType",
"=",
"(",
"DynamicTypeImpl",
")",
"helper",
".",
"getType",
"(",
"ENTITY_TYPE",
")",
";",
"DynamicEntity",
"simpleInstance1",
"=",
"createSimpleInstance",
"(",
"1",
")",
";",
"DynamicEntity",
"simpleInstance2",
"=",
"createSimpleInstance",
"(",
"2",
")",
";",
"int",
"simpleCount",
"=",
"(",
"(",
"Number",
")",
"em",
".",
"createQuery",
"(",
"\"",
"SELECT COUNT(o) FROM ",
"\"",
"+",
"ENTITY_TYPE",
"+",
"\"",
" o",
"\"",
")",
".",
"getSingleResult",
"(",
")",
")",
".",
"intValue",
"(",
")",
";",
"assertEquals",
"(",
"2",
",",
"simpleCount",
")",
";",
"IdentityMapAccessor",
"cache",
"=",
"helper",
".",
"getSession",
"(",
")",
".",
"getIdentityMapAccessor",
"(",
")",
";",
"assertTrue",
"(",
"cache",
".",
"containsObjectInIdentityMap",
"(",
"simpleInstance1",
")",
")",
";",
"assertTrue",
"(",
"cache",
".",
"containsObjectInIdentityMap",
"(",
"simpleInstance2",
")",
")",
";",
"em",
".",
"clear",
"(",
")",
";",
"cache",
".",
"initializeAllIdentityMaps",
"(",
")",
";",
"DynamicEntity",
"findResult1",
"=",
"(",
"DynamicEntity",
")",
"em",
".",
"find",
"(",
"simpleType",
".",
"getJavaClass",
"(",
")",
",",
"1",
")",
";",
"DynamicEntity",
"findResult2",
"=",
"(",
"DynamicEntity",
")",
"em",
".",
"find",
"(",
"simpleType",
".",
"getJavaClass",
"(",
")",
",",
"2",
")",
";",
"assertNotNull",
"(",
"findResult1",
")",
";",
"assertNotNull",
"(",
"findResult2",
")",
";",
"assertEquals",
"(",
"simpleInstance1",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
",",
"findResult1",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"assertEquals",
"(",
"simpleInstance2",
".",
"get",
"(",
"\"",
"value1",
"\"",
")",
",",
"findResult2",
".",
"get",
"(",
"\"",
"value1",
"\"",
")",
")",
";",
"em",
".",
"close",
"(",
")",
";",
"}",
"public",
"DynamicEntity",
"createSimpleInstance",
"(",
"int",
"expectedId",
")",
"{",
"EntityManager",
"em",
"=",
"emf",
".",
"createEntityManager",
"(",
")",
";",
"DynamicType",
"simpleEntityType",
"=",
"helper",
".",
"getType",
"(",
"ENTITY_TYPE",
")",
";",
"Assert",
".",
"assertNotNull",
"(",
"simpleEntityType",
")",
";",
"DynamicEntity",
"simpleInstance",
"=",
"simpleEntityType",
".",
"newDynamicEntity",
"(",
")",
";",
"simpleInstance",
".",
"set",
"(",
"\"",
"value1",
"\"",
",",
"TABLE_NAME",
")",
";",
"em",
".",
"getTransaction",
"(",
")",
".",
"begin",
"(",
")",
";",
"assertEquals",
"(",
"0",
",",
"simpleInstance",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"em",
".",
"persist",
"(",
"simpleInstance",
")",
";",
"em",
".",
"getTransaction",
"(",
")",
".",
"commit",
"(",
")",
";",
"assertEquals",
"(",
"expectedId",
",",
"simpleInstance",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"em",
".",
"close",
"(",
")",
";",
"return",
"simpleInstance",
";",
"}",
"}"
] | domain-specific (testing) imports | [
"domain",
"-",
"specific",
"(",
"testing",
")",
"imports"
] | [
"//test fixtures\r",
"// test after commit - in case sequencing involves round-trip to DB\r"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd02c0bc06604e39e830b980b5f0c193bd0ba4db | google-admin/gmail-oauth2-tools | obsolete/java/com/google/code/samples/xoauth/XoauthSaslClientFactory.java | [
"Apache-2.0"
] | Java | XoauthSaslClientFactory | /**
* A SaslClientFactory that returns instances of XoauthSaslClient.
*
* <p>Only the "XOAUTH" mechanism is supported. Only the "imaps" protocol is
* supported. The {@code callbackHandler} is passed to the XoauthSaslClient.
* Other parameters are ignored.
*/ | A SaslClientFactory that returns instances of XoauthSaslClient.
Only the "XOAUTH" mechanism is supported. Only the "imaps" protocol is
supported. The callbackHandler is passed to the XoauthSaslClient.
Other parameters are ignored. | [
"A",
"SaslClientFactory",
"that",
"returns",
"instances",
"of",
"XoauthSaslClient",
".",
"Only",
"the",
"\"",
"XOAUTH",
"\"",
"mechanism",
"is",
"supported",
".",
"Only",
"the",
"\"",
"imaps",
"\"",
"protocol",
"is",
"supported",
".",
"The",
"callbackHandler",
"is",
"passed",
"to",
"the",
"XoauthSaslClient",
".",
"Other",
"parameters",
"are",
"ignored",
"."
] | public class XoauthSaslClientFactory implements SaslClientFactory {
public static final String OAUTH_TOKEN_PROP =
"mail.imaps.sasl.mechanisms.xoauth.oauthToken";
public static final String OAUTH_TOKEN_SECRET_PROP =
"mail.imaps.sasl.mechanisms.xoauth.oauthTokenSecret";
public static final String CONSUMER_KEY_PROP =
"mail.imaps.sasl.mechanisms.xoauth.consumerKey";
public static final String CONSUMER_SECRET_PROP =
"mail.imaps.sasl.mechanisms.xoauth.consumerSecret";
public SaslClient createSaslClient(String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String, ?> props,
CallbackHandler callbackHandler) {
boolean matchedMechanism = false;
for (int i = 0; i < mechanisms.length; ++i) {
if ("XOAUTH".equalsIgnoreCase(mechanisms[i])) {
matchedMechanism = true;
break;
}
}
if (!matchedMechanism) {
return null;
}
XoauthProtocol xoauthProtocol = null;
if ("imaps".equalsIgnoreCase(protocol)) {
xoauthProtocol = XoauthProtocol.IMAP;
}
if ("smtp".equalsIgnoreCase(protocol)) {
xoauthProtocol = XoauthProtocol.SMTP;
}
if (xoauthProtocol == null) {
return null;
}
return new XoauthSaslClient(xoauthProtocol,
(String) props.get(OAUTH_TOKEN_PROP),
(String) props.get(OAUTH_TOKEN_SECRET_PROP),
(String) props.get(CONSUMER_KEY_PROP),
(String) props.get(CONSUMER_SECRET_PROP),
callbackHandler);
}
public String[] getMechanismNames(Map<String, ?> props) {
return new String[] {"XOAUTH"};
}
} | [
"public",
"class",
"XoauthSaslClientFactory",
"implements",
"SaslClientFactory",
"{",
"public",
"static",
"final",
"String",
"OAUTH_TOKEN_PROP",
"=",
"\"",
"mail.imaps.sasl.mechanisms.xoauth.oauthToken",
"\"",
";",
"public",
"static",
"final",
"String",
"OAUTH_TOKEN_SECRET_PROP",
"=",
"\"",
"mail.imaps.sasl.mechanisms.xoauth.oauthTokenSecret",
"\"",
";",
"public",
"static",
"final",
"String",
"CONSUMER_KEY_PROP",
"=",
"\"",
"mail.imaps.sasl.mechanisms.xoauth.consumerKey",
"\"",
";",
"public",
"static",
"final",
"String",
"CONSUMER_SECRET_PROP",
"=",
"\"",
"mail.imaps.sasl.mechanisms.xoauth.consumerSecret",
"\"",
";",
"public",
"SaslClient",
"createSaslClient",
"(",
"String",
"[",
"]",
"mechanisms",
",",
"String",
"authorizationId",
",",
"String",
"protocol",
",",
"String",
"serverName",
",",
"Map",
"<",
"String",
",",
"?",
">",
"props",
",",
"CallbackHandler",
"callbackHandler",
")",
"{",
"boolean",
"matchedMechanism",
"=",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mechanisms",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"\"",
"XOAUTH",
"\"",
".",
"equalsIgnoreCase",
"(",
"mechanisms",
"[",
"i",
"]",
")",
")",
"{",
"matchedMechanism",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"matchedMechanism",
")",
"{",
"return",
"null",
";",
"}",
"XoauthProtocol",
"xoauthProtocol",
"=",
"null",
";",
"if",
"(",
"\"",
"imaps",
"\"",
".",
"equalsIgnoreCase",
"(",
"protocol",
")",
")",
"{",
"xoauthProtocol",
"=",
"XoauthProtocol",
".",
"IMAP",
";",
"}",
"if",
"(",
"\"",
"smtp",
"\"",
".",
"equalsIgnoreCase",
"(",
"protocol",
")",
")",
"{",
"xoauthProtocol",
"=",
"XoauthProtocol",
".",
"SMTP",
";",
"}",
"if",
"(",
"xoauthProtocol",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"XoauthSaslClient",
"(",
"xoauthProtocol",
",",
"(",
"String",
")",
"props",
".",
"get",
"(",
"OAUTH_TOKEN_PROP",
")",
",",
"(",
"String",
")",
"props",
".",
"get",
"(",
"OAUTH_TOKEN_SECRET_PROP",
")",
",",
"(",
"String",
")",
"props",
".",
"get",
"(",
"CONSUMER_KEY_PROP",
")",
",",
"(",
"String",
")",
"props",
".",
"get",
"(",
"CONSUMER_SECRET_PROP",
")",
",",
"callbackHandler",
")",
";",
"}",
"public",
"String",
"[",
"]",
"getMechanismNames",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"props",
")",
"{",
"return",
"new",
"String",
"[",
"]",
"{",
"\"",
"XOAUTH",
"\"",
"}",
";",
"}",
"}"
] | A SaslClientFactory that returns instances of XoauthSaslClient. | [
"A",
"SaslClientFactory",
"that",
"returns",
"instances",
"of",
"XoauthSaslClient",
"."
] | [] | [
{
"param": "SaslClientFactory",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "SaslClientFactory",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd06133ac987a4704f2110e8e0d481b0f2110478 | hugmanrique/Cartage | src/main/java/me/hugmanrique/cartage/util/Checksums.java | [
"MIT"
] | Java | Checksums | /**
* Contains methods implementing checksum algorithms, and other checksum-related utilities.
*
* <p>A checksum function maps an arbitrary block of data to a number called a <i>checksum</i>.
*/ | Contains methods implementing checksum algorithms, and other checksum-related utilities.
A checksum function maps an arbitrary block of data to a number called a checksum. | [
"Contains",
"methods",
"implementing",
"checksum",
"algorithms",
"and",
"other",
"checksum",
"-",
"related",
"utilities",
".",
"A",
"checksum",
"function",
"maps",
"an",
"arbitrary",
"block",
"of",
"data",
"to",
"a",
"number",
"called",
"a",
"checksum",
"."
] | public final class Checksums {
// We could provide a ChecksumFunction interface, but the implemented checksum functions
// have different return types, which would require a generic type that boxes these values.
private static final short[] CRC_16_TABLE = new short[]
{
(short) 0xC0C1, (short) 0xC181, (short) 0xC301, (short) 0xC601, (short) 0xCC01,
(short) 0xD801, (short) 0xF001, (short) 0xA001
};
/**
* Computes the CRC-16 code of the next {@code length} bytes starting at the cartridge's current
* offset, which is then incremented by {@code length}.
*
* <p>This function is equivalent to the GetCRC16 routine present in the BIOS of the GBA and
* Nintendo DS.
*
* @param cartridge the source cartridge
* @param length the number of bytes to be read
* @return the CRC-16 code
* @throws IndexOutOfBoundsException if {@link Cartridge#remaining()} is less than {@code
* length}
*/
public static short crc16(final Cartridge cartridge, final int length) {
// TODO Optimize
short crc = 0;
for (int i = 0; i < length; i++) {
crc ^= cartridge.readByte();
for (int j = 0; j < 8; j++) {
if ((crc >>>= 1) != 0) {
crc ^= (CRC_16_TABLE[j] << (7 - j));
}
}
}
return crc;
}
/**
* Computes the CRC-16 code of the next {@code length} bytes starting at the given offset in the
* cartridge.
*
* <p>This function is equivalent to the GetCRC16 routine present in the BIOS of the GBA and
* Nintendo DS.
*
* @param cartridge the source cartridge
* @param offset the offset in the cartridge from which the first byte will be read
* @param length the number of bytes to be read
* @return the CRC-16 code
* @throws IndexOutOfBoundsException if {@code offset} is out of bounds, i.e. less than 0 or
* greater than <code>({@link Cartridge#size()} - length)</code>; or {@link
* Cartridge#remaining()} is less than {@code length}
*/
public static short crc16(final Cartridge cartridge, final long offset, final int length) {
final long prevOffset = cartridge.offset();
cartridge.setOffset(offset); // does bounds check
try {
return crc16(cartridge, length);
} finally {
cartridge.setOffset(prevOffset);
}
}
} | [
"public",
"final",
"class",
"Checksums",
"{",
"private",
"static",
"final",
"short",
"[",
"]",
"CRC_16_TABLE",
"=",
"new",
"short",
"[",
"]",
"{",
"(",
"short",
")",
"0xC0C1",
",",
"(",
"short",
")",
"0xC181",
",",
"(",
"short",
")",
"0xC301",
",",
"(",
"short",
")",
"0xC601",
",",
"(",
"short",
")",
"0xCC01",
",",
"(",
"short",
")",
"0xD801",
",",
"(",
"short",
")",
"0xF001",
",",
"(",
"short",
")",
"0xA001",
"}",
";",
"/**\n * Computes the CRC-16 code of the next {@code length} bytes starting at the cartridge's current\n * offset, which is then incremented by {@code length}.\n *\n * <p>This function is equivalent to the GetCRC16 routine present in the BIOS of the GBA and\n * Nintendo DS.\n *\n * @param cartridge the source cartridge\n * @param length the number of bytes to be read\n * @return the CRC-16 code\n * @throws IndexOutOfBoundsException if {@link Cartridge#remaining()} is less than {@code\n * length}\n */",
"public",
"static",
"short",
"crc16",
"(",
"final",
"Cartridge",
"cartridge",
",",
"final",
"int",
"length",
")",
"{",
"short",
"crc",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"crc",
"^=",
"cartridge",
".",
"readByte",
"(",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"8",
";",
"j",
"++",
")",
"{",
"if",
"(",
"(",
"crc",
">>>=",
"1",
")",
"!=",
"0",
")",
"{",
"crc",
"^=",
"(",
"CRC_16_TABLE",
"[",
"j",
"]",
"<<",
"(",
"7",
"-",
"j",
")",
")",
";",
"}",
"}",
"}",
"return",
"crc",
";",
"}",
"/**\n * Computes the CRC-16 code of the next {@code length} bytes starting at the given offset in the\n * cartridge.\n *\n * <p>This function is equivalent to the GetCRC16 routine present in the BIOS of the GBA and\n * Nintendo DS.\n *\n * @param cartridge the source cartridge\n * @param offset the offset in the cartridge from which the first byte will be read\n * @param length the number of bytes to be read\n * @return the CRC-16 code\n * @throws IndexOutOfBoundsException if {@code offset} is out of bounds, i.e. less than 0 or\n * greater than <code>({@link Cartridge#size()} - length)</code>; or {@link\n * Cartridge#remaining()} is less than {@code length}\n */",
"public",
"static",
"short",
"crc16",
"(",
"final",
"Cartridge",
"cartridge",
",",
"final",
"long",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"final",
"long",
"prevOffset",
"=",
"cartridge",
".",
"offset",
"(",
")",
";",
"cartridge",
".",
"setOffset",
"(",
"offset",
")",
";",
"try",
"{",
"return",
"crc16",
"(",
"cartridge",
",",
"length",
")",
";",
"}",
"finally",
"{",
"cartridge",
".",
"setOffset",
"(",
"prevOffset",
")",
";",
"}",
"}",
"}"
] | Contains methods implementing checksum algorithms, and other checksum-related utilities. | [
"Contains",
"methods",
"implementing",
"checksum",
"algorithms",
"and",
"other",
"checksum",
"-",
"related",
"utilities",
"."
] | [
"// We could provide a ChecksumFunction interface, but the implemented checksum functions",
"// have different return types, which would require a generic type that boxes these values.",
"// TODO Optimize",
"// does bounds check"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd06d7d615afc3d415cf8d0aab545f9b2152e1f6 | jettmarks/clueRide-angular | crCore/src/test/java/com/clueride/service/DefaultLocationServiceTest.java | [
"Apache-2.0"
] | Java | DefaultLocationServiceTest | /**
* Exercises the DefaultLocationServiceTest class.
*/ | Exercises the DefaultLocationServiceTest class. | [
"Exercises",
"the",
"DefaultLocationServiceTest",
"class",
"."
] | @Guice(modules=CoreGuiceModuleTest.class)
public class DefaultLocationServiceTest {
private static final Logger LOGGER = Logger.getLogger(DefaultLocationServiceTest.class);
private DefaultLocationService toTest;
@Inject
private Location location;
@Inject
private @Jpa LocationStore locationStore;
@Inject
private NodeService nodeService;
@Inject
private LatLonService latLonService;
@Inject
private LocationTypeService locationTypeService;
@Inject
private Provider<DefaultLocationService> toTestProvider;
@Inject
private Provider<LocationType> locationTypeProvider;
@BeforeMethod
public void setup() {
initMocks(this);
reset(
locationStore,
nodeService
);
toTest = toTestProvider.get();
}
@Test
public void testGetLocation() throws Exception {
Location expected = location;
/* train mocks */
Integer locationId = location.getId();
when(locationStore.getLocationById(locationId)).thenReturn(expected);
/* make call */
String actual = toTest.getLocation(locationId);
/* verify results */
assertNotNull(actual);
assertTrue(!actual.isEmpty());
LOGGER.debug(actual);
}
/**
* For this test, the location IDs match the Node IDs.
* @throws Exception catchall
*/
@Test
public void testGetNearestMarkerLocations() throws Exception {
List<URL> imageList = new ArrayList<>();
imageList.add(new URL("http://localhost:8080/"));
List<Integer> clueList = new ArrayList<>();
clueList.add(1);
clueList.add(2);
// Prepare fake locations
List<Location.Builder> locationList = new ArrayList<>();
Location.Builder builder = Location.Builder.builder();
for (Integer id = 1; id<=6; id++) {
LocationType.Builder locationTypeBuilderFromService =
LocationType.Builder.from(locationTypeProvider.get())
.withId(id);
LocationType locationTypeToMatch = locationTypeBuilderFromService.build();
when(locationTypeService.getById(id)).thenReturn(locationTypeToMatch);
when(nodeService.getPointByNodeId(id)).thenReturn(PointFactory.getJtsInstance(10.0, 11.0, 0.0));
locationList.add(
builder.withId(id)
.withNodeId(id)
.withName("Test Loc " + id)
.withDescription("Description for Loc " + id)
.withLocationTypeId(id)
.withImageUrls(imageList)
.withClueIds(clueList)
);
}
when(locationStore.getLocationBuilders()).thenReturn(locationList);
assertNotNull(toTest);
String actual = toTest.getNearestMarkerLocations(-10.0, 12.7);
LOGGER.debug(actual);
}
@Test
public void testProposeLocation() throws Exception {
/* setup data */
double lat = 33.77;
double lon = -84.37;
Integer newLatLonId = 19;
LatLon latLonWithoutId = new LatLon(lat, lon);
LatLon latLon = new LatLon(lat, lon).setId(newLatLonId);
LocationType expectedLocationType = locationTypeProvider.get();
Location expected = Location.Builder.builder()
.withLocationType(expectedLocationType)
.withLatLon(latLon)
.build();
/* train mocks */
when(latLonService.addNew(latLonWithoutId)).thenReturn(latLon);
when(locationStore.addNew(any(Location.Builder.class))).thenReturn(newLatLonId);
when(locationStore.getLocationById(newLatLonId)).thenReturn(expected);
when(locationTypeService.getByName(expected.getLocationTypeName()))
.thenReturn(expectedLocationType);
/* make call */
Location actual;
actual = toTest.proposeLocation(latLon, locationTypeProvider.get().getName());
/* verify results */
assertNotNull(actual);
assertEquals(actual, expected);
}
@Test
public void testDecodeBase64() {
// String expected = "Test String to be encoded";
//
// String encoded = "data:image/jpeg;base64," + BaseEncoding.base64().encode(expected);
// String actual = toTest.decodeBase64(encoded);
// assertEquals(actual, expected);
}
} | [
"@",
"Guice",
"(",
"modules",
"=",
"CoreGuiceModuleTest",
".",
"class",
")",
"public",
"class",
"DefaultLocationServiceTest",
"{",
"private",
"static",
"final",
"Logger",
"LOGGER",
"=",
"Logger",
".",
"getLogger",
"(",
"DefaultLocationServiceTest",
".",
"class",
")",
";",
"private",
"DefaultLocationService",
"toTest",
";",
"@",
"Inject",
"private",
"Location",
"location",
";",
"@",
"Inject",
"private",
"@",
"Jpa",
"LocationStore",
"locationStore",
";",
"@",
"Inject",
"private",
"NodeService",
"nodeService",
";",
"@",
"Inject",
"private",
"LatLonService",
"latLonService",
";",
"@",
"Inject",
"private",
"LocationTypeService",
"locationTypeService",
";",
"@",
"Inject",
"private",
"Provider",
"<",
"DefaultLocationService",
">",
"toTestProvider",
";",
"@",
"Inject",
"private",
"Provider",
"<",
"LocationType",
">",
"locationTypeProvider",
";",
"@",
"BeforeMethod",
"public",
"void",
"setup",
"(",
")",
"{",
"initMocks",
"(",
"this",
")",
";",
"reset",
"(",
"locationStore",
",",
"nodeService",
")",
";",
"toTest",
"=",
"toTestProvider",
".",
"get",
"(",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testGetLocation",
"(",
")",
"throws",
"Exception",
"{",
"Location",
"expected",
"=",
"location",
";",
"/* train mocks */",
"Integer",
"locationId",
"=",
"location",
".",
"getId",
"(",
")",
";",
"when",
"(",
"locationStore",
".",
"getLocationById",
"(",
"locationId",
")",
")",
".",
"thenReturn",
"(",
"expected",
")",
";",
"/* make call */",
"String",
"actual",
"=",
"toTest",
".",
"getLocation",
"(",
"locationId",
")",
";",
"/* verify results */",
"assertNotNull",
"(",
"actual",
")",
";",
"assertTrue",
"(",
"!",
"actual",
".",
"isEmpty",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"actual",
")",
";",
"}",
"/**\n * For this test, the location IDs match the Node IDs.\n * @throws Exception catchall\n */",
"@",
"Test",
"public",
"void",
"testGetNearestMarkerLocations",
"(",
")",
"throws",
"Exception",
"{",
"List",
"<",
"URL",
">",
"imageList",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"imageList",
".",
"add",
"(",
"new",
"URL",
"(",
"\"",
"http://localhost:8080/",
"\"",
")",
")",
";",
"List",
"<",
"Integer",
">",
"clueList",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"clueList",
".",
"add",
"(",
"1",
")",
";",
"clueList",
".",
"add",
"(",
"2",
")",
";",
"List",
"<",
"Location",
".",
"Builder",
">",
"locationList",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Location",
".",
"Builder",
"builder",
"=",
"Location",
".",
"Builder",
".",
"builder",
"(",
")",
";",
"for",
"(",
"Integer",
"id",
"=",
"1",
";",
"id",
"<=",
"6",
";",
"id",
"++",
")",
"{",
"LocationType",
".",
"Builder",
"locationTypeBuilderFromService",
"=",
"LocationType",
".",
"Builder",
".",
"from",
"(",
"locationTypeProvider",
".",
"get",
"(",
")",
")",
".",
"withId",
"(",
"id",
")",
";",
"LocationType",
"locationTypeToMatch",
"=",
"locationTypeBuilderFromService",
".",
"build",
"(",
")",
";",
"when",
"(",
"locationTypeService",
".",
"getById",
"(",
"id",
")",
")",
".",
"thenReturn",
"(",
"locationTypeToMatch",
")",
";",
"when",
"(",
"nodeService",
".",
"getPointByNodeId",
"(",
"id",
")",
")",
".",
"thenReturn",
"(",
"PointFactory",
".",
"getJtsInstance",
"(",
"10.0",
",",
"11.0",
",",
"0.0",
")",
")",
";",
"locationList",
".",
"add",
"(",
"builder",
".",
"withId",
"(",
"id",
")",
".",
"withNodeId",
"(",
"id",
")",
".",
"withName",
"(",
"\"",
"Test Loc ",
"\"",
"+",
"id",
")",
".",
"withDescription",
"(",
"\"",
"Description for Loc ",
"\"",
"+",
"id",
")",
".",
"withLocationTypeId",
"(",
"id",
")",
".",
"withImageUrls",
"(",
"imageList",
")",
".",
"withClueIds",
"(",
"clueList",
")",
")",
";",
"}",
"when",
"(",
"locationStore",
".",
"getLocationBuilders",
"(",
")",
")",
".",
"thenReturn",
"(",
"locationList",
")",
";",
"assertNotNull",
"(",
"toTest",
")",
";",
"String",
"actual",
"=",
"toTest",
".",
"getNearestMarkerLocations",
"(",
"-",
"10.0",
",",
"12.7",
")",
";",
"LOGGER",
".",
"debug",
"(",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testProposeLocation",
"(",
")",
"throws",
"Exception",
"{",
"/* setup data */",
"double",
"lat",
"=",
"33.77",
";",
"double",
"lon",
"=",
"-",
"84.37",
";",
"Integer",
"newLatLonId",
"=",
"19",
";",
"LatLon",
"latLonWithoutId",
"=",
"new",
"LatLon",
"(",
"lat",
",",
"lon",
")",
";",
"LatLon",
"latLon",
"=",
"new",
"LatLon",
"(",
"lat",
",",
"lon",
")",
".",
"setId",
"(",
"newLatLonId",
")",
";",
"LocationType",
"expectedLocationType",
"=",
"locationTypeProvider",
".",
"get",
"(",
")",
";",
"Location",
"expected",
"=",
"Location",
".",
"Builder",
".",
"builder",
"(",
")",
".",
"withLocationType",
"(",
"expectedLocationType",
")",
".",
"withLatLon",
"(",
"latLon",
")",
".",
"build",
"(",
")",
";",
"/* train mocks */",
"when",
"(",
"latLonService",
".",
"addNew",
"(",
"latLonWithoutId",
")",
")",
".",
"thenReturn",
"(",
"latLon",
")",
";",
"when",
"(",
"locationStore",
".",
"addNew",
"(",
"any",
"(",
"Location",
".",
"Builder",
".",
"class",
")",
")",
")",
".",
"thenReturn",
"(",
"newLatLonId",
")",
";",
"when",
"(",
"locationStore",
".",
"getLocationById",
"(",
"newLatLonId",
")",
")",
".",
"thenReturn",
"(",
"expected",
")",
";",
"when",
"(",
"locationTypeService",
".",
"getByName",
"(",
"expected",
".",
"getLocationTypeName",
"(",
")",
")",
")",
".",
"thenReturn",
"(",
"expectedLocationType",
")",
";",
"/* make call */",
"Location",
"actual",
";",
"actual",
"=",
"toTest",
".",
"proposeLocation",
"(",
"latLon",
",",
"locationTypeProvider",
".",
"get",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"/* verify results */",
"assertNotNull",
"(",
"actual",
")",
";",
"assertEquals",
"(",
"actual",
",",
"expected",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDecodeBase64",
"(",
")",
"{",
"}",
"}"
] | Exercises the DefaultLocationServiceTest class. | [
"Exercises",
"the",
"DefaultLocationServiceTest",
"class",
"."
] | [
"// Prepare fake locations",
"// String expected = \"Test String to be encoded\";",
"//",
"// String encoded = \"data:image/jpeg;base64,\" + BaseEncoding.base64().encode(expected);",
"// String actual = toTest.decodeBase64(encoded);",
"// assertEquals(actual, expected);"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd0d636de6211a923609a4194dd749c08465ae2a | xpanxion/xhire-spring-bootcamp | source/jenkins/src/main/java/com/xpx/bootcamp/jenkins/entity/Action.java | [
"MIT"
] | Java | Action | /**
* The Class Action.
*/ | The Class Action. | [
"The",
"Class",
"Action",
"."
] | public class Action {
/** The parameters. */
List<Parameter> parameters;
/**
* Gets the parameters.
*
* @return the parameters
*/
public List<Parameter> getParameters() {
return parameters;
}
/**
* Sets the parameters.
*
* @param parameters the new parameters
*/
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
} | [
"public",
"class",
"Action",
"{",
"/** The parameters. */",
"List",
"<",
"Parameter",
">",
"parameters",
";",
"/**\n\t * Gets the parameters.\n\t *\n\t * @return the parameters\n\t */",
"public",
"List",
"<",
"Parameter",
">",
"getParameters",
"(",
")",
"{",
"return",
"parameters",
";",
"}",
"/**\n\t * Sets the parameters.\n\t *\n\t * @param parameters the new parameters\n\t */",
"public",
"void",
"setParameters",
"(",
"List",
"<",
"Parameter",
">",
"parameters",
")",
"{",
"this",
".",
"parameters",
"=",
"parameters",
";",
"}",
"}"
] | The Class Action. | [
"The",
"Class",
"Action",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd0f32c92b92574382217e15fddf34a265d26927 | citlab/Intercloud | xmpp-occi/src/main/java/de/tu_berlin/cit/intercloud/occi/sla/OfferKind.java | [
"Apache-2.0"
] | Java | OfferKind | /**
* TODO
*
* @author Alexander Stanik <alexander.stanik@tu-berlin.de>
*/ |
@author Alexander Stanik | [
"@author",
"Alexander",
"Stanik"
] | @Kind(schema = SlaSchemas.SlaSchema, term = OfferKind.OfferTerm)
public class OfferKind extends Category {
public final static String OfferTitle = "Offer Resource";
public final static String OfferTerm = "offer";
public OfferKind() {
super(OfferTitle);
}
public OfferKind(String title) {
super(title);
}
} | [
"@",
"Kind",
"(",
"schema",
"=",
"SlaSchemas",
".",
"SlaSchema",
",",
"term",
"=",
"OfferKind",
".",
"OfferTerm",
")",
"public",
"class",
"OfferKind",
"extends",
"Category",
"{",
"public",
"final",
"static",
"String",
"OfferTitle",
"=",
"\"",
"Offer Resource",
"\"",
";",
"public",
"final",
"static",
"String",
"OfferTerm",
"=",
"\"",
"offer",
"\"",
";",
"public",
"OfferKind",
"(",
")",
"{",
"super",
"(",
"OfferTitle",
")",
";",
"}",
"public",
"OfferKind",
"(",
"String",
"title",
")",
"{",
"super",
"(",
"title",
")",
";",
"}",
"}"
] | TODO | [
"TODO"
] | [] | [
{
"param": "Category",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Category",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd18be1086ed80cf6365ba13bb76ae17430f519a | AlexRogalskiy/java4you | src/main/java/com/sensiblemetrics/api/alpenidos/pattern/command6/management/OrderBookSellCommand.java | [
"MIT"
] | Java | OrderBookSellCommand | /**
* Concrete Command for placing a SELL order.
*/ | Concrete Command for placing a SELL order. | [
"Concrete",
"Command",
"for",
"placing",
"a",
"SELL",
"order",
"."
] | public class OrderBookSellCommand implements OrderCommand {
/**
* The Order Book is the receiver
*/
private final OrderBook orderBook;
/**
* Constructs the command with the Recevier.
*
* @param orderBook the receiver the command will perform operations on.
*/
public OrderBookSellCommand(OrderBook orderBook) {
this.orderBook = orderBook;
}
@Override
public void execute(Order order) {
orderBook.updateSellOrders(order);
}
} | [
"public",
"class",
"OrderBookSellCommand",
"implements",
"OrderCommand",
"{",
"/**\n * The Order Book is the receiver\n */",
"private",
"final",
"OrderBook",
"orderBook",
";",
"/**\n * Constructs the command with the Recevier.\n *\n * @param orderBook the receiver the command will perform operations on.\n */",
"public",
"OrderBookSellCommand",
"(",
"OrderBook",
"orderBook",
")",
"{",
"this",
".",
"orderBook",
"=",
"orderBook",
";",
"}",
"@",
"Override",
"public",
"void",
"execute",
"(",
"Order",
"order",
")",
"{",
"orderBook",
".",
"updateSellOrders",
"(",
"order",
")",
";",
"}",
"}"
] | Concrete Command for placing a SELL order. | [
"Concrete",
"Command",
"for",
"placing",
"a",
"SELL",
"order",
"."
] | [] | [
{
"param": "OrderCommand",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "OrderCommand",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd1c17187f98bcb16fac9d4a2e4f66e9e55411cf | chentc/PrivacyStreams-Android | privacystreams-core/src/main/java/com/github/privacystreams/core/actions/callback/OnFieldChangeCallback.java | [
"Apache-2.0"
] | Java | OnFieldChangeCallback | /**
* Created by yuanchun on 28/12/2016.
* Callback with a field value of an item
* if the field value is different from the field value of the former item.
*/ | Created by yuanchun on 28/12/2016.
Callback with a field value of an item
if the field value is different from the field value of the former item. | [
"Created",
"by",
"yuanchun",
"on",
"28",
"/",
"12",
"/",
"2016",
".",
"Callback",
"with",
"a",
"field",
"value",
"of",
"an",
"item",
"if",
"the",
"field",
"value",
"is",
"different",
"from",
"the",
"field",
"value",
"of",
"the",
"former",
"item",
"."
] | class OnFieldChangeCallback<TValue, Void> extends MStreamAction {
private final String fieldToSelect;
private final Function<TValue, Void> fieldValueCallback;
OnFieldChangeCallback(String fieldToSelect, Function<TValue, Void> fieldValueCallback) {
this.fieldToSelect = Assertions.notNull("fieldToSelect", fieldToSelect);
this.fieldValueCallback = Assertions.notNull("fieldValueCallback", fieldValueCallback);
this.addParameters(fieldToSelect, fieldValueCallback);
}
private transient TValue lastFieldValue;
@Override
protected void onInput(Item item) {
if (item.isEndOfStream()) {
this.finish();
return;
}
TValue fieldValue = item.getValueByField(this.fieldToSelect);
if (fieldValue.equals(this.lastFieldValue)) return;
this.fieldValueCallback.apply(this.getUQI(), fieldValue);
this.lastFieldValue = fieldValue;
}
} | [
"class",
"OnFieldChangeCallback",
"<",
"TValue",
",",
"Void",
">",
"extends",
"MStreamAction",
"{",
"private",
"final",
"String",
"fieldToSelect",
";",
"private",
"final",
"Function",
"<",
"TValue",
",",
"Void",
">",
"fieldValueCallback",
";",
"OnFieldChangeCallback",
"(",
"String",
"fieldToSelect",
",",
"Function",
"<",
"TValue",
",",
"Void",
">",
"fieldValueCallback",
")",
"{",
"this",
".",
"fieldToSelect",
"=",
"Assertions",
".",
"notNull",
"(",
"\"",
"fieldToSelect",
"\"",
",",
"fieldToSelect",
")",
";",
"this",
".",
"fieldValueCallback",
"=",
"Assertions",
".",
"notNull",
"(",
"\"",
"fieldValueCallback",
"\"",
",",
"fieldValueCallback",
")",
";",
"this",
".",
"addParameters",
"(",
"fieldToSelect",
",",
"fieldValueCallback",
")",
";",
"}",
"private",
"transient",
"TValue",
"lastFieldValue",
";",
"@",
"Override",
"protected",
"void",
"onInput",
"(",
"Item",
"item",
")",
"{",
"if",
"(",
"item",
".",
"isEndOfStream",
"(",
")",
")",
"{",
"this",
".",
"finish",
"(",
")",
";",
"return",
";",
"}",
"TValue",
"fieldValue",
"=",
"item",
".",
"getValueByField",
"(",
"this",
".",
"fieldToSelect",
")",
";",
"if",
"(",
"fieldValue",
".",
"equals",
"(",
"this",
".",
"lastFieldValue",
")",
")",
"return",
";",
"this",
".",
"fieldValueCallback",
".",
"apply",
"(",
"this",
".",
"getUQI",
"(",
")",
",",
"fieldValue",
")",
";",
"this",
".",
"lastFieldValue",
"=",
"fieldValue",
";",
"}",
"}"
] | Created by yuanchun on 28/12/2016. | [
"Created",
"by",
"yuanchun",
"on",
"28",
"/",
"12",
"/",
"2016",
"."
] | [] | [
{
"param": "MStreamAction",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "MStreamAction",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd1c62e7fa9df9d083c8c1dcbeed68eccac29619 | cFactorComputing/odin | odin-mvc/src/main/java/io/github/cfactorcomputing/odin/mvc/security/OdinSecurityProperties.java | [
"Apache-2.0"
] | Java | OdinSecurityProperties | /**
* Created by gibugeorge on 21/12/2016.
*/ | Created by gibugeorge on 21/12/2016. | [
"Created",
"by",
"gibugeorge",
"on",
"21",
"/",
"12",
"/",
"2016",
"."
] | @ConfigurationProperties(prefix = "security")
public class OdinSecurityProperties {
public static final int BASIC_AUTH_ORDER = SecurityProperties.BASIC_AUTH_ORDER;
private boolean enabled = true;
private DigestAuthenticationProperties digest = new DigestAuthenticationProperties();
private OAuth2SecurityProperties oauth2 = new OAuth2SecurityProperties();
private User user = new User();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public DigestAuthenticationProperties getDigest() {
return digest;
}
public void setDigest(DigestAuthenticationProperties digest) {
this.digest = digest;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public static class User {
private String name;
private String password;
private List<String> role = new ArrayList<>(Arrays.asList("ROLE_USER"));
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRole() {
return role;
}
public void setRole(List<String> role) {
this.role = role;
}
}
} | [
"@",
"ConfigurationProperties",
"(",
"prefix",
"=",
"\"",
"security",
"\"",
")",
"public",
"class",
"OdinSecurityProperties",
"{",
"public",
"static",
"final",
"int",
"BASIC_AUTH_ORDER",
"=",
"SecurityProperties",
".",
"BASIC_AUTH_ORDER",
";",
"private",
"boolean",
"enabled",
"=",
"true",
";",
"private",
"DigestAuthenticationProperties",
"digest",
"=",
"new",
"DigestAuthenticationProperties",
"(",
")",
";",
"private",
"OAuth2SecurityProperties",
"oauth2",
"=",
"new",
"OAuth2SecurityProperties",
"(",
")",
";",
"private",
"User",
"user",
"=",
"new",
"User",
"(",
")",
";",
"public",
"boolean",
"isEnabled",
"(",
")",
"{",
"return",
"enabled",
";",
"}",
"public",
"void",
"setEnabled",
"(",
"boolean",
"enabled",
")",
"{",
"this",
".",
"enabled",
"=",
"enabled",
";",
"}",
"public",
"DigestAuthenticationProperties",
"getDigest",
"(",
")",
"{",
"return",
"digest",
";",
"}",
"public",
"void",
"setDigest",
"(",
"DigestAuthenticationProperties",
"digest",
")",
"{",
"this",
".",
"digest",
"=",
"digest",
";",
"}",
"public",
"User",
"getUser",
"(",
")",
"{",
"return",
"user",
";",
"}",
"public",
"void",
"setUser",
"(",
"User",
"user",
")",
"{",
"this",
".",
"user",
"=",
"user",
";",
"}",
"public",
"static",
"class",
"User",
"{",
"private",
"String",
"name",
";",
"private",
"String",
"password",
";",
"private",
"List",
"<",
"String",
">",
"role",
"=",
"new",
"ArrayList",
"<",
">",
"(",
"Arrays",
".",
"asList",
"(",
"\"",
"ROLE_USER",
"\"",
")",
")",
";",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"name",
";",
"}",
"public",
"void",
"setName",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"public",
"String",
"getPassword",
"(",
")",
"{",
"return",
"password",
";",
"}",
"public",
"void",
"setPassword",
"(",
"String",
"password",
")",
"{",
"this",
".",
"password",
"=",
"password",
";",
"}",
"public",
"List",
"<",
"String",
">",
"getRole",
"(",
")",
"{",
"return",
"role",
";",
"}",
"public",
"void",
"setRole",
"(",
"List",
"<",
"String",
">",
"role",
")",
"{",
"this",
".",
"role",
"=",
"role",
";",
"}",
"}",
"}"
] | Created by gibugeorge on 21/12/2016. | [
"Created",
"by",
"gibugeorge",
"on",
"21",
"/",
"12",
"/",
"2016",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd23a5be6970d0e082b84ea04dbaa9cf0e658b33 | vlipovetskii/ithillel-prj | vlfsoft.ithillel.jee.test/src/test/java/vlfsoft/ithillel/jee/GetNextValueSynchronized.java | [
"Apache-2.0"
] | Java | GetNextValueSynchronized | /**
* Given the following class;
* public class IncrementSynchronize {
* private int value = 0;
* //getNextValue()
* }
* Write three different method options for getNextValue() that will return 'value++', each method needs to be synchronized in a different way.
*
* Assumption: public int getNextValue() { return value++; }
* If the Task require public int getNextValue() { return ++value; }, then replace return value++ with return ++value and leverage incrementAndGet() instead of getAndIncrement()
*/ | Given the following class;
public class IncrementSynchronize {
private int value = 0;
getNextValue()
}
Write three different method options for getNextValue() that will return 'value++', each method needs to be synchronized in a different way.
| [
"Given",
"the",
"following",
"class",
";",
"public",
"class",
"IncrementSynchronize",
"{",
"private",
"int",
"value",
"=",
"0",
";",
"getNextValue",
"()",
"}",
"Write",
"three",
"different",
"method",
"options",
"for",
"getNextValue",
"()",
"that",
"will",
"return",
"'",
"value",
"++",
"'",
"each",
"method",
"needs",
"to",
"be",
"synchronized",
"in",
"a",
"different",
"way",
"."
] | class GetNextValueSynchronized {
private final static int maxCount = 10;
static class GetNextValueRunnable implements Runnable {
CountDownLatch finishTestLatch;
IncrementSynchronizeA incrementSynchronize;
GetNextValueRunnable(CountDownLatch finishTestLatch, IncrementSynchronizeA incrementSynchronize) {
this.finishTestLatch = finishTestLatch;
this.incrementSynchronize = incrementSynchronize;
}
int value = 0;
@Override
public void run() {
while (value < maxCount) {
try {
// Leverage sleep, to run threads more parallel.
TimeUnit.MILLISECONDS.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s: getNextValue = %d\n", Thread.currentThread().getName(), incrementSynchronize.getNextValue());
value++;
}
finishTestLatch.countDown();
}
}
interface IncrementSynchronizeA {
int getValue();
int getNextValue();
}
private void getNextValueSynchronizedTest(IncrementSynchronizeA incrementSynchronize) {
CountDownLatch finishTestLatch = new CountDownLatch(2);
GetNextValueRunnable t1 = new GetNextValueRunnable(finishTestLatch, incrementSynchronize);
GetNextValueRunnable t2 = new GetNextValueRunnable(finishTestLatch, incrementSynchronize);
// new Thread(t1).start();
// new Thread(t2).start();
// Or
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(t1);
executorService.submit(t2);
try {
finishTestLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("t1.value = %d\n", t1.value);
System.out.printf("t2.value = %d\n", t1.value);
System.out.printf("incrementSynchronize.getValue = %d\n", incrementSynchronize.getValue());
assertEquals(maxCount, t1.value);
assertEquals(maxCount, t2.value);
assertEquals(incrementSynchronize.getValue(), t1.value + t2.value);
}
static class IncrementSynchronize1 implements IncrementSynchronizeA {
private int value = 0;
@Override
synchronized public int getValue() {
return value;
}
@Override
synchronized public int getNextValue() {
return value++;
}
}
@Test
void getNextValueSynchronizedTest1() {
getNextValueSynchronizedTest(new IncrementSynchronize1());
}
static class IncrementSynchronize2 implements IncrementSynchronizeA {
private int value = 0;
private ReadWriteLock readWriteLock;
IncrementSynchronize2(ReadWriteLock readWriteLock) {
this.readWriteLock = readWriteLock;
}
@Override
public int getValue() {
Lock lock = readWriteLock.readLock();
lock.lock();
try {
return value;
} finally {
lock.unlock();
}
}
@Override
public int getNextValue() {
Lock lock = readWriteLock.writeLock();
lock.lock();
try {
return value++;
} finally {
lock.unlock();
}
}
}
@Test
void getNextValueSynchronizedTest2() {
getNextValueSynchronizedTest(new IncrementSynchronize2(new ReentrantReadWriteLock()));
}
static class IncrementSynchronize3 implements IncrementSynchronizeA {
private int value = 0;
private StampedLock readWriteLock;
IncrementSynchronize3(StampedLock readWriteLock) {
this.readWriteLock = readWriteLock;
}
@Override
public int getValue() {
long stamp = readWriteLock.tryOptimisticRead();
int retValue = value;
if (!readWriteLock.validate(stamp)) {
try {
retValue =value;
} finally {
readWriteLock.unlock(stamp);
}
}
return retValue;
}
@Override
public int getNextValue() {
long stamp = readWriteLock.writeLock();
try {
return value++;
} finally {
readWriteLock.unlock(stamp);
}
}
}
@Test
void getNextValueSynchronizedTest3() {
getNextValueSynchronizedTest(new IncrementSynchronize3(new StampedLock()));
}
static class IncrementSynchronize4 implements IncrementSynchronizeA {
private AtomicInteger value = new AtomicInteger(0);
@Override
public int getValue() {
return value.get();
}
@Override
public int getNextValue() {
return value.getAndIncrement();
}
}
@Test
void getNextValueSynchronizedTest4() {
getNextValueSynchronizedTest(new IncrementSynchronize4());
}
} | [
"class",
"GetNextValueSynchronized",
"{",
"private",
"final",
"static",
"int",
"maxCount",
"=",
"10",
";",
"static",
"class",
"GetNextValueRunnable",
"implements",
"Runnable",
"{",
"CountDownLatch",
"finishTestLatch",
";",
"IncrementSynchronizeA",
"incrementSynchronize",
";",
"GetNextValueRunnable",
"(",
"CountDownLatch",
"finishTestLatch",
",",
"IncrementSynchronizeA",
"incrementSynchronize",
")",
"{",
"this",
".",
"finishTestLatch",
"=",
"finishTestLatch",
";",
"this",
".",
"incrementSynchronize",
"=",
"incrementSynchronize",
";",
"}",
"int",
"value",
"=",
"0",
";",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"while",
"(",
"value",
"<",
"maxCount",
")",
"{",
"try",
"{",
"TimeUnit",
".",
"MILLISECONDS",
".",
"sleep",
"(",
"250",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"%s: getNextValue = %d",
"\\n",
"\"",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
",",
"incrementSynchronize",
".",
"getNextValue",
"(",
")",
")",
";",
"value",
"++",
";",
"}",
"finishTestLatch",
".",
"countDown",
"(",
")",
";",
"}",
"}",
"interface",
"IncrementSynchronizeA",
"{",
"int",
"getValue",
"(",
")",
";",
"int",
"getNextValue",
"(",
")",
";",
"}",
"private",
"void",
"getNextValueSynchronizedTest",
"(",
"IncrementSynchronizeA",
"incrementSynchronize",
")",
"{",
"CountDownLatch",
"finishTestLatch",
"=",
"new",
"CountDownLatch",
"(",
"2",
")",
";",
"GetNextValueRunnable",
"t1",
"=",
"new",
"GetNextValueRunnable",
"(",
"finishTestLatch",
",",
"incrementSynchronize",
")",
";",
"GetNextValueRunnable",
"t2",
"=",
"new",
"GetNextValueRunnable",
"(",
"finishTestLatch",
",",
"incrementSynchronize",
")",
";",
"ExecutorService",
"executorService",
"=",
"Executors",
".",
"newFixedThreadPool",
"(",
"2",
")",
";",
"executorService",
".",
"submit",
"(",
"t1",
")",
";",
"executorService",
".",
"submit",
"(",
"t2",
")",
";",
"try",
"{",
"finishTestLatch",
".",
"await",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"t1.value = %d",
"\\n",
"\"",
",",
"t1",
".",
"value",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"t2.value = %d",
"\\n",
"\"",
",",
"t1",
".",
"value",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"incrementSynchronize.getValue = %d",
"\\n",
"\"",
",",
"incrementSynchronize",
".",
"getValue",
"(",
")",
")",
";",
"assertEquals",
"(",
"maxCount",
",",
"t1",
".",
"value",
")",
";",
"assertEquals",
"(",
"maxCount",
",",
"t2",
".",
"value",
")",
";",
"assertEquals",
"(",
"incrementSynchronize",
".",
"getValue",
"(",
")",
",",
"t1",
".",
"value",
"+",
"t2",
".",
"value",
")",
";",
"}",
"static",
"class",
"IncrementSynchronize1",
"implements",
"IncrementSynchronizeA",
"{",
"private",
"int",
"value",
"=",
"0",
";",
"@",
"Override",
"synchronized",
"public",
"int",
"getValue",
"(",
")",
"{",
"return",
"value",
";",
"}",
"@",
"Override",
"synchronized",
"public",
"int",
"getNextValue",
"(",
")",
"{",
"return",
"value",
"++",
";",
"}",
"}",
"@",
"Test",
"void",
"getNextValueSynchronizedTest1",
"(",
")",
"{",
"getNextValueSynchronizedTest",
"(",
"new",
"IncrementSynchronize1",
"(",
")",
")",
";",
"}",
"static",
"class",
"IncrementSynchronize2",
"implements",
"IncrementSynchronizeA",
"{",
"private",
"int",
"value",
"=",
"0",
";",
"private",
"ReadWriteLock",
"readWriteLock",
";",
"IncrementSynchronize2",
"(",
"ReadWriteLock",
"readWriteLock",
")",
"{",
"this",
".",
"readWriteLock",
"=",
"readWriteLock",
";",
"}",
"@",
"Override",
"public",
"int",
"getValue",
"(",
")",
"{",
"Lock",
"lock",
"=",
"readWriteLock",
".",
"readLock",
"(",
")",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"value",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"int",
"getNextValue",
"(",
")",
"{",
"Lock",
"lock",
"=",
"readWriteLock",
".",
"writeLock",
"(",
")",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"value",
"++",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}",
"}",
"@",
"Test",
"void",
"getNextValueSynchronizedTest2",
"(",
")",
"{",
"getNextValueSynchronizedTest",
"(",
"new",
"IncrementSynchronize2",
"(",
"new",
"ReentrantReadWriteLock",
"(",
")",
")",
")",
";",
"}",
"static",
"class",
"IncrementSynchronize3",
"implements",
"IncrementSynchronizeA",
"{",
"private",
"int",
"value",
"=",
"0",
";",
"private",
"StampedLock",
"readWriteLock",
";",
"IncrementSynchronize3",
"(",
"StampedLock",
"readWriteLock",
")",
"{",
"this",
".",
"readWriteLock",
"=",
"readWriteLock",
";",
"}",
"@",
"Override",
"public",
"int",
"getValue",
"(",
")",
"{",
"long",
"stamp",
"=",
"readWriteLock",
".",
"tryOptimisticRead",
"(",
")",
";",
"int",
"retValue",
"=",
"value",
";",
"if",
"(",
"!",
"readWriteLock",
".",
"validate",
"(",
"stamp",
")",
")",
"{",
"try",
"{",
"retValue",
"=",
"value",
";",
"}",
"finally",
"{",
"readWriteLock",
".",
"unlock",
"(",
"stamp",
")",
";",
"}",
"}",
"return",
"retValue",
";",
"}",
"@",
"Override",
"public",
"int",
"getNextValue",
"(",
")",
"{",
"long",
"stamp",
"=",
"readWriteLock",
".",
"writeLock",
"(",
")",
";",
"try",
"{",
"return",
"value",
"++",
";",
"}",
"finally",
"{",
"readWriteLock",
".",
"unlock",
"(",
"stamp",
")",
";",
"}",
"}",
"}",
"@",
"Test",
"void",
"getNextValueSynchronizedTest3",
"(",
")",
"{",
"getNextValueSynchronizedTest",
"(",
"new",
"IncrementSynchronize3",
"(",
"new",
"StampedLock",
"(",
")",
")",
")",
";",
"}",
"static",
"class",
"IncrementSynchronize4",
"implements",
"IncrementSynchronizeA",
"{",
"private",
"AtomicInteger",
"value",
"=",
"new",
"AtomicInteger",
"(",
"0",
")",
";",
"@",
"Override",
"public",
"int",
"getValue",
"(",
")",
"{",
"return",
"value",
".",
"get",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getNextValue",
"(",
")",
"{",
"return",
"value",
".",
"getAndIncrement",
"(",
")",
";",
"}",
"}",
"@",
"Test",
"void",
"getNextValueSynchronizedTest4",
"(",
")",
"{",
"getNextValueSynchronizedTest",
"(",
"new",
"IncrementSynchronize4",
"(",
")",
")",
";",
"}",
"}"
] | Given the following class;
public class IncrementSynchronize {
private int value = 0;
//getNextValue()
}
Write three different method options for getNextValue() that will return 'value++', each method needs to be synchronized in a different way. | [
"Given",
"the",
"following",
"class",
";",
"public",
"class",
"IncrementSynchronize",
"{",
"private",
"int",
"value",
"=",
"0",
";",
"//",
"getNextValue",
"()",
"}",
"Write",
"three",
"different",
"method",
"options",
"for",
"getNextValue",
"()",
"that",
"will",
"return",
"'",
"value",
"++",
"'",
"each",
"method",
"needs",
"to",
"be",
"synchronized",
"in",
"a",
"different",
"way",
"."
] | [
"// Leverage sleep, to run threads more parallel.",
"// new Thread(t1).start();",
"// new Thread(t2).start();",
"// Or"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd2714cae75e439b24e16c148a29d2bc6c6dfd79 | greatji/Dima | sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/KryoShapeSerializer.java | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | Java | KryoShapeSerializer | /**
* Created by dong on 3/24/16.
*/ | Created by dong on 3/24/16. | [
"Created",
"by",
"dong",
"on",
"3",
"/",
"24",
"/",
"16",
"."
] | public class KryoShapeSerializer {
static private Kryo kryo = new Kryo();
static {
kryo.register(Shape.class);
kryo.register(Point.class);
kryo.register(MBR.class);
kryo.register(Polygon.class);
kryo.register(Circle.class);
}
public static Shape deserialize(byte[] data) {
ByteArrayInputStream in = new ByteArrayInputStream(data);
Input input = new Input(in);
return kryo.readObject(input, Shape.class);
}
public static byte[] serialize(Shape o) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Output output = new Output(out);
kryo.writeObject(output, o);
output.flush();
return out.toByteArray();
}
} | [
"public",
"class",
"KryoShapeSerializer",
"{",
"static",
"private",
"Kryo",
"kryo",
"=",
"new",
"Kryo",
"(",
")",
";",
"static",
"{",
"kryo",
".",
"register",
"(",
"Shape",
".",
"class",
")",
";",
"kryo",
".",
"register",
"(",
"Point",
".",
"class",
")",
";",
"kryo",
".",
"register",
"(",
"MBR",
".",
"class",
")",
";",
"kryo",
".",
"register",
"(",
"Polygon",
".",
"class",
")",
";",
"kryo",
".",
"register",
"(",
"Circle",
".",
"class",
")",
";",
"}",
"public",
"static",
"Shape",
"deserialize",
"(",
"byte",
"[",
"]",
"data",
")",
"{",
"ByteArrayInputStream",
"in",
"=",
"new",
"ByteArrayInputStream",
"(",
"data",
")",
";",
"Input",
"input",
"=",
"new",
"Input",
"(",
"in",
")",
";",
"return",
"kryo",
".",
"readObject",
"(",
"input",
",",
"Shape",
".",
"class",
")",
";",
"}",
"public",
"static",
"byte",
"[",
"]",
"serialize",
"(",
"Shape",
"o",
")",
"{",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"Output",
"output",
"=",
"new",
"Output",
"(",
"out",
")",
";",
"kryo",
".",
"writeObject",
"(",
"output",
",",
"o",
")",
";",
"output",
".",
"flush",
"(",
")",
";",
"return",
"out",
".",
"toByteArray",
"(",
")",
";",
"}",
"}"
] | Created by dong on 3/24/16. | [
"Created",
"by",
"dong",
"on",
"3",
"/",
"24",
"/",
"16",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd292e2a0089454763148fe5f3b2323b11d9dcff | esavin/annotate4j-classfile | src/main/java/annotate4j/classfile/structure/annotation/AnnotationValue.java | [
"Apache-2.0"
] | Java | AnnotationValue | /**
* @author Eugene Savin
*/ | @author Eugene Savin | [
"@author",
"Eugene",
"Savin"
] | public class AnnotationValue extends ElementValue {
@FieldOrder(index = 2)
private Annotation annotationValue;
public Annotation getAnnotationValue() {
return annotationValue;
}
public void setAnnotationValue(Annotation annotationValue) {
this.annotationValue = annotationValue;
}
} | [
"public",
"class",
"AnnotationValue",
"extends",
"ElementValue",
"{",
"@",
"FieldOrder",
"(",
"index",
"=",
"2",
")",
"private",
"Annotation",
"annotationValue",
";",
"public",
"Annotation",
"getAnnotationValue",
"(",
")",
"{",
"return",
"annotationValue",
";",
"}",
"public",
"void",
"setAnnotationValue",
"(",
"Annotation",
"annotationValue",
")",
"{",
"this",
".",
"annotationValue",
"=",
"annotationValue",
";",
"}",
"}"
] | @author Eugene Savin | [
"@author",
"Eugene",
"Savin"
] | [] | [
{
"param": "ElementValue",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ElementValue",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd2bf1388c77af7d2d12d44d8a03d1e74a4b6bf1 | NekoHitDev/Ritmin | src/test/java/com/nekohit/neo/contract/WCARefundTest.java | [
"Apache-2.0"
] | Java | WCARefundTest | /**
* This class test the refund method for WCA.
* Including invalid id, invalid signer, unpaid, last ms is finished, last ms expired.
* record not found, normal op(before and after threshold)
*/ | This class test the refund method for WCA.
Including invalid id, invalid signer, unpaid, last ms is finished, last ms expired.
record not found, normal op(before and after threshold) | [
"This",
"class",
"test",
"the",
"refund",
"method",
"for",
"WCA",
".",
"Including",
"invalid",
"id",
"invalid",
"signer",
"unpaid",
"last",
"ms",
"is",
"finished",
"last",
"ms",
"expired",
".",
"record",
"not",
"found",
"normal",
"op",
"(",
"before",
"and",
"after",
"threshold",
")"
] | @ContractTest(blockTime = 1, contracts = {
CatToken.class,
WCAContract.class,
})
public class WCARefundTest extends ContractTestFramework {
private Account creatorAccount;
private Account testAccount;
@BeforeEach
void setUp() {
creatorAccount = getTestAccount();
testAccount = getTestAccount();
}
@Test
void testInvalidId() {
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
"some_invalid_id",
this.creatorAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.RECORD_NOT_FOUND),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testInvalidSigner() {
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractTestFramework.invokeFunction(
getWcaContract(), "refund",
new ContractParameter[]{
ContractParameter.string("identifier"),
ContractParameter.hash160(Account.create())
},
new Signer[]{
AccountSigner.calledByEntry(this.creatorAccount)
}
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.INVALID_SIGNATURE),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testRefundUnpaid() throws Throwable {
var identifier = ContractInvokeHelper.declareProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1_00,
new String[]{"milestone"},
new String[]{"milestone"},
new Long[]{System.currentTimeMillis() + 60 * 1000},
0, 100, false,
"test_refund_unpaid_" + System.currentTimeMillis(),
this.creatorAccount
);
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.creatorAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.INVALID_STATUS_ALLOW_ONGOING),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testLastMilestoneFinished() throws Throwable {
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1_00,
new String[]{"milestone1"},
new String[]{"milestone1"},
new Long[]{System.currentTimeMillis() + 60 * 1000},
0, 100, false,
"test_refund_last_ms_finished_" + System.currentTimeMillis(),
this.creatorAccount
);
ContractInvokeHelper.finishMilestone(
getWcaContract(), identifier, 0, "proofOfWork", this.creatorAccount
);
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.creatorAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.INVALID_STATUS_ALLOW_ONGOING),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testLastMilestoneExpired() throws Throwable {
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1_00,
new String[]{"milestone1"},
new String[]{"milestone1"},
new Long[]{System.currentTimeMillis() + 2 * 1000},
0, 100, false,
"test_refund_last_ms_expired_" + System.currentTimeMillis(),
this.creatorAccount
);
Thread.sleep(3 * 1000);
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.creatorAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.INVALID_STAGE_READY_TO_FINISH),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testRecordNotFoundBeforeThreshold() throws Throwable {
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1_00,
new String[]{"milestone1"},
new String[]{"milestone1"},
new Long[]{System.currentTimeMillis() + 60 * 1000},
0, 100, false,
"test_record_404_before_thrshd_" + System.currentTimeMillis(),
this.creatorAccount
);
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.testAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.RECORD_NOT_FOUND),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testRecordNotFoundAfterThreshold() throws Throwable {
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1_00,
new String[]{"milestone1", "milestone2"},
new String[]{"milestone1", "milestone2"},
new Long[]{System.currentTimeMillis() + 60 * 1000, System.currentTimeMillis() + 61 * 1000},
0, 100, false,
"test_record_404_after_thrshd_" + System.currentTimeMillis(),
this.creatorAccount
);
ContractInvokeHelper.finishMilestone(
getWcaContract(), identifier, 0, "proofOfWork", this.creatorAccount
);
var throwable = assertThrows(
TransactionConfigurationException.class,
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.testAccount
)
);
assertTrue(
throwable.getMessage().contains(ExceptionMessages.RECORD_NOT_FOUND),
"Unknown exception: " + throwable.getMessage()
);
}
@Test
void testNormalRefundBeforeThreshold() throws Throwable {
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), 1_00, 1000_00,
new String[]{"milestone1", "milestone2"},
new String[]{"milestone1", "milestone2"},
new Long[]{System.currentTimeMillis() + 60 * 1000, System.currentTimeMillis() + 61 * 1000},
0, 100, false,
"test_normal_refund_before_threshold_" + System.currentTimeMillis(),
this.creatorAccount
);
var oldBalance = getCatToken().getBalanceOf(this.testAccount).longValue();
// purchase
transferToken(
getCatToken(), this.testAccount, getWcaContractAddress(),
1000_00, identifier, true
);
assertDoesNotThrow(
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.testAccount
)
);
var newBalance = getCatToken().getBalanceOf(this.testAccount).longValue();
assertEquals(oldBalance, newBalance);
}
@Test
void testNormalRefundAfterThreshold() throws Throwable {
var stakeRate = 1_00;
var identifier = ContractInvokeHelper.createAndPayProject(
// stake: 1.00 * 1.00
getWcaContract(), "description",
getCatTokenAddress(), stakeRate, 1000_00,
new String[]{"milestone1", "milestone2"},
new String[]{"milestone1", "milestone2"},
new Long[]{System.currentTimeMillis() + 60 * 1000, System.currentTimeMillis() + 61 * 1000},
0, 100, false,
"test_normal_refund_after_threshold_" + System.currentTimeMillis(),
this.creatorAccount
);
var purchaseAmount = 1000_00;
var oldBuyerBalance = getCatToken().getBalanceOf(this.testAccount).longValue();
var oldCreatorBalance = getCatToken().getBalanceOf(this.creatorAccount).longValue();
// purchase
transferToken(
getCatToken(), this.testAccount, getWcaContractAddress(),
purchaseAmount, identifier, true
);
ContractInvokeHelper.finishMilestone(
getWcaContract(), identifier, 0, "proofOfWork", this.creatorAccount
);
assertDoesNotThrow(
() -> ContractInvokeHelper.refund(
getWcaContract(),
identifier,
this.testAccount
)
);
var newBuyerBalance = getCatToken().getBalanceOf(this.testAccount).longValue();
var newCreatorBalance = getCatToken().getBalanceOf(this.creatorAccount).longValue();
assertEquals(oldBuyerBalance - purchaseAmount / 2, newBuyerBalance);
assertEquals(oldCreatorBalance + purchaseAmount * stakeRate / 100 / 2, newCreatorBalance);
}
} | [
"@",
"ContractTest",
"(",
"blockTime",
"=",
"1",
",",
"contracts",
"=",
"{",
"CatToken",
".",
"class",
",",
"WCAContract",
".",
"class",
",",
"}",
")",
"public",
"class",
"WCARefundTest",
"extends",
"ContractTestFramework",
"{",
"private",
"Account",
"creatorAccount",
";",
"private",
"Account",
"testAccount",
";",
"@",
"BeforeEach",
"void",
"setUp",
"(",
")",
"{",
"creatorAccount",
"=",
"getTestAccount",
"(",
")",
";",
"testAccount",
"=",
"getTestAccount",
"(",
")",
";",
"}",
"@",
"Test",
"void",
"testInvalidId",
"(",
")",
"{",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"some_invalid_id",
"\"",
",",
"this",
".",
"creatorAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"RECORD_NOT_FOUND",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testInvalidSigner",
"(",
")",
"{",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractTestFramework",
".",
"invokeFunction",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"refund",
"\"",
",",
"new",
"ContractParameter",
"[",
"]",
"{",
"ContractParameter",
".",
"string",
"(",
"\"",
"identifier",
"\"",
")",
",",
"ContractParameter",
".",
"hash160",
"(",
"Account",
".",
"create",
"(",
")",
")",
"}",
",",
"new",
"Signer",
"[",
"]",
"{",
"AccountSigner",
".",
"calledByEntry",
"(",
"this",
".",
"creatorAccount",
")",
"}",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"INVALID_SIGNATURE",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testRefundUnpaid",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"declareProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_refund_unpaid_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"creatorAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"INVALID_STATUS_ALLOW_ONGOING",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testLastMilestoneFinished",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_refund_last_ms_finished_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"ContractInvokeHelper",
".",
"finishMilestone",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"0",
",",
"\"",
"proofOfWork",
"\"",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"creatorAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"INVALID_STATUS_ALLOW_ONGOING",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testLastMilestoneExpired",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"2",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_refund_last_ms_expired_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"Thread",
".",
"sleep",
"(",
"3",
"*",
"1000",
")",
";",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"creatorAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"INVALID_STAGE_READY_TO_FINISH",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testRecordNotFoundBeforeThreshold",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_record_404_before_thrshd_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"testAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"RECORD_NOT_FOUND",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testRecordNotFoundAfterThreshold",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"61",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_record_404_after_thrshd_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"ContractInvokeHelper",
".",
"finishMilestone",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"0",
",",
"\"",
"proofOfWork",
"\"",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"throwable",
"=",
"assertThrows",
"(",
"TransactionConfigurationException",
".",
"class",
",",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"testAccount",
")",
")",
";",
"assertTrue",
"(",
"throwable",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"ExceptionMessages",
".",
"RECORD_NOT_FOUND",
")",
",",
"\"",
"Unknown exception: ",
"\"",
"+",
"throwable",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"@",
"Test",
"void",
"testNormalRefundBeforeThreshold",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"1_00",
",",
"1000_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"61",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_normal_refund_before_threshold_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"oldBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"testAccount",
")",
".",
"longValue",
"(",
")",
";",
"transferToken",
"(",
"getCatToken",
"(",
")",
",",
"this",
".",
"testAccount",
",",
"getWcaContractAddress",
"(",
")",
",",
"1000_00",
",",
"identifier",
",",
"true",
")",
";",
"assertDoesNotThrow",
"(",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"testAccount",
")",
")",
";",
"var",
"newBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"testAccount",
")",
".",
"longValue",
"(",
")",
";",
"assertEquals",
"(",
"oldBalance",
",",
"newBalance",
")",
";",
"}",
"@",
"Test",
"void",
"testNormalRefundAfterThreshold",
"(",
")",
"throws",
"Throwable",
"{",
"var",
"stakeRate",
"=",
"1_00",
";",
"var",
"identifier",
"=",
"ContractInvokeHelper",
".",
"createAndPayProject",
"(",
"getWcaContract",
"(",
")",
",",
"\"",
"description",
"\"",
",",
"getCatTokenAddress",
"(",
")",
",",
"stakeRate",
",",
"1000_00",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"\"",
"milestone1",
"\"",
",",
"\"",
"milestone2",
"\"",
"}",
",",
"new",
"Long",
"[",
"]",
"{",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"60",
"*",
"1000",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"61",
"*",
"1000",
"}",
",",
"0",
",",
"100",
",",
"false",
",",
"\"",
"test_normal_refund_after_threshold_",
"\"",
"+",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"this",
".",
"creatorAccount",
")",
";",
"var",
"purchaseAmount",
"=",
"1000_00",
";",
"var",
"oldBuyerBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"testAccount",
")",
".",
"longValue",
"(",
")",
";",
"var",
"oldCreatorBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"creatorAccount",
")",
".",
"longValue",
"(",
")",
";",
"transferToken",
"(",
"getCatToken",
"(",
")",
",",
"this",
".",
"testAccount",
",",
"getWcaContractAddress",
"(",
")",
",",
"purchaseAmount",
",",
"identifier",
",",
"true",
")",
";",
"ContractInvokeHelper",
".",
"finishMilestone",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"0",
",",
"\"",
"proofOfWork",
"\"",
",",
"this",
".",
"creatorAccount",
")",
";",
"assertDoesNotThrow",
"(",
"(",
")",
"->",
"ContractInvokeHelper",
".",
"refund",
"(",
"getWcaContract",
"(",
")",
",",
"identifier",
",",
"this",
".",
"testAccount",
")",
")",
";",
"var",
"newBuyerBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"testAccount",
")",
".",
"longValue",
"(",
")",
";",
"var",
"newCreatorBalance",
"=",
"getCatToken",
"(",
")",
".",
"getBalanceOf",
"(",
"this",
".",
"creatorAccount",
")",
".",
"longValue",
"(",
")",
";",
"assertEquals",
"(",
"oldBuyerBalance",
"-",
"purchaseAmount",
"/",
"2",
",",
"newBuyerBalance",
")",
";",
"assertEquals",
"(",
"oldCreatorBalance",
"+",
"purchaseAmount",
"*",
"stakeRate",
"/",
"100",
"/",
"2",
",",
"newCreatorBalance",
")",
";",
"}",
"}"
] | This class test the refund method for WCA. | [
"This",
"class",
"test",
"the",
"refund",
"method",
"for",
"WCA",
"."
] | [
"// stake: 1.00 * 1.00",
"// stake: 1.00 * 1.00",
"// stake: 1.00 * 1.00",
"// stake: 1.00 * 1.00",
"// stake: 1.00 * 1.00",
"// stake: 1.00 * 1.00",
"// purchase",
"// stake: 1.00 * 1.00",
"// purchase"
] | [
{
"param": "ContractTestFramework",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ContractTestFramework",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd2c360eb5fd2deaa3c4ac1b6ec893da688a1df0 | lwinmoethu25/mClinicPlus-58d957d7494 | MHealthPlus/src/com/lucentinsight/mclinicplus/fragment/DoctorListFragment.java | [
"Apache-2.0"
] | Java | DoctorListFragment | /**
* A simple {@link Fragment} subclass.
* Use the {@link DoctorListFragment#newInstance} factory method to
* create an instance of this fragment.
*/ | A simple Fragment subclass.
Use the DoctorListFragment#newInstance factory method to
create an instance of this fragment. | [
"A",
"simple",
"Fragment",
"subclass",
".",
"Use",
"the",
"DoctorListFragment#newInstance",
"factory",
"method",
"to",
"create",
"an",
"instance",
"of",
"this",
"fragment",
"."
] | public class DoctorListFragment extends Fragment implements AdapterView.OnItemClickListener{
private List<Doctor> doctors;
@InjectView(R.id.listView)
ListView listView;
DoctorListAdapter adapter;
public DoctorListAdapter getAdapter() {
return adapter;
}
@Override
public void onStart() {
super.onStart();
((MainActivity)getActivity()).setDoctorListFragment(this);
}
@Override
public void onStop() {
super.onStop();
((MainActivity)getActivity()).removeDoctorListFragment();
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment DoctorListFragment.
*/
public static DoctorListFragment newInstance() {
DoctorListFragment fragment = new DoctorListFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public DoctorListFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
DBHelper dbHelper = DBHelper.getInstance(getActivity());
doctors = dbHelper.getDoctorList(null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_doctor_list, container, false);
ButterKnife.inject(this, view);
adapter = new DoctorListAdapter(getActivity(), doctors);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return view;
}
public void filter(String text){
adapter.getFilter().filter(text);
adapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Doctor doctor = adapter.getItem(position);
Intent intent = new Intent(getActivity(), DoctorDetailActivity.class);
intent.putExtra(DoctorDetailActivity.DOCTOR, doctor);
startActivity(intent);
}
} | [
"public",
"class",
"DoctorListFragment",
"extends",
"Fragment",
"implements",
"AdapterView",
".",
"OnItemClickListener",
"{",
"private",
"List",
"<",
"Doctor",
">",
"doctors",
";",
"@",
"InjectView",
"(",
"R",
".",
"id",
".",
"listView",
")",
"ListView",
"listView",
";",
"DoctorListAdapter",
"adapter",
";",
"public",
"DoctorListAdapter",
"getAdapter",
"(",
")",
"{",
"return",
"adapter",
";",
"}",
"@",
"Override",
"public",
"void",
"onStart",
"(",
")",
"{",
"super",
".",
"onStart",
"(",
")",
";",
"(",
"(",
"MainActivity",
")",
"getActivity",
"(",
")",
")",
".",
"setDoctorListFragment",
"(",
"this",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onStop",
"(",
")",
"{",
"super",
".",
"onStop",
"(",
")",
";",
"(",
"(",
"MainActivity",
")",
"getActivity",
"(",
")",
")",
".",
"removeDoctorListFragment",
"(",
")",
";",
"}",
"/**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @return A new instance of fragment DoctorListFragment.\n */",
"public",
"static",
"DoctorListFragment",
"newInstance",
"(",
")",
"{",
"DoctorListFragment",
"fragment",
"=",
"new",
"DoctorListFragment",
"(",
")",
";",
"Bundle",
"args",
"=",
"new",
"Bundle",
"(",
")",
";",
"fragment",
".",
"setArguments",
"(",
"args",
")",
";",
"return",
"fragment",
";",
"}",
"public",
"DoctorListFragment",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onCreate",
"(",
"Bundle",
"savedInstanceState",
")",
"{",
"super",
".",
"onCreate",
"(",
"savedInstanceState",
")",
";",
"if",
"(",
"getArguments",
"(",
")",
"!=",
"null",
")",
"{",
"}",
"DBHelper",
"dbHelper",
"=",
"DBHelper",
".",
"getInstance",
"(",
"getActivity",
"(",
")",
")",
";",
"doctors",
"=",
"dbHelper",
".",
"getDoctorList",
"(",
"null",
")",
";",
"}",
"@",
"Override",
"public",
"View",
"onCreateView",
"(",
"LayoutInflater",
"inflater",
",",
"ViewGroup",
"container",
",",
"Bundle",
"savedInstanceState",
")",
"{",
"View",
"view",
"=",
"inflater",
".",
"inflate",
"(",
"R",
".",
"layout",
".",
"fragment_doctor_list",
",",
"container",
",",
"false",
")",
";",
"ButterKnife",
".",
"inject",
"(",
"this",
",",
"view",
")",
";",
"adapter",
"=",
"new",
"DoctorListAdapter",
"(",
"getActivity",
"(",
")",
",",
"doctors",
")",
";",
"listView",
".",
"setAdapter",
"(",
"adapter",
")",
";",
"listView",
".",
"setOnItemClickListener",
"(",
"this",
")",
";",
"return",
"view",
";",
"}",
"public",
"void",
"filter",
"(",
"String",
"text",
")",
"{",
"adapter",
".",
"getFilter",
"(",
")",
".",
"filter",
"(",
"text",
")",
";",
"adapter",
".",
"notifyDataSetChanged",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onItemClick",
"(",
"AdapterView",
"<",
"?",
">",
"parent",
",",
"View",
"view",
",",
"int",
"position",
",",
"long",
"id",
")",
"{",
"Doctor",
"doctor",
"=",
"adapter",
".",
"getItem",
"(",
"position",
")",
";",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"getActivity",
"(",
")",
",",
"DoctorDetailActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"DoctorDetailActivity",
".",
"DOCTOR",
",",
"doctor",
")",
";",
"startActivity",
"(",
"intent",
")",
";",
"}",
"}"
] | A simple {@link Fragment} subclass. | [
"A",
"simple",
"{",
"@link",
"Fragment",
"}",
"subclass",
"."
] | [
"// Required empty public constructor",
"// Inflate the layout for this fragment"
] | [
{
"param": "Fragment",
"type": null
},
{
"param": "AdapterView.OnItemClickListener",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Fragment",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "AdapterView.OnItemClickListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd2f59feeee5ea515afb81d686f9bd996f9924bf | yazad3/atlas | src/main/java/org/openstreetmap/atlas/geography/atlas/change/description/ChangeDescriptorGenerator.java | [
"BSD-3-Clause"
] | Java | ChangeDescriptorGenerator | /**
* A helper class for generating a list of {@link ChangeDescriptor}s based on some
* {@link AtlasEntity} beforeView and afterView.
*
* @author lcram
*/ | A helper class for generating a list of ChangeDescriptors based on some
AtlasEntity beforeView and afterView.
@author lcram | [
"A",
"helper",
"class",
"for",
"generating",
"a",
"list",
"of",
"ChangeDescriptors",
"based",
"on",
"some",
"AtlasEntity",
"beforeView",
"and",
"afterView",
".",
"@author",
"lcram"
] | public final class ChangeDescriptorGenerator
{
private static final ChangeDescriptorComparator COMPARATOR = new ChangeDescriptorComparator();
private static final String CORRUPTED_FEATURECHANGE_MESSAGE = "Corrupted FeatureChange: afterView {} != null but beforeView {} == null";
private final AtlasEntity beforeView;
private final AtlasEntity afterView;
private final ChangeDescriptorType changeDescriptorType;
ChangeDescriptorGenerator(final AtlasEntity beforeView, final AtlasEntity afterView,
final ChangeDescriptorType changeDescriptorType)
{
this.beforeView = beforeView;
this.afterView = afterView;
this.changeDescriptorType = changeDescriptorType;
}
List<ChangeDescriptor> generate()
{
final List<ChangeDescriptor> descriptors = new ArrayList<>();
/*
* For the REMOVE case, there's no point showing any details. Users can just look at the
* FeatureChange output itself to see the beforeView and afterView.
*/
if (this.changeDescriptorType == ChangeDescriptorType.REMOVE)
{
return descriptors;
}
descriptors.addAll(generateTagDescriptors());
descriptors.addAll(generateGeometryDescriptors());
descriptors.addAll(generateParentRelationDescriptors(CompleteEntity::relationIdentifiers));
if (this.afterView.getType() == ItemType.NODE)
{
descriptors.addAll(generateNodeInOutDescriptors(ChangeDescriptorName.IN_EDGE,
CompleteNode::inEdgeIdentifiers));
descriptors.addAll(generateNodeInOutDescriptors(ChangeDescriptorName.OUT_EDGE,
CompleteNode::outEdgeIdentifiers));
}
if (this.afterView.getType() == ItemType.EDGE)
{
descriptors.addAll(generateEdgeStartEndDescriptors(ChangeDescriptorName.START_NODE,
CompleteEdge::startNodeIdentifier));
descriptors.addAll(generateEdgeStartEndDescriptors(ChangeDescriptorName.END_NODE,
CompleteEdge::endNodeIdentifier));
}
if (this.afterView.getType() == ItemType.RELATION)
{
descriptors.addAll(generateRelationMemberDescriptors());
/*
* Should we handle the other special relation fields here?
* allRelationsWithSameOsmIdentifier, allKnownOsmMembers, and osmRelationIdentifier are
* fields that may be altered.
*/
}
descriptors.sort(COMPARATOR);
return descriptors;
}
ChangeDescriptorType getChangeDescriptorType()
{
return this.changeDescriptorType;
}
private List<LongElementChangeDescriptor> generateEdgeStartEndDescriptors(
final ChangeDescriptorName name, final Function<CompleteEdge, Long> memberExtractor) // NOSONAR
{
final CompleteEdge beforeEntity = (CompleteEdge) this.beforeView;
final CompleteEdge afterEntity = (CompleteEdge) this.afterView;
/*
* If the afterView identifier was null, then we know that it was not updated. We can just
* return nothing.
*/
if (memberExtractor.apply(afterEntity) == null)
{
return new ArrayList<>();
}
final Long beforeIdentifier;
if (beforeEntity != null)
{
if (memberExtractor.apply(beforeEntity) == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, name, name);
}
beforeIdentifier = memberExtractor.apply(beforeEntity);
}
else
{
beforeIdentifier = null;
}
final Long afterIdentifier = memberExtractor.apply(afterEntity);
return generateLongValueDescriptors(name, beforeIdentifier, afterIdentifier);
}
private List<ChangeDescriptor> generateGeometryDescriptors()
{
final List<ChangeDescriptor> descriptors = new ArrayList<>();
/*
* Relations do not have explicit geometry, so return nothing.
*/
if (this.afterView.getType() == ItemType.RELATION)
{
return descriptors;
}
final CompleteEntity<? extends CompleteEntity<?>> beforeEntity = (CompleteEntity<? extends CompleteEntity<?>>) this.beforeView;
final CompleteEntity<? extends CompleteEntity<?>> afterEntity = (CompleteEntity<? extends CompleteEntity<?>>) this.afterView;
/*
* If the afterView geometry is null, then we know the geometry was not updated.
*/
if (afterEntity.getGeometry() == null)
{
return descriptors;
}
final List<Location> beforeGeometry = new ArrayList<>();
final List<Location> afterGeometry = new ArrayList<>();
afterEntity.getGeometry().forEach(afterGeometry::add);
if (beforeEntity != null)
{
if (beforeEntity.getGeometry() == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, "geometry", "geometry");
}
beforeEntity.getGeometry().forEach(beforeGeometry::add);
}
descriptors.addAll(
GeometryChangeDescriptor.getDescriptorsForGeometry(beforeGeometry, afterGeometry));
return descriptors;
}
private List<LongElementChangeDescriptor> generateLongSetDescriptors(
final ChangeDescriptorName name, final Set<Long> beforeSet, final Set<Long> afterSet)
{
final List<LongElementChangeDescriptor> descriptors = new ArrayList<>();
final Set<Long> removedFromAfterView = com.google.common.collect.Sets.difference(beforeSet,
afterSet);
final Set<Long> addedToAfterView = com.google.common.collect.Sets.difference(afterSet,
beforeSet);
for (final Long identifier : removedFromAfterView)
{
descriptors.add(new LongElementChangeDescriptor(ChangeDescriptorType.REMOVE, identifier,
null, name));
}
for (final Long identifier : addedToAfterView)
{
descriptors.add(
new LongElementChangeDescriptor(ChangeDescriptorType.ADD, identifier, name));
}
return descriptors;
}
private List<LongElementChangeDescriptor> generateLongValueDescriptors(
final ChangeDescriptorName name, final Long beforeIdentifier,
final Long afterIdentifier)
{
final List<LongElementChangeDescriptor> descriptors = new ArrayList<>();
/*
* This case occurs when an brand new Long value (e.g. startNode, endNode, etc.) is being
* added, and so there is no beforeElement.
*/
if (beforeIdentifier == null)
{
descriptors.add(new LongElementChangeDescriptor(ChangeDescriptorType.ADD, null,
afterIdentifier, name));
}
else
{
descriptors.add(new LongElementChangeDescriptor(ChangeDescriptorType.UPDATE,
beforeIdentifier, afterIdentifier, name));
}
return descriptors;
}
private List<LongElementChangeDescriptor> generateNodeInOutDescriptors(
final ChangeDescriptorName name,
final Function<CompleteNode, Set<Long>> memberExtractor)
{
final CompleteNode beforeEntity = (CompleteNode) this.beforeView;
final CompleteNode afterEntity = (CompleteNode) this.afterView;
/*
* If the afterView in/out edge set was null, then we know that it was not updated. We can
* just return nothing.
*/
if (memberExtractor.apply(afterEntity) == null)
{
return new ArrayList<>();
}
final Set<Long> beforeSet;
if (beforeEntity != null)
{
if (memberExtractor.apply(beforeEntity) == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, name, name);
}
beforeSet = memberExtractor.apply(beforeEntity);
}
else
{
beforeSet = new HashSet<>();
}
final Set<Long> afterSet = memberExtractor.apply(afterEntity);
return generateLongSetDescriptors(name, beforeSet, afterSet);
}
private List<LongElementChangeDescriptor> generateParentRelationDescriptors(
final Function<CompleteEntity, Set<Long>> memberExtractor)
{
final ChangeDescriptorName name = ChangeDescriptorName.PARENT_RELATION;
final CompleteEntity<? extends CompleteEntity<?>> beforeEntity = (CompleteEntity<? extends CompleteEntity<?>>) this.beforeView;
final CompleteEntity<? extends CompleteEntity<?>> afterEntity = (CompleteEntity<? extends CompleteEntity<?>>) this.afterView;
/*
* If the afterView parent relations were null, then we know that they were not updated. We
* can just return nothing.
*/
if (memberExtractor.apply(afterEntity) == null)
{
return new ArrayList<>();
}
final Set<Long> beforeSet;
if (beforeEntity != null)
{
if (memberExtractor.apply(beforeEntity) == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, name, name);
}
beforeSet = memberExtractor.apply(beforeEntity);
}
else
{
beforeSet = new HashSet<>();
}
final Set<Long> afterSet = memberExtractor.apply(afterEntity);
return generateLongSetDescriptors(name, beforeSet, afterSet);
}
private List<ChangeDescriptor> generateRelationMemberDescriptors()
{
final List<ChangeDescriptor> descriptors = new ArrayList<>();
final CompleteRelation beforeEntity = (CompleteRelation) this.beforeView;
final CompleteRelation afterEntity = (CompleteRelation) this.afterView;
/*
* If the afterView members were null, then we know that the members were not updated. We
* can just return nothing.
*/
if (afterEntity.members() == null)
{
return descriptors;
}
final Set<RelationBean.RelationBeanItem> beforeBeanSet;
if (beforeEntity != null)
{
if (beforeEntity.members() == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, "relation members",
"relation members");
}
beforeBeanSet = beforeEntity.members().asBean().asSet();
}
else
{
beforeBeanSet = new HashSet<>();
}
final Set<RelationBean.RelationBeanItem> afterBeanSet = afterEntity.members().asBean()
.asSet();
final Set<RelationBean.RelationBeanItem> itemsRemovedFromAfterView = com.google.common.collect.Sets
.difference(beforeBeanSet, afterBeanSet);
final Set<RelationBean.RelationBeanItem> itemsAddedToAfterView = com.google.common.collect.Sets
.difference(afterBeanSet, beforeBeanSet);
for (final RelationBean.RelationBeanItem item : itemsRemovedFromAfterView)
{
descriptors.add(new RelationMemberChangeDescriptor(ChangeDescriptorType.REMOVE,
item.getIdentifier(), item.getType(), item.getRole()));
}
for (final RelationBean.RelationBeanItem item : itemsAddedToAfterView)
{
descriptors.add(new RelationMemberChangeDescriptor(ChangeDescriptorType.ADD,
item.getIdentifier(), item.getType(), item.getRole()));
}
return descriptors;
}
private List<ChangeDescriptor> generateTagDescriptors()
{
final List<ChangeDescriptor> descriptors = new ArrayList<>();
/*
* If the afterView tags were null, then we know that the tags were not updated. We can just
* return nothing.
*/
if (this.afterView.getTags() == null)
{
return descriptors;
}
final Map<String, String> beforeTags;
if (this.beforeView != null)
{
if (this.beforeView.getTags() == null)
{
throw new CoreException(CORRUPTED_FEATURECHANGE_MESSAGE, "tags", "tags");
}
beforeTags = this.beforeView.getTags();
}
else
{
beforeTags = new HashMap<>();
}
final Map<String, String> afterTags = this.afterView.getTags();
final Set<String> keysRemovedFromAfterView = com.google.common.collect.Sets
.difference(beforeTags.keySet(), afterTags.keySet());
final Set<String> keysAddedToAfterView = com.google.common.collect.Sets
.difference(afterTags.keySet(), beforeTags.keySet());
final Set<String> keysShared = com.google.common.collect.Sets
.intersection(beforeTags.keySet(), afterTags.keySet());
for (final String key : keysRemovedFromAfterView)
{
descriptors.add(
new TagChangeDescriptor(ChangeDescriptorType.REMOVE, key, beforeTags.get(key)));
}
for (final String key : keysAddedToAfterView)
{
descriptors.add(
new TagChangeDescriptor(ChangeDescriptorType.ADD, key, afterTags.get(key)));
}
for (final String key : keysShared)
{
if (!beforeTags.get(key).equals(afterTags.get(key)))
{
descriptors.add(new TagChangeDescriptor(ChangeDescriptorType.UPDATE, key,
afterTags.get(key), beforeTags.get(key)));
}
}
return descriptors;
}
} | [
"public",
"final",
"class",
"ChangeDescriptorGenerator",
"{",
"private",
"static",
"final",
"ChangeDescriptorComparator",
"COMPARATOR",
"=",
"new",
"ChangeDescriptorComparator",
"(",
")",
";",
"private",
"static",
"final",
"String",
"CORRUPTED_FEATURECHANGE_MESSAGE",
"=",
"\"",
"Corrupted FeatureChange: afterView {} != null but beforeView {} == null",
"\"",
";",
"private",
"final",
"AtlasEntity",
"beforeView",
";",
"private",
"final",
"AtlasEntity",
"afterView",
";",
"private",
"final",
"ChangeDescriptorType",
"changeDescriptorType",
";",
"ChangeDescriptorGenerator",
"(",
"final",
"AtlasEntity",
"beforeView",
",",
"final",
"AtlasEntity",
"afterView",
",",
"final",
"ChangeDescriptorType",
"changeDescriptorType",
")",
"{",
"this",
".",
"beforeView",
"=",
"beforeView",
";",
"this",
".",
"afterView",
"=",
"afterView",
";",
"this",
".",
"changeDescriptorType",
"=",
"changeDescriptorType",
";",
"}",
"List",
"<",
"ChangeDescriptor",
">",
"generate",
"(",
")",
"{",
"final",
"List",
"<",
"ChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"/*\n * For the REMOVE case, there's no point showing any details. Users can just look at the\n * FeatureChange output itself to see the beforeView and afterView.\n */",
"if",
"(",
"this",
".",
"changeDescriptorType",
"==",
"ChangeDescriptorType",
".",
"REMOVE",
")",
"{",
"return",
"descriptors",
";",
"}",
"descriptors",
".",
"addAll",
"(",
"generateTagDescriptors",
"(",
")",
")",
";",
"descriptors",
".",
"addAll",
"(",
"generateGeometryDescriptors",
"(",
")",
")",
";",
"descriptors",
".",
"addAll",
"(",
"generateParentRelationDescriptors",
"(",
"CompleteEntity",
"::",
"relationIdentifiers",
")",
")",
";",
"if",
"(",
"this",
".",
"afterView",
".",
"getType",
"(",
")",
"==",
"ItemType",
".",
"NODE",
")",
"{",
"descriptors",
".",
"addAll",
"(",
"generateNodeInOutDescriptors",
"(",
"ChangeDescriptorName",
".",
"IN_EDGE",
",",
"CompleteNode",
"::",
"inEdgeIdentifiers",
")",
")",
";",
"descriptors",
".",
"addAll",
"(",
"generateNodeInOutDescriptors",
"(",
"ChangeDescriptorName",
".",
"OUT_EDGE",
",",
"CompleteNode",
"::",
"outEdgeIdentifiers",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"afterView",
".",
"getType",
"(",
")",
"==",
"ItemType",
".",
"EDGE",
")",
"{",
"descriptors",
".",
"addAll",
"(",
"generateEdgeStartEndDescriptors",
"(",
"ChangeDescriptorName",
".",
"START_NODE",
",",
"CompleteEdge",
"::",
"startNodeIdentifier",
")",
")",
";",
"descriptors",
".",
"addAll",
"(",
"generateEdgeStartEndDescriptors",
"(",
"ChangeDescriptorName",
".",
"END_NODE",
",",
"CompleteEdge",
"::",
"endNodeIdentifier",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"afterView",
".",
"getType",
"(",
")",
"==",
"ItemType",
".",
"RELATION",
")",
"{",
"descriptors",
".",
"addAll",
"(",
"generateRelationMemberDescriptors",
"(",
")",
")",
";",
"/*\n * Should we handle the other special relation fields here?\n * allRelationsWithSameOsmIdentifier, allKnownOsmMembers, and osmRelationIdentifier are\n * fields that may be altered.\n */",
"}",
"descriptors",
".",
"sort",
"(",
"COMPARATOR",
")",
";",
"return",
"descriptors",
";",
"}",
"ChangeDescriptorType",
"getChangeDescriptorType",
"(",
")",
"{",
"return",
"this",
".",
"changeDescriptorType",
";",
"}",
"private",
"List",
"<",
"LongElementChangeDescriptor",
">",
"generateEdgeStartEndDescriptors",
"(",
"final",
"ChangeDescriptorName",
"name",
",",
"final",
"Function",
"<",
"CompleteEdge",
",",
"Long",
">",
"memberExtractor",
")",
"{",
"final",
"CompleteEdge",
"beforeEntity",
"=",
"(",
"CompleteEdge",
")",
"this",
".",
"beforeView",
";",
"final",
"CompleteEdge",
"afterEntity",
"=",
"(",
"CompleteEdge",
")",
"this",
".",
"afterView",
";",
"/*\n * If the afterView identifier was null, then we know that it was not updated. We can just\n * return nothing.\n */",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
"==",
"null",
")",
"{",
"return",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"}",
"final",
"Long",
"beforeIdentifier",
";",
"if",
"(",
"beforeEntity",
"!=",
"null",
")",
"{",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"name",
",",
"name",
")",
";",
"}",
"beforeIdentifier",
"=",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
";",
"}",
"else",
"{",
"beforeIdentifier",
"=",
"null",
";",
"}",
"final",
"Long",
"afterIdentifier",
"=",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
";",
"return",
"generateLongValueDescriptors",
"(",
"name",
",",
"beforeIdentifier",
",",
"afterIdentifier",
")",
";",
"}",
"private",
"List",
"<",
"ChangeDescriptor",
">",
"generateGeometryDescriptors",
"(",
")",
"{",
"final",
"List",
"<",
"ChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"/*\n * Relations do not have explicit geometry, so return nothing.\n */",
"if",
"(",
"this",
".",
"afterView",
".",
"getType",
"(",
")",
"==",
"ItemType",
".",
"RELATION",
")",
"{",
"return",
"descriptors",
";",
"}",
"final",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
"beforeEntity",
"=",
"(",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
")",
"this",
".",
"beforeView",
";",
"final",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
"afterEntity",
"=",
"(",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
")",
"this",
".",
"afterView",
";",
"/*\n * If the afterView geometry is null, then we know the geometry was not updated.\n */",
"if",
"(",
"afterEntity",
".",
"getGeometry",
"(",
")",
"==",
"null",
")",
"{",
"return",
"descriptors",
";",
"}",
"final",
"List",
"<",
"Location",
">",
"beforeGeometry",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"final",
"List",
"<",
"Location",
">",
"afterGeometry",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"afterEntity",
".",
"getGeometry",
"(",
")",
".",
"forEach",
"(",
"afterGeometry",
"::",
"add",
")",
";",
"if",
"(",
"beforeEntity",
"!=",
"null",
")",
"{",
"if",
"(",
"beforeEntity",
".",
"getGeometry",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"\"",
"geometry",
"\"",
",",
"\"",
"geometry",
"\"",
")",
";",
"}",
"beforeEntity",
".",
"getGeometry",
"(",
")",
".",
"forEach",
"(",
"beforeGeometry",
"::",
"add",
")",
";",
"}",
"descriptors",
".",
"addAll",
"(",
"GeometryChangeDescriptor",
".",
"getDescriptorsForGeometry",
"(",
"beforeGeometry",
",",
"afterGeometry",
")",
")",
";",
"return",
"descriptors",
";",
"}",
"private",
"List",
"<",
"LongElementChangeDescriptor",
">",
"generateLongSetDescriptors",
"(",
"final",
"ChangeDescriptorName",
"name",
",",
"final",
"Set",
"<",
"Long",
">",
"beforeSet",
",",
"final",
"Set",
"<",
"Long",
">",
"afterSet",
")",
"{",
"final",
"List",
"<",
"LongElementChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"final",
"Set",
"<",
"Long",
">",
"removedFromAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"beforeSet",
",",
"afterSet",
")",
";",
"final",
"Set",
"<",
"Long",
">",
"addedToAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"afterSet",
",",
"beforeSet",
")",
";",
"for",
"(",
"final",
"Long",
"identifier",
":",
"removedFromAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"LongElementChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"REMOVE",
",",
"identifier",
",",
"null",
",",
"name",
")",
")",
";",
"}",
"for",
"(",
"final",
"Long",
"identifier",
":",
"addedToAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"LongElementChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"ADD",
",",
"identifier",
",",
"name",
")",
")",
";",
"}",
"return",
"descriptors",
";",
"}",
"private",
"List",
"<",
"LongElementChangeDescriptor",
">",
"generateLongValueDescriptors",
"(",
"final",
"ChangeDescriptorName",
"name",
",",
"final",
"Long",
"beforeIdentifier",
",",
"final",
"Long",
"afterIdentifier",
")",
"{",
"final",
"List",
"<",
"LongElementChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"/*\n * This case occurs when an brand new Long value (e.g. startNode, endNode, etc.) is being\n * added, and so there is no beforeElement.\n */",
"if",
"(",
"beforeIdentifier",
"==",
"null",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"LongElementChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"ADD",
",",
"null",
",",
"afterIdentifier",
",",
"name",
")",
")",
";",
"}",
"else",
"{",
"descriptors",
".",
"add",
"(",
"new",
"LongElementChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"UPDATE",
",",
"beforeIdentifier",
",",
"afterIdentifier",
",",
"name",
")",
")",
";",
"}",
"return",
"descriptors",
";",
"}",
"private",
"List",
"<",
"LongElementChangeDescriptor",
">",
"generateNodeInOutDescriptors",
"(",
"final",
"ChangeDescriptorName",
"name",
",",
"final",
"Function",
"<",
"CompleteNode",
",",
"Set",
"<",
"Long",
">",
">",
"memberExtractor",
")",
"{",
"final",
"CompleteNode",
"beforeEntity",
"=",
"(",
"CompleteNode",
")",
"this",
".",
"beforeView",
";",
"final",
"CompleteNode",
"afterEntity",
"=",
"(",
"CompleteNode",
")",
"this",
".",
"afterView",
";",
"/*\n * If the afterView in/out edge set was null, then we know that it was not updated. We can\n * just return nothing.\n */",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
"==",
"null",
")",
"{",
"return",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"}",
"final",
"Set",
"<",
"Long",
">",
"beforeSet",
";",
"if",
"(",
"beforeEntity",
"!=",
"null",
")",
"{",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"name",
",",
"name",
")",
";",
"}",
"beforeSet",
"=",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
";",
"}",
"else",
"{",
"beforeSet",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"}",
"final",
"Set",
"<",
"Long",
">",
"afterSet",
"=",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
";",
"return",
"generateLongSetDescriptors",
"(",
"name",
",",
"beforeSet",
",",
"afterSet",
")",
";",
"}",
"private",
"List",
"<",
"LongElementChangeDescriptor",
">",
"generateParentRelationDescriptors",
"(",
"final",
"Function",
"<",
"CompleteEntity",
",",
"Set",
"<",
"Long",
">",
">",
"memberExtractor",
")",
"{",
"final",
"ChangeDescriptorName",
"name",
"=",
"ChangeDescriptorName",
".",
"PARENT_RELATION",
";",
"final",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
"beforeEntity",
"=",
"(",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
")",
"this",
".",
"beforeView",
";",
"final",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
"afterEntity",
"=",
"(",
"CompleteEntity",
"<",
"?",
"extends",
"CompleteEntity",
"<",
"?",
">",
">",
")",
"this",
".",
"afterView",
";",
"/*\n * If the afterView parent relations were null, then we know that they were not updated. We\n * can just return nothing.\n */",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
"==",
"null",
")",
"{",
"return",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"}",
"final",
"Set",
"<",
"Long",
">",
"beforeSet",
";",
"if",
"(",
"beforeEntity",
"!=",
"null",
")",
"{",
"if",
"(",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"name",
",",
"name",
")",
";",
"}",
"beforeSet",
"=",
"memberExtractor",
".",
"apply",
"(",
"beforeEntity",
")",
";",
"}",
"else",
"{",
"beforeSet",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"}",
"final",
"Set",
"<",
"Long",
">",
"afterSet",
"=",
"memberExtractor",
".",
"apply",
"(",
"afterEntity",
")",
";",
"return",
"generateLongSetDescriptors",
"(",
"name",
",",
"beforeSet",
",",
"afterSet",
")",
";",
"}",
"private",
"List",
"<",
"ChangeDescriptor",
">",
"generateRelationMemberDescriptors",
"(",
")",
"{",
"final",
"List",
"<",
"ChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"final",
"CompleteRelation",
"beforeEntity",
"=",
"(",
"CompleteRelation",
")",
"this",
".",
"beforeView",
";",
"final",
"CompleteRelation",
"afterEntity",
"=",
"(",
"CompleteRelation",
")",
"this",
".",
"afterView",
";",
"/*\n * If the afterView members were null, then we know that the members were not updated. We\n * can just return nothing.\n */",
"if",
"(",
"afterEntity",
".",
"members",
"(",
")",
"==",
"null",
")",
"{",
"return",
"descriptors",
";",
"}",
"final",
"Set",
"<",
"RelationBean",
".",
"RelationBeanItem",
">",
"beforeBeanSet",
";",
"if",
"(",
"beforeEntity",
"!=",
"null",
")",
"{",
"if",
"(",
"beforeEntity",
".",
"members",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"\"",
"relation members",
"\"",
",",
"\"",
"relation members",
"\"",
")",
";",
"}",
"beforeBeanSet",
"=",
"beforeEntity",
".",
"members",
"(",
")",
".",
"asBean",
"(",
")",
".",
"asSet",
"(",
")",
";",
"}",
"else",
"{",
"beforeBeanSet",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"}",
"final",
"Set",
"<",
"RelationBean",
".",
"RelationBeanItem",
">",
"afterBeanSet",
"=",
"afterEntity",
".",
"members",
"(",
")",
".",
"asBean",
"(",
")",
".",
"asSet",
"(",
")",
";",
"final",
"Set",
"<",
"RelationBean",
".",
"RelationBeanItem",
">",
"itemsRemovedFromAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"beforeBeanSet",
",",
"afterBeanSet",
")",
";",
"final",
"Set",
"<",
"RelationBean",
".",
"RelationBeanItem",
">",
"itemsAddedToAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"afterBeanSet",
",",
"beforeBeanSet",
")",
";",
"for",
"(",
"final",
"RelationBean",
".",
"RelationBeanItem",
"item",
":",
"itemsRemovedFromAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"RelationMemberChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"REMOVE",
",",
"item",
".",
"getIdentifier",
"(",
")",
",",
"item",
".",
"getType",
"(",
")",
",",
"item",
".",
"getRole",
"(",
")",
")",
")",
";",
"}",
"for",
"(",
"final",
"RelationBean",
".",
"RelationBeanItem",
"item",
":",
"itemsAddedToAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"RelationMemberChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"ADD",
",",
"item",
".",
"getIdentifier",
"(",
")",
",",
"item",
".",
"getType",
"(",
")",
",",
"item",
".",
"getRole",
"(",
")",
")",
")",
";",
"}",
"return",
"descriptors",
";",
"}",
"private",
"List",
"<",
"ChangeDescriptor",
">",
"generateTagDescriptors",
"(",
")",
"{",
"final",
"List",
"<",
"ChangeDescriptor",
">",
"descriptors",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"/*\n * If the afterView tags were null, then we know that the tags were not updated. We can just\n * return nothing.\n */",
"if",
"(",
"this",
".",
"afterView",
".",
"getTags",
"(",
")",
"==",
"null",
")",
"{",
"return",
"descriptors",
";",
"}",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"beforeTags",
";",
"if",
"(",
"this",
".",
"beforeView",
"!=",
"null",
")",
"{",
"if",
"(",
"this",
".",
"beforeView",
".",
"getTags",
"(",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"CoreException",
"(",
"CORRUPTED_FEATURECHANGE_MESSAGE",
",",
"\"",
"tags",
"\"",
",",
"\"",
"tags",
"\"",
")",
";",
"}",
"beforeTags",
"=",
"this",
".",
"beforeView",
".",
"getTags",
"(",
")",
";",
"}",
"else",
"{",
"beforeTags",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"}",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"afterTags",
"=",
"this",
".",
"afterView",
".",
"getTags",
"(",
")",
";",
"final",
"Set",
"<",
"String",
">",
"keysRemovedFromAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"beforeTags",
".",
"keySet",
"(",
")",
",",
"afterTags",
".",
"keySet",
"(",
")",
")",
";",
"final",
"Set",
"<",
"String",
">",
"keysAddedToAfterView",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"difference",
"(",
"afterTags",
".",
"keySet",
"(",
")",
",",
"beforeTags",
".",
"keySet",
"(",
")",
")",
";",
"final",
"Set",
"<",
"String",
">",
"keysShared",
"=",
"com",
".",
"google",
".",
"common",
".",
"collect",
".",
"Sets",
".",
"intersection",
"(",
"beforeTags",
".",
"keySet",
"(",
")",
",",
"afterTags",
".",
"keySet",
"(",
")",
")",
";",
"for",
"(",
"final",
"String",
"key",
":",
"keysRemovedFromAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"TagChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"REMOVE",
",",
"key",
",",
"beforeTags",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"}",
"for",
"(",
"final",
"String",
"key",
":",
"keysAddedToAfterView",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"TagChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"ADD",
",",
"key",
",",
"afterTags",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"}",
"for",
"(",
"final",
"String",
"key",
":",
"keysShared",
")",
"{",
"if",
"(",
"!",
"beforeTags",
".",
"get",
"(",
"key",
")",
".",
"equals",
"(",
"afterTags",
".",
"get",
"(",
"key",
")",
")",
")",
"{",
"descriptors",
".",
"add",
"(",
"new",
"TagChangeDescriptor",
"(",
"ChangeDescriptorType",
".",
"UPDATE",
",",
"key",
",",
"afterTags",
".",
"get",
"(",
"key",
")",
",",
"beforeTags",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"}",
"}",
"return",
"descriptors",
";",
"}",
"}"
] | A helper class for generating a list of {@link ChangeDescriptor}s based on some
{@link AtlasEntity} beforeView and afterView. | [
"A",
"helper",
"class",
"for",
"generating",
"a",
"list",
"of",
"{",
"@link",
"ChangeDescriptor",
"}",
"s",
"based",
"on",
"some",
"{",
"@link",
"AtlasEntity",
"}",
"beforeView",
"and",
"afterView",
"."
] | [
"// NOSONAR"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd2fd959ed21e7a7d054c42ccd33ec15b3ab62e0 | timboudreau/netbeans-contrib | vcscore/src/main/java/org/netbeans/modules/vcscore/VcsFSUtils.java | [
"Apache-2.0"
] | Java | VcsFSUtils | /**
* Yet unimplemented file system utilities
*
* @author Martin Entlicher
*/ | Yet unimplemented file system utilities
@author Martin Entlicher | [
"Yet",
"unimplemented",
"file",
"system",
"utilities",
"@author",
"Martin",
"Entlicher"
] | public class VcsFSUtils {
private static VcsFSUtils vcsFSUtils;
private Map lockedFilesToBeModified;
/** Creates a new instance of VcsFSUtils */
private VcsFSUtils() {
lockedFilesToBeModified = new HashMap();
}
public static synchronized VcsFSUtils getDefault() {
if (vcsFSUtils == null) {
vcsFSUtils = new VcsFSUtils();
}
return vcsFSUtils;
}
/**
* Lock the files so that they can not be modified in the IDE.
* This is necessary for commands, that make changes to the processed files.
* It's crutial, that the file does not get modified twice - externally via
* the update command and internally (e.g. through the Editor).
* One <b>MUST</b> call {@link #unlockFilesToBeModified} after the command
* finish.
* @param path The path of the file to be locked or directory in which all
* files will be locked.
* @param recursively Whether the files in directories should be locked recursively.
*/
public void lockFilesToBeModified(String path, boolean recursively) {
if (".".equals(path)) path = "";
synchronized (lockedFilesToBeModified) {
// Multiple locks are not considered. It's locked just once.
lockedFilesToBeModified.put(path, recursively ? Boolean.TRUE : Boolean.FALSE);
}
}
/**
* Unlock the files that were previously locked by {@link #lockFilesToBeModified}
* method. It's necessary to call this method with appropriate arguments after
* the command finish so that the user can edit the files.
*/
public void unlockFilesToBeModified(String path, boolean recursively) {
if (".".equals(path)) path = "";
synchronized (lockedFilesToBeModified) {
lockedFilesToBeModified.remove(path);
}
}
private static final Object GROUP_LOCK = new Object();
public void fileChanged(final FileObject fo) {
// Fire the change asynchronously to prevent deadlocks.
org.openide.util.RequestProcessor.getDefault().post(new Runnable() {
public void run() {
FileProperties fprops = Turbo.getMeta(fo);
String oldStatus = FileProperties.getStatus(fprops);
VcsProvider provider = VcsProvider.getProvider(fo);
if (provider == null) {
return ;
}
if (!provider.getNotModifiableStatuses().contains(oldStatus) && Statuses.getUnknownStatus().equals(oldStatus) == false) {
String status = FileStatusInfo.MODIFIED.getName();
Map tranls = provider.getGenericStatusTranslation();
if (tranls != null) {
status = (String) tranls.get(status);
if (status == null) {
// There's no mapping, use the generic status name!
status = FileStatusInfo.MODIFIED.getName();
}
}
FileProperties updated = new FileProperties(fprops);
updated.setName(fo.getNameExt());
updated.setStatus(status);
Turbo.setMeta(fo, updated);
}
provider.callFileChangeHandler(fo, oldStatus);
VcsGroupSettings grSettings = (VcsGroupSettings) SharedClassObject.findObject(VcsGroupSettings.class, true);
if (!grSettings.isDisableGroups()) {
if (grSettings.getAutoAddition() == VcsGroupSettings.ADDITION_TO_DEFAULT
|| grSettings.getAutoAddition() == VcsGroupSettings.ADDITION_ASK) {
if (fo != null) {
try {
int sharability = SharabilityQuery.getSharability(FileUtil.toFile(fo));
if (sharability != SharabilityQuery.NOT_SHARABLE) {
DataObject dobj = DataObject.find(fo);
synchronized (GROUP_LOCK) {
DataShadow shadow = GroupUtils.findDOInGroups(dobj);
if (shadow == null) {
// it doesn't exist in groups, add it..
if (grSettings.getAutoAddition() == VcsGroupSettings.ADDITION_ASK) {
AddToGroupDialog.openChooseDialog(dobj);
} else {
GroupUtils.addToDefaultGroup(new Node[] {dobj.getNodeDelegate()});
}
}
}
}
} catch (DataObjectNotFoundException exc) {
}
}
}
}
}
});
}
} | [
"public",
"class",
"VcsFSUtils",
"{",
"private",
"static",
"VcsFSUtils",
"vcsFSUtils",
";",
"private",
"Map",
"lockedFilesToBeModified",
";",
"/** Creates a new instance of VcsFSUtils */",
"private",
"VcsFSUtils",
"(",
")",
"{",
"lockedFilesToBeModified",
"=",
"new",
"HashMap",
"(",
")",
";",
"}",
"public",
"static",
"synchronized",
"VcsFSUtils",
"getDefault",
"(",
")",
"{",
"if",
"(",
"vcsFSUtils",
"==",
"null",
")",
"{",
"vcsFSUtils",
"=",
"new",
"VcsFSUtils",
"(",
")",
";",
"}",
"return",
"vcsFSUtils",
";",
"}",
"/**\n * Lock the files so that they can not be modified in the IDE.\n * This is necessary for commands, that make changes to the processed files.\n * It's crutial, that the file does not get modified twice - externally via\n * the update command and internally (e.g. through the Editor).\n * One <b>MUST</b> call {@link #unlockFilesToBeModified} after the command\n * finish.\n * @param path The path of the file to be locked or directory in which all\n * files will be locked.\n * @param recursively Whether the files in directories should be locked recursively.\n */",
"public",
"void",
"lockFilesToBeModified",
"(",
"String",
"path",
",",
"boolean",
"recursively",
")",
"{",
"if",
"(",
"\"",
".",
"\"",
".",
"equals",
"(",
"path",
")",
")",
"path",
"=",
"\"",
"\"",
";",
"synchronized",
"(",
"lockedFilesToBeModified",
")",
"{",
"lockedFilesToBeModified",
".",
"put",
"(",
"path",
",",
"recursively",
"?",
"Boolean",
".",
"TRUE",
":",
"Boolean",
".",
"FALSE",
")",
";",
"}",
"}",
"/**\n * Unlock the files that were previously locked by {@link #lockFilesToBeModified}\n * method. It's necessary to call this method with appropriate arguments after\n * the command finish so that the user can edit the files.\n */",
"public",
"void",
"unlockFilesToBeModified",
"(",
"String",
"path",
",",
"boolean",
"recursively",
")",
"{",
"if",
"(",
"\"",
".",
"\"",
".",
"equals",
"(",
"path",
")",
")",
"path",
"=",
"\"",
"\"",
";",
"synchronized",
"(",
"lockedFilesToBeModified",
")",
"{",
"lockedFilesToBeModified",
".",
"remove",
"(",
"path",
")",
";",
"}",
"}",
"private",
"static",
"final",
"Object",
"GROUP_LOCK",
"=",
"new",
"Object",
"(",
")",
";",
"public",
"void",
"fileChanged",
"(",
"final",
"FileObject",
"fo",
")",
"{",
"org",
".",
"openide",
".",
"util",
".",
"RequestProcessor",
".",
"getDefault",
"(",
")",
".",
"post",
"(",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"FileProperties",
"fprops",
"=",
"Turbo",
".",
"getMeta",
"(",
"fo",
")",
";",
"String",
"oldStatus",
"=",
"FileProperties",
".",
"getStatus",
"(",
"fprops",
")",
";",
"VcsProvider",
"provider",
"=",
"VcsProvider",
".",
"getProvider",
"(",
"fo",
")",
";",
"if",
"(",
"provider",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"provider",
".",
"getNotModifiableStatuses",
"(",
")",
".",
"contains",
"(",
"oldStatus",
")",
"&&",
"Statuses",
".",
"getUnknownStatus",
"(",
")",
".",
"equals",
"(",
"oldStatus",
")",
"==",
"false",
")",
"{",
"String",
"status",
"=",
"FileStatusInfo",
".",
"MODIFIED",
".",
"getName",
"(",
")",
";",
"Map",
"tranls",
"=",
"provider",
".",
"getGenericStatusTranslation",
"(",
")",
";",
"if",
"(",
"tranls",
"!=",
"null",
")",
"{",
"status",
"=",
"(",
"String",
")",
"tranls",
".",
"get",
"(",
"status",
")",
";",
"if",
"(",
"status",
"==",
"null",
")",
"{",
"status",
"=",
"FileStatusInfo",
".",
"MODIFIED",
".",
"getName",
"(",
")",
";",
"}",
"}",
"FileProperties",
"updated",
"=",
"new",
"FileProperties",
"(",
"fprops",
")",
";",
"updated",
".",
"setName",
"(",
"fo",
".",
"getNameExt",
"(",
")",
")",
";",
"updated",
".",
"setStatus",
"(",
"status",
")",
";",
"Turbo",
".",
"setMeta",
"(",
"fo",
",",
"updated",
")",
";",
"}",
"provider",
".",
"callFileChangeHandler",
"(",
"fo",
",",
"oldStatus",
")",
";",
"VcsGroupSettings",
"grSettings",
"=",
"(",
"VcsGroupSettings",
")",
"SharedClassObject",
".",
"findObject",
"(",
"VcsGroupSettings",
".",
"class",
",",
"true",
")",
";",
"if",
"(",
"!",
"grSettings",
".",
"isDisableGroups",
"(",
")",
")",
"{",
"if",
"(",
"grSettings",
".",
"getAutoAddition",
"(",
")",
"==",
"VcsGroupSettings",
".",
"ADDITION_TO_DEFAULT",
"||",
"grSettings",
".",
"getAutoAddition",
"(",
")",
"==",
"VcsGroupSettings",
".",
"ADDITION_ASK",
")",
"{",
"if",
"(",
"fo",
"!=",
"null",
")",
"{",
"try",
"{",
"int",
"sharability",
"=",
"SharabilityQuery",
".",
"getSharability",
"(",
"FileUtil",
".",
"toFile",
"(",
"fo",
")",
")",
";",
"if",
"(",
"sharability",
"!=",
"SharabilityQuery",
".",
"NOT_SHARABLE",
")",
"{",
"DataObject",
"dobj",
"=",
"DataObject",
".",
"find",
"(",
"fo",
")",
";",
"synchronized",
"(",
"GROUP_LOCK",
")",
"{",
"DataShadow",
"shadow",
"=",
"GroupUtils",
".",
"findDOInGroups",
"(",
"dobj",
")",
";",
"if",
"(",
"shadow",
"==",
"null",
")",
"{",
"if",
"(",
"grSettings",
".",
"getAutoAddition",
"(",
")",
"==",
"VcsGroupSettings",
".",
"ADDITION_ASK",
")",
"{",
"AddToGroupDialog",
".",
"openChooseDialog",
"(",
"dobj",
")",
";",
"}",
"else",
"{",
"GroupUtils",
".",
"addToDefaultGroup",
"(",
"new",
"Node",
"[",
"]",
"{",
"dobj",
".",
"getNodeDelegate",
"(",
")",
"}",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"DataObjectNotFoundException",
"exc",
")",
"{",
"}",
"}",
"}",
"}",
"}",
"}",
")",
";",
"}",
"}"
] | Yet unimplemented file system utilities | [
"Yet",
"unimplemented",
"file",
"system",
"utilities"
] | [
"// Multiple locks are not considered. It's locked just once.",
"// Fire the change asynchronously to prevent deadlocks.",
"// There's no mapping, use the generic status name!",
"// it doesn't exist in groups, add it.."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd31fa2367af242562bd4378b9874d8aaeadab6b | Ronneesley/redesocial | codigo/RedeSocial/test/br/com/redesocial/modelo/bo/CategoriaBOTest.java | [
"MIT"
] | Java | CategoriaBOTest | /**
* Unidade de testes para o CategoriaBO
* @author Fernando Maciel da Silva
* @since 26/09/2017
*/ | Unidade de testes para o CategoriaBO
@author Fernando Maciel da Silva
@since 26/09/2017 | [
"Unidade",
"de",
"testes",
"para",
"o",
"CategoriaBO",
"@author",
"Fernando",
"Maciel",
"da",
"Silva",
"@since",
"26",
"/",
"09",
"/",
"2017"
] | public class CategoriaBOTest {
@Test
public void testMetodoInserir() {
CategoriaBO categoriaBO = new CategoriaBO();
Categoria categoria = new Categoria();
categoria.setDescricao("Comentário");
try {
categoriaBO.inserir(categoria);
} catch (Exception ex) {
fail("Falha ao inserir comentário: " + ex.getMessage());
}
}
@Test
public void testMetodoAlterar() {
}
@Test
public void testMetodoSelecionar() {
}
@Test
public void testMetodoListar() {
CategoriaBO bo = new CategoriaBO();
try {
List existentes = bo.listar();
int qtdeExistentes = existentes.size();
final int qtde = 10;
for (int i = 0; i < 10; i++){
Categoria categoria = new Categoria();
categoria.setDescricao("Listar");
try {
bo.inserir(categoria);
} catch (Exception ex) {
fail("Falha ao inserir uma categoria: " + ex.getMessage());
}
}
List existentesFinal = bo.listar();
int qtdeExistentesFinal = existentesFinal.size();
int diferenca = qtdeExistentesFinal - qtdeExistentes;
assertEquals(qtde, diferenca);
} catch (Exception ex){
fail("Erro ao listar: " + ex.getMessage());
}
}
@Test
public void testMetodoExcluir() {
}
} | [
"public",
"class",
"CategoriaBOTest",
"{",
"@",
"Test",
"public",
"void",
"testMetodoInserir",
"(",
")",
"{",
"CategoriaBO",
"categoriaBO",
"=",
"new",
"CategoriaBO",
"(",
")",
";",
"Categoria",
"categoria",
"=",
"new",
"Categoria",
"(",
")",
";",
"categoria",
".",
"setDescricao",
"(",
"\"",
"Comentário\"",
")",
";",
"",
"try",
"{",
"categoriaBO",
".",
"inserir",
"(",
"categoria",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"fail",
"(",
"\"",
"Falha ao inserir comentário: \"",
" ",
" ",
"x.",
"g",
"etMessage(",
")",
")",
";",
"",
"}",
"}",
"@",
"Test",
"public",
"void",
"testMetodoAlterar",
"(",
")",
"{",
"}",
"@",
"Test",
"public",
"void",
"testMetodoSelecionar",
"(",
")",
"{",
"}",
"@",
"Test",
"public",
"void",
"testMetodoListar",
"(",
")",
"{",
"CategoriaBO",
"bo",
"=",
"new",
"CategoriaBO",
"(",
")",
";",
"try",
"{",
"List",
"existentes",
"=",
"bo",
".",
"listar",
"(",
")",
";",
"int",
"qtdeExistentes",
"=",
"existentes",
".",
"size",
"(",
")",
";",
"final",
"int",
"qtde",
"=",
"10",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"10",
";",
"i",
"++",
")",
"{",
"Categoria",
"categoria",
"=",
"new",
"Categoria",
"(",
")",
";",
"categoria",
".",
"setDescricao",
"(",
"\"",
"Listar",
"\"",
")",
";",
"try",
"{",
"bo",
".",
"inserir",
"(",
"categoria",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"fail",
"(",
"\"",
"Falha ao inserir uma categoria: ",
"\"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"List",
"existentesFinal",
"=",
"bo",
".",
"listar",
"(",
")",
";",
"int",
"qtdeExistentesFinal",
"=",
"existentesFinal",
".",
"size",
"(",
")",
";",
"int",
"diferenca",
"=",
"qtdeExistentesFinal",
"-",
"qtdeExistentes",
";",
"assertEquals",
"(",
"qtde",
",",
"diferenca",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"fail",
"(",
"\"",
"Erro ao listar: ",
"\"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testMetodoExcluir",
"(",
")",
"{",
"}",
"}"
] | Unidade de testes para o CategoriaBO
@author Fernando Maciel da Silva
@since 26/09/2017 | [
"Unidade",
"de",
"testes",
"para",
"o",
"CategoriaBO",
"@author",
"Fernando",
"Maciel",
"da",
"Silva",
"@since",
"26",
"/",
"09",
"/",
"2017"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | HtmlNodeFilters | /** Factory methods for making various useful combinations of NodeFilters,
* and additional {@link NodeFilter}s to supplement those in
* {@link org.htmlparser.filters}
*/ | Factory methods for making various useful combinations of NodeFilters,
and additional NodeFilters to supplement those in
org.htmlparser.filters | [
"Factory",
"methods",
"for",
"making",
"various",
"useful",
"combinations",
"of",
"NodeFilters",
"and",
"additional",
"NodeFilters",
"to",
"supplement",
"those",
"in",
"org",
".",
"htmlparser",
".",
"filters"
] | public class HtmlNodeFilters {
private static Logger log = Logger.getLogger(HtmlNodeFilters.class);
/** No instances */
private HtmlNodeFilters() {
}
/** Create a NodeFilter that matches tags. Equivalant to
* <pre>new TagNameFilter(tag)</pre> */
public static NodeFilter tag(String tag) {
return new TagNameFilter(tag);
}
/** Create a NodeFilter that matches tags with a specified tagname and
* attribute value. Equivalant to
* <pre>new AndFilter(new TagNameFilter(tag),
new HasAttributeFilter(attr, val))</pre> */
public static NodeFilter tagWithAttribute(String tag,
String attr, String val) {
return new AndFilter(new TagNameFilter(tag),
new HasAttributeFilter(attr, val));
}
/** Create a NodeFilter that matches tags with a specified tagname and
* that define a given attribute. Equivalant to
* <pre>new AndFilter(new TagNameFilter(tag),
new HasAttributeFilter(attr))</pre>
* @since 1.32.0
*/
public static NodeFilter tagWithAttribute(String tag,
String attr) {
return new AndFilter(new TagNameFilter(tag),
new HasAttributeFilter(attr));
}
/** Create a NodeFilter that matches div tags with a specified
* attribute value. Equivalant to
* <pre>new AndFilter(new TagNameFilter("div"),
new HasAttributeFilter(attr, val))</pre> */
public static NodeFilter divWithAttribute(String attr, String val) {
return tagWithAttribute("div", attr, val);
}
/** Create a NodeFilter that matches tags with a specified tagname and
* an attribute value matching a regex.
* @param tag The tagname.
* @param attr The attribute name.
* @param valRegexp The pattern to match against the attribute value.
*/
public static NodeFilter tagWithAttributeRegex(String tag,
String attr,
String valRegexp) {
return new AndFilter(new TagNameFilter(tag),
new HasAttributeRegexFilter(attr, valRegexp));
}
/** Create a NodeFilter that matches tags with a specified tagname and
* an attribute value matching a regex.
* @param tag The tagname.
* @param attr The attribute name.
* @param valRegexp The pattern to match against the attribute value.
* @param ignoreCase If true, match is case insensitive
*/
public static NodeFilter tagWithAttributeRegex(String tag,
String attr,
String valRegexp,
boolean ignoreCase) {
return new AndFilter(new TagNameFilter(tag),
new HasAttributeRegexFilter(attr, valRegexp,
ignoreCase));
}
/** Create a NodeFilter that matches tags with a specified tagname and
* nested text containing a substring. <i>Eg,</i> in <code>
* <select><option value="1">Option text
* 1</option>...</select></code>, <code>tagWithText("option", "Option text") </code>would match the <code><option> </code>node.
* @param tag The tagname.
* @param text The nested text to match.
*/
public static NodeFilter tagWithText(String tag, String text) {
return new AndFilter(new TagNameFilter(tag),
new CompositeStringFilter(text));
}
/** Create a NodeFilter that matches tags with a specified tagname and
* nested text containing a substring.
* @param tag The tagname.
* @param text The nested text to match.
* @param ignoreCase If true, match is case insensitive
*/
public static NodeFilter tagWithText(String tag, String text,
boolean ignoreCase) {
return new AndFilter(new TagNameFilter(tag),
new CompositeStringFilter(text, ignoreCase));
}
/** Create a NodeFilter that matches composite tags with a specified
* tagname and nested text matching a regex. <i>Eg</i>, <code>
* @param tag The tagname.
* @param regex The pattern to match against the nested text.
*/
public static NodeFilter tagWithTextRegex(String tag, String regex) {
return new AndFilter(new TagNameFilter(tag),
new CompositeRegexFilter(regex));
}
/** Create a NodeFilter that matches tags with a specified tagname and
* nested text matching a regex. Equivalant to
* <pre>new AndFilter(new TagNameFilter(tag),
new RegexFilter(regex))</pre>
* @param tag The tagname.
* @param regex The pattern to match against the nested text.
* @param ignoreCase If true, match is case insensitive
*/
public static NodeFilter tagWithTextRegex(String tag,
String regex,
boolean ignoreCase) {
return new AndFilter(new TagNameFilter(tag),
new CompositeRegexFilter(regex, ignoreCase));
}
/**
* <p>
* Returns a node filter that selects nodes that have an ancestor node that
* matches the given ancestor node filter.
* </p>
* <p>
* Note that this filter will match not only the node you might be thinking
* of but also every node between it and the ancestor you might be thinking
* of: you should combine it with another filter, probably an AndFilter, to
* select only the node you might mean.
* </p>
*
* @param ancestorFilter
* A node filter to be applied to ancestors.
* @return A node filter that returns true if and only if the examined node is
* non-null and has an ancestor that matches the given ancestor node
* filter.
* @since 1.71
*/ public static NodeFilter ancestor(final NodeFilter ancestorFilter) {
return new NodeFilter() {
@Override
public boolean accept(Node node) {
if (node == null || !(node instanceof Tag) || ((Tag)node).isEndTag()) {
return false;
}
Node ancestor = node.getParent();
while (ancestor != null && ancestor instanceof Tag) {
if (ancestorFilter.accept(ancestor)) {
return true;
}
ancestor = ancestor.getParent();
}
return false;
}
};
}
/**
* <p>
* A node filter that matches any HTML comment.
* </p>
*
* @return A node filter that matches HTML comment nodes.
* @since 1.64
*/
public static NodeFilter comment() {
return new NodeFilter() {
@Override
public boolean accept(Node node) {
return (node instanceof Remark);
}
};
}
/**
* Creates a NodeFilter that accepts comment nodes containing the
* specified string. The match is case sensitive.
* @param string The string to look for
*/
public static NodeFilter commentWithString(String string) {
return new CommentStringFilter(string);
}
/**
* Creates a NodeFilter that accepts comment nodes containing the
* specified string.
* @param string The string to look for
* @param ignoreCase If true, match is case insensitive
*/
public static NodeFilter commentWithString(String string,
boolean ignoreCase) {
return new CommentStringFilter(string, ignoreCase);
}
/** Create a NodeFilter that matches html comments containing a match for
* a specified regex. The match is case sensitive.
* @param regex The pattern to match.
*/
public static NodeFilter commentWithRegex(String regex) {
return new CommentRegexFilter(regex);
}
/** Create a NodeFilter that matches html comments containing a match for
* a specified regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public static NodeFilter commentWithRegex(String regex, boolean ignoreCase) {
return new CommentRegexFilter(regex, ignoreCase);
}
/** Create a NodeFilter that matches the lowest level node that matches the
* specified filter. This is useful for searching for text within a tag,
* because the default is to match parent nodes as well.
*/
public static NodeFilter lowestLevelMatchFilter(NodeFilter filter) {
return new AndFilter(filter,
new NotFilter(new HasChildFilter(filter, true)));
}
/** Create a NodeFilter that applies all of an array of LinkRegexYesXforms
*/
public static NodeFilter linkRegexYesXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace,
String[] attrs) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
filters[i] = new LinkRegexXform(regex[i], ignoreCase[i],
target[i], replace[i], attrs);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that applies all of an array of LinkRegexNoXforms
*/
public static NodeFilter linkRegexNoXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace,
String[] attrs) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
filters[i] = new LinkRegexXform(regex[i], ignoreCase[i],
target[i], replace[i], attrs)
.setNegateFilter(true);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that applies all of an array of MetaRegexYesXforms
*/
public static NodeFilter metaTagRegexYesXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace,
List<String> names) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
filters[i] = new MetaTagRegexXform(regex[i], ignoreCase[i],
target[i], replace[i], names);
}
return new OrFilter(filters);
}
/**
* <p>
* Returns a node filter that selects tags whose immediate parent tag matches
* the given parent node filter.
* </p>
*
* @param parentFilter
* A node filter to be applied to the immediate parent tag.
* @return A node filter that returns true if and only if the examined node is
* a non-null tag and has an immediate parent tag that matches the
* given parent node filter.
* @since 1.71
*/
public static NodeFilter parent(final NodeFilter parentFilter) {
return new NodeFilter() {
@Override
public boolean accept(Node node) {
if (node == null || !(node instanceof Tag) || ((Tag)node).isEndTag()) {
return false; // end tags return as their parent the matching opening tag
}
Node parent = node.getParent();
if (parent == null || !(node instanceof Tag)) {
return false;
}
return parentFilter.accept(parent);
}
};
}
/** Create a NodeFilter that applies all of an array of StyleRegexYesXforms
*/
public static NodeFilter styleRegexYesXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
filters[i] = new StyleRegexXform(regex[i], ignoreCase[i],
target[i], replace[i]);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that applies all of an array of StyleRegexNoXforms
*/
public static NodeFilter styleRegexNoXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
filters[i] = new StyleRegexXform(regex[i], ignoreCase[i],
target[i], replace[i])
.setNegateFilter(true);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that applies all of an array of RefreshRegexYesXforms
*/
public static NodeFilter refreshRegexYesXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
if (log.isDebug3()) {
log.debug3("Build meta yes" + regex[i] + " targ " + target[i] +
" repl " + replace[i]);
}
filters[i] = new RefreshRegexXform(regex[i], ignoreCase[i],
target[i], replace[i]);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that applies all of an array of RefreshRegexNoXforms
*/
public static NodeFilter refreshRegexNoXforms(String[] regex,
boolean[] ignoreCase,
String[] target,
String[] replace) {
NodeFilter[] filters = new NodeFilter[regex.length];
for (int i = 0; i < regex.length; i++) {
if (log.isDebug3()) {
log.debug3("Build meta no" + regex[i] + " targ " + target[i] +
" repl " + replace[i]);
}
filters[i] = new RefreshRegexXform(regex[i], ignoreCase[i],
target[i], replace[i])
.setNegateFilter(true);
}
return new OrFilter(filters);
}
/** Create a NodeFilter that matches all parts of a subtree except for a
* subtree contained within it. This is useful for removing a section of
* a document except for one or more of its subsections. See {@link
* AllExceptSubtreeNodeFilter}.
*/
public static NodeFilter allExceptSubtree(NodeFilter rootNodeFilter,
NodeFilter subtreeNodeFilter) {
return new AllExceptSubtreeNodeFilter(rootNodeFilter, subtreeNodeFilter);
}
static String getCompositeStringText(CompositeTag node) {
if (node.getEndTag() != null &&
node.getEndPosition() < node.getEndTag().getStartPosition()) {
return node.getStringText();
}
return "";
}
/**
* This class accepts all comment nodes containing the given string.
*/
public static class CommentStringFilter implements NodeFilter {
private String string;
private boolean ignoreCase = false;
/**
* Creates a CommentStringFilter that accepts comment nodes containing
* the specified string. The match is case sensitive.
* @param substring The string to look for
*/
public CommentStringFilter(String substring) {
this(substring, false);
}
/**
* Creates a CommentStringFilter that accepts comment nodes containing
* the specified string.
* @param substring The string to look for
* @param ignoreCase If true, match is case insensitive
*/
public CommentStringFilter(String substring, boolean ignoreCase) {
this.string = substring;
this.ignoreCase = ignoreCase;
}
public boolean accept(Node node) {
if (node instanceof Remark) {
String nodestr = ((Remark)node).getText();
return -1 != (ignoreCase
? StringUtil.indexOfIgnoreCase(nodestr, string)
: nodestr.indexOf(string));
}
return false;
}
}
/**
* This class accepts all composite nodes containing the given string.
*/
public static class CompositeStringFilter implements NodeFilter {
private String string;
private boolean ignoreCase = false;
/**
* Creates a CompositeStringFilter that accepts composite nodes
* containing the specified string. The match is case sensitive.
* @param substring The string to look for
*/
public CompositeStringFilter(String substring) {
this(substring, false);
}
/**
* Creates a CompositeStringFilter that accepts composite nodes
* containing the specified string.
* @param substring The string to look for
* @param ignoreCase If true, match is case insensitive
*/
public CompositeStringFilter(String substring, boolean ignoreCase) {
this.string = substring;
this.ignoreCase = ignoreCase;
}
public boolean accept(Node node) {
if (node instanceof CompositeTag) {
String nodestr = getCompositeStringText((CompositeTag)node);
return -1 != (ignoreCase
? StringUtil.indexOfIgnoreCase(nodestr, string)
: nodestr.indexOf(string));
}
return false;
}
}
/**
* Abstract class for regex filters
*/
public abstract static class BaseRegexFilter implements NodeFilter {
protected CachedPattern pat;
protected boolean negateFilter = false;
/**
* Creates a BaseRegexFilter that performs a case sensitive match for
* the specified regex
* @param regex The pattern to match.
*/
public BaseRegexFilter(String regex) {
this(regex, false);
}
/**
* Creates a BaseRegexFilter that performs a match for
* the specified regex
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public BaseRegexFilter(String regex, boolean ignoreCase) {
this.pat = new CachedPattern(regex);
if (ignoreCase) {
pat.setIgnoreCase(true);
}
// pat.getPattern();
}
public BaseRegexFilter setNegateFilter(boolean val) {
negateFilter = val;
return this;
}
protected boolean isFilterMatch(String str, CachedPattern pat) {
boolean isMatch = pat.getMatcher(str).find();
return negateFilter ? !isMatch : isMatch;
}
public abstract boolean accept(Node node);
/**
* URL encode the part of url that represents the original URL
* @param url the string including the rewritten URL
* @return the content of url with the original url encoded
*/
private static final String tag = "?url=";
protected String urlEncode(String url) {
return urlEncode(url, false);
}
protected String cssEncode(String url) {
return urlEncode(url, true);
}
protected String urlEncode(String url, boolean isCss) {
int startIx = url.indexOf(tag);
if (startIx < 0) {
log.warning("urlEncode: no tag (" + tag + ") in " + url);
return url;
}
startIx += tag.length();
String oldUrl = url.substring(startIx);
// If it is already encoded, leave it alone
if (StringUtil.startsWithIgnoreCase(oldUrl, "http%") ||
StringUtil.startsWithIgnoreCase(oldUrl, "ftp%") ||
StringUtil.startsWithIgnoreCase(oldUrl, "https%")) {
log.debug3("not encoding " + url);
return url;
}
int endIx = url.indexOf('"', startIx);
if (endIx > startIx) {
// meta tag content attribute
oldUrl = url.substring(startIx, endIx);
} else if (isCss && (endIx = url.indexOf(')', startIx)) > startIx) {
// CSS @import
oldUrl = url.substring(startIx, endIx);
} else {
// Normal tag attribute
endIx = -1;
}
int hashpos = oldUrl.indexOf('#');
String hashref = null;
if (hashpos >= 0) {
hashref = oldUrl.substring(hashpos);
oldUrl = oldUrl.substring(0, hashpos);
}
String newUrl = UrlUtil.encodeUrl(oldUrl);
if (log.isDebug3()) log.debug3("urlEncode: " + oldUrl + " -> " + newUrl);
StringBuilder sb = new StringBuilder();
sb.append(url, 0, startIx);
sb.append(newUrl);
if (hashref != null) {
sb.append(hashref);
}
if (endIx >= 0) {
sb.append(url.substring(endIx, url.length()));
}
return sb.toString();
// return url.substring(0, startIx) + newUrl +
// (endIx < 0 ? "" : url.substring(endIx));
}
}
/**
* This class accepts all comment nodes whose text contains a match for
* the regex.
*/
public static class CommentRegexFilter extends BaseRegexFilter {
/**
* Creates a CommentRegexFilter that accepts comment nodes whose text
* contains a match for the regex. The match is case sensitive.
* @param regex The pattern to match.
*/
public CommentRegexFilter(String regex) {
super(regex);
}
/**
* Creates a CommentRegexFilter that accepts comment nodes containing
* the specified string.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public CommentRegexFilter(String regex, boolean ignoreCase) {
super(regex, ignoreCase);
}
public boolean accept(Node node) {
if (node instanceof Remark) {
String nodestr = ((Remark)node).getText();
return isFilterMatch(nodestr, pat);
}
return false;
}
}
/** A regex filter that performs a regex replacement on matching nodes. */
public interface RegexXform {
void setReplace(String replace);
}
abstract static class BaseRegexXform
extends BaseRegexFilter
implements RegexXform {
protected CachedPattern targetPat;
protected String replace;
public BaseRegexXform(String regex, String target, String replace) {
this(regex, false, target, replace);
}
public BaseRegexXform(String regex, boolean ignoreCase,
String target, String replace) {
super(regex, ignoreCase);
this.targetPat = new CachedPattern(target);
this.replace = replace;
}
public void setReplace(String replace) {
this.replace = replace;
}
}
/**
* This class accepts everything but applies a transform to
* links that match the regex.
*/
public static class LinkRegexXform extends BaseRegexXform {
private String[] attrs;
/**
* Creates a LinkRegexXform that rejects everything but applies
* a transform to nodes whose text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
* @param attrs Attributes to process
*/
public LinkRegexXform(String regex, boolean ignoreCase,
String target, String replace, String[] attrs) {
super(regex, ignoreCase, target, replace);
this.attrs = attrs;
}
public boolean accept(Node node) {
if (node instanceof TagNode &&
!(node instanceof MetaTag)) {
for (int i = 0; i < attrs.length; i++) {
Attribute attribute = ((TagNode)node).getAttributeEx(attrs[i]);
if (attribute != null && attribute.getValue() != null) {
// Rewrite this attribute
String url = attribute.getValue();
if (isFilterMatch(url, pat)) {
if (log.isDebug3()) {
log.debug3("Attribute " + attribute.getName() + " old " + url +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newUrl = targetPat.getMatcher(url).replaceFirst(replace);
if (!newUrl.equals(url)) {
String encoded = urlEncode(newUrl);
attribute.setValue(encoded);
((TagNode)node).setAttributeEx(attribute);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
// return false;
}
}
}
return false;
}
}
private static final String importTag = "@import";
/**
* This class rejects everything but applies a transform to
* links is Style tags that match the regex.
* @deprecated Processes only @import; use {@link StyleTagXformDispatch}
* instead.
*/
@Deprecated
public static class StyleRegexXform extends BaseRegexXform {
/**
* Creates a StyleRegexXform that rejects everything but applies
* a transform to style nodes whose child text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
*/
public StyleRegexXform(String regex, boolean ignoreCase,
String target, String replace) {
super(regex, ignoreCase, target, replace);
}
public boolean accept(Node node) {
if (node instanceof StyleTag) {
try {
NodeIterator it;
nodeLoop:
for (it = ((StyleTag)node).children(); it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
// Find each instance of @import.*)
String text = ((TextNode)child).getText();
int startIx = 0;
while ((startIx = text.indexOf(importTag, startIx)) >= 0) {
int endIx = text.indexOf(')', startIx);
int delta = 0;
if (endIx < 0) {
log.error("Can't find close paren in " + text);
continue nodeLoop;
// return false;
}
String oldImport = text.substring(startIx, endIx + 1);
if (isFilterMatch(oldImport, pat)) {
String newImport = targetPat.getMatcher(oldImport).replaceFirst(replace);
if (!newImport.equals(oldImport)) {
String encoded = cssEncode(newImport);
delta = encoded.length() - oldImport.length();
String newText = text.substring(0, startIx) +
encoded + text.substring(endIx + 1);
if (log.isDebug3())
log.debug3("Import rewritten " + newText);
text = newText;
((TextNode)child).setText(text);
}
}
startIx = endIx + 1 + delta;
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
return false;
}
}
/**
* Base class for rewriting contents of style tag or attr
*/
public static class BaseStyleDispatch {
protected ArchivalUnit au;
protected String charset;
protected String baseUrl;
protected ServletUtil.LinkTransform xform;
protected LinkRewriterFactory lrf;
public BaseStyleDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
this.au = au;
if (charset == null) {
this.charset = Constants.DEFAULT_ENCODING;
} else {
this.charset = charset;
}
this.baseUrl = baseUrl;
this.xform = xform;
}
public void setBaseUrl(String newBase) {
baseUrl = newBase;
}
protected static String DEFAULT_STYLE_MIME_TYPE = "text/css";
protected String rewriteStyleDispatch(String text,
LinkRewriterFactory lrf,
String mime)
throws PluginException, IOException {
InputStream rewritten = null;
try {
rewritten =
lrf.createLinkRewriter(mime,
au,
new ReaderInputStream(new StringReader(text),
charset),
charset,
baseUrl,
xform);
String res =
StringUtil.fromReader(new InputStreamReader(rewritten, charset));
return res;
} finally {
IOUtil.safeClose(rewritten);
}
}
}
/**
* Rejects everything and applies a CSS LinkRewriter to the text in
* style tags
*/
public static class StyleTagXformDispatch
extends BaseStyleDispatch implements NodeFilter
{
public StyleTagXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
public boolean accept(Node node) {
if (node instanceof StyleTag) {
StyleTag tag = (StyleTag)node;
if (tag.getAttribute("src") != null) {
return false;
}
String mime = tag.getAttribute("type");
if (mime == null) {
// shouldn't happen - type attr is required
log.warning("<style> tag with no type attribute");
mime = DEFAULT_STYLE_MIME_TYPE;
}
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
for (NodeIterator it = (tag).children();
it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
TextNode textChild = (TextNode)child;
String source = textChild.getText();
if (!StringUtil.isNullString(source)) {
try {
String res = rewriteStyleDispatch(source, lrf, mime);
if (!res.equals(source)) {
if (log.isDebug3()) log.debug3("Style rewritten " + res);
textChild.setText(res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
}
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
}
return false;
}
}
/**
* @deprecated Here only to keep old class name used by
* taylorandfrancis.NodeFilterHtmlLinkRewriterFactory. Should be removed
* once no references.
*/
public static class StyleXformDispatch
extends StyleTagXformDispatch {
public StyleXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
}
/**
* Rejects everything and applies a CSS LinkRewriter to the text in
* style attributes
*/
public static class StyleAttrXformDispatch
extends BaseStyleDispatch implements NodeFilter {
public StyleAttrXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
public boolean accept(Node node) {
if (node instanceof TagNode &&
!(node instanceof MetaTag)) {
TagNode tag = (TagNode)node;
// Check for style attribute
Attribute attribute = tag.getAttributeEx("style");
if (attribute != null) {
String style = attribute.getValue();
// style attr is very common, invoking css rewriter is expensive,
// do only if evidence of URLs
if (style != null
&& StringUtil.indexOfIgnoreCase(style, "url(") >= 0) {
String mime = DEFAULT_STYLE_MIME_TYPE;
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
String res = rewriteStyleDispatch(style, lrf, mime);
if (!res.equals(style)) {
// res = BaseRegexFilter.urlEncode(res);
attribute.setValue(res);
tag.setAttributeEx(attribute);
if (log.isDebug3()) log.debug3("new " + res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
}
}
}
}
}
return false;
}
}
/**
* Rejects everything and applies a CSS LinkRewriter to the text in
* script tags
*/
public static class ScriptXformDispatch implements NodeFilter {
private ArchivalUnit au;
private String charset;
private String baseUrl;
private ServletUtil.LinkTransform xform;
public ScriptXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
this.au = au;
if (charset == null) {
this.charset = Constants.DEFAULT_ENCODING;
} else {
this.charset = charset;
}
this.baseUrl = baseUrl;
this.xform = xform;
}
public void setBaseUrl(String newBase) {
baseUrl = newBase;
}
static String DEFAULT_SCRIPT_MIME_TYPE = "text/javascript";
public boolean accept(Node node) {
if (node instanceof ScriptTag) {
ScriptTag tag = (ScriptTag)node;
if (tag.getAttribute("src") != null) {
return false;
}
String mime = tag.getAttribute("type");
if (mime == null) {
mime = tag.getAttribute("language");
if (mime != null) {
if (mime.indexOf("/") < 0) {
mime = "text/" + mime;
}
} else {
// shouldn't happen - type attr is required
log.warning("<script> tag with no type or language attribute");
mime = DEFAULT_SCRIPT_MIME_TYPE;
}
}
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
for (NodeIterator it = (tag).children();
it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
TextNode textChild = (TextNode)child;
String source = textChild.getText();
if (!StringUtil.isNullString(source)) {
InputStream rewritten = null;
try {
rewritten =
lrf.createLinkRewriter(mime,
au,
new ReaderInputStream(new StringReader(source),
charset),
charset,
baseUrl,
xform);
String res =
StringUtil.fromReader(new InputStreamReader(rewritten,
charset));
if (!res.equals(source)) {
if (log.isDebug3()) log.debug3("Script rewritten " + res);
textChild.setText(res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
} finally {
IOUtil.safeClose(rewritten);
}
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
}
return false;
}
}
/**
* This class rejects everything but applies a transform to
* meta refresh tags that match the regex.
*/
public static class RefreshRegexXform extends BaseRegexXform {
/**
* Creates a RefreshRegexXform that rejects everything but applies
* a transform to nodes whose text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
*/
public RefreshRegexXform(String regex, boolean ignoreCase,
String target, String replace) {
super(regex, ignoreCase, target, replace);
}
public boolean accept(Node node) {
if (node instanceof MetaTag) {
String equiv = ((MetaTag)node).getAttribute("http-equiv");
if ("refresh".equalsIgnoreCase(equiv)) {
String contentVal = ((MetaTag)node).getAttribute("content");
if (log.isDebug3()) log.debug3("RefreshRegexXform: " + contentVal);
if (contentVal != null && isFilterMatch(contentVal, pat)) {
// Rewrite the attribute
if (log.isDebug3()) {
log.debug3("Refresh old " + contentVal +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newVal = targetPat.getMatcher(contentVal).replaceFirst(replace);
if (!newVal.equals(contentVal)) {
String encoded = urlEncode(newVal);
((MetaTag)node).setAttribute("content", encoded);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
}
}
return false;
}
}
/**
* This class rejects everything but applies a transform to the content
* attr of meta tags whose name attr matches one of the supplied names.
*/
public static class MetaTagRegexXform extends BaseRegexXform {
private List<String> names;
/**
* Creates a MetaTagRegexXform that rejects everything but applies a
* transform to the content attr of meta tags whose name attr matches
* one of the supplied names.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
* @param names List of <code>name</code> attributes for which to
* rewrite the <code>content</code> URL.
*/
public MetaTagRegexXform(String regex, boolean ignoreCase,
String target, String replace,
List<String> names) {
super(regex, ignoreCase, target, replace);
this.names = names;
}
public boolean accept(Node node) {
if (node instanceof MetaTag) {
String nameVal = ((MetaTag)node).getAttribute("name");
if (names.contains(nameVal)) {
String contentVal = ((MetaTag)node).getAttribute("content");
if (log.isDebug3()) {
log.debug3("MetaTagRegexXform: " + nameVal
+ " = " + contentVal +
( isFilterMatch(contentVal, pat)
? " metches " : " does not match ") +
pat.getPattern());
}
if (contentVal != null && isFilterMatch(contentVal, pat)) {
// Rewrite the content attribute
if (log.isDebug3()) {
log.debug3("Meta old " + contentVal +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newVal =
targetPat.getMatcher(contentVal).replaceFirst(replace);
if (!newVal.equals(contentVal)) {
String encoded = urlEncode(newVal);
((MetaTag)node).setAttribute("content", encoded);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
}
}
return false;
}
}
/**
* This class accepts all composite nodes whose text contains a match for
* the regex.
*/
public static class CompositeRegexFilter extends BaseRegexFilter {
/**
* Creates a CompositeRegexFilter that accepts composite nodes whose
* text contains a match for the regex. The match is case sensitive.
* @param regex The pattern to match.
*/
public CompositeRegexFilter(String regex) {
super(regex);
}
/**
* Creates a CompositeRegexFilter that accepts composite nodes whose
* text contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public CompositeRegexFilter(String regex, boolean ignoreCase) {
super(regex, ignoreCase);
}
public boolean accept(Node node) {
if (node instanceof CompositeTag) {
String nodestr = getCompositeStringText((CompositeTag)node);
return isFilterMatch(nodestr, pat);
}
return false;
}
}
/**
* A filter that matches tags that have a specified attribute whose value
* matches a regex
*/
public static class HasAttributeRegexFilter extends BaseRegexFilter {
private String attr;
/**
* Creates a HasAttributeRegexFilter that accepts nodes whose specified
* attribute value matches a regex.
* The match is case insensitive.
* @param attr The attribute name
* @param regex The regex to match against the attribute value.
*/
public HasAttributeRegexFilter(String attr, String regex) {
this(attr, regex, true);
}
/**
* Creates a HasAttributeRegexFilter that accepts nodes whose specified
* attribute value matches a regex.
* @param attr The attribute name
* @param regex The regex to match against the attribute value.
* @param ignoreCase if true match is case insensitive
*/
public HasAttributeRegexFilter(String attr, String regex,
boolean ignoreCase) {
super(regex, ignoreCase);
this.attr = attr;
}
public boolean accept(Node node) {
if (node instanceof Tag) {
Tag tag = (Tag)node;
String attribute = tag.getAttribute(attr);
if (attribute != null) {
return isFilterMatch(attribute, pat);
}
}
return false;
}
}
/**
* <p>
* This node filter selects all nodes in a target tree (characterized by a
* target root node filter), except for the nodes in a designated subtree
* (characterized by a designated subtree node filter) and all nodes on the
* direct path from the target root to the designated subtree.
* </p>
* <p>
* If used as the underlying node filter of an
* {@link HtmlNodeFilterTransform#exclude(NodeFilter)} transform, everything
* in the target tree will be excluded except for the designated subtree and
* the direct path to it from the target root (just enough to retain the
* original structure).
* </p>
* <p>
* Sample document:
* </p>
<pre>
<div id="a1">
<div id="a11">
<div id="a111">...</div>
<div id="a112">...</div>
<div id="a113">...</div>
</div>
<div id="a12">
<div id="a121">
<div id="a1211">...</div>
<div id="a1212">...</div>
<div id="a1213">...</div>
</div>
<div id="a122">
<div id="a1221">...</div>
<div id="a1222">...</div>
<div id="a1223">...</div>
</div>
<div id="a123">
<div id="a1231">...</div>
<div id="a1232">...</div>
<div id="a1233">...</div>
</div>
</div>
<div id="a13">
<div id="a131">...</div>
<div id="a132">...</div>
<div id="a133">...</div>
</div>
</div>
</pre>
* <p>
* This code will focus its attention on the tree rooted at a12 but will
* protect the subtree rooted at a122, by selecting a121, a1211, a1212, a1213,
* a123, a1231, a1232, a1233, but not a122, a1221, a1222, a1223, nor a12, nor
* anything higher than a12 (like a11 and all its contents and a13 and all its
* contents):
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a12"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a122"));
</pre>
* <p>
* This code will select absolutely everything in the tree rooted at a12,
* because there is no subtree "a99" to protect, nor a path to it:
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a12"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a99"));
</pre>
* <p>
* This code will select absolutely nothing, because there is no target tree
* "a99" to flag:
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a99"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a122"));
</pre>
*
* @since 1.65.4
*/
public static class AllExceptSubtreeNodeFilter implements NodeFilter {
/**
* <p>
* A node filter characterizing the target root.
* </p>
*/
protected NodeFilter rootNodeFilter;
/**
* <p>
* A node filter characterizing the designated subtree.
* </p>
*/
protected NodeFilter subtreeNodeFilter;
/**
* <p>
* Builds a node filter that will select all nodes in the target tree
* (rooted at the node characterized by the target root node filter), except
* for the nodes in the designated subtree characterized by the subtree node
* filter and any nodes in the direct path from the target root node to the
* designated subtree.
* </p>
*
* @param rootNodeFilter
* A node filter characterizing the target root.
* @param subtreeNodeFilter
* A node filter characterizing the designated subtree.
*/
public AllExceptSubtreeNodeFilter(NodeFilter rootNodeFilter,
NodeFilter subtreeNodeFilter) {
this.rootNodeFilter = rootNodeFilter;
this.subtreeNodeFilter = subtreeNodeFilter;
}
@Override
public boolean accept(Node node) {
// Inspect the node's ancestors
for (Node current = node ; current != null ; current = current.getParent()) {
if (subtreeNodeFilter.accept(current)) {
// The node is in the designated subtree: don't select it (meaning,
// return false).
return false;
}
if (rootNodeFilter.accept(current)) {
// The node is in the target tree. Selecting it or not depends on
// whether it is on the path from the target root to the designated
// subtree or not.
NodeList nl = new NodeList();
node.collectInto(nl, subtreeNodeFilter);
// If the node list is empty, the node is not on the path from the
// target root to the designated subtree: select it (meaning, return
// true). If the node list is non-empty, the node is on the path from
// the target root to the designated subtree: don't select it
// (meaning, return false). In other words, return the result of
// asking if the node list is empty.
return nl.size() == 0;
}
}
// The node is not under the target root: don't select it (meaning,
// return false).
return false;
}
}
} | [
"public",
"class",
"HtmlNodeFilters",
"{",
"private",
"static",
"Logger",
"log",
"=",
"Logger",
".",
"getLogger",
"(",
"HtmlNodeFilters",
".",
"class",
")",
";",
"/** No instances */",
"private",
"HtmlNodeFilters",
"(",
")",
"{",
"}",
"/** Create a NodeFilter that matches tags. Equivalant to\n * <pre>new TagNameFilter(tag)</pre> */",
"public",
"static",
"NodeFilter",
"tag",
"(",
"String",
"tag",
")",
"{",
"return",
"new",
"TagNameFilter",
"(",
"tag",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * attribute value. Equivalant to\n * <pre>new AndFilter(new TagNameFilter(tag),\n new HasAttributeFilter(attr, val))</pre> */",
"public",
"static",
"NodeFilter",
"tagWithAttribute",
"(",
"String",
"tag",
",",
"String",
"attr",
",",
"String",
"val",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"HasAttributeFilter",
"(",
"attr",
",",
"val",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * that define a given attribute. Equivalant to\n * <pre>new AndFilter(new TagNameFilter(tag),\n new HasAttributeFilter(attr))</pre>\n * @since 1.32.0\n */",
"public",
"static",
"NodeFilter",
"tagWithAttribute",
"(",
"String",
"tag",
",",
"String",
"attr",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"HasAttributeFilter",
"(",
"attr",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches div tags with a specified\n * attribute value. Equivalant to\n * <pre>new AndFilter(new TagNameFilter(\"div\"),\n new HasAttributeFilter(attr, val))</pre> */",
"public",
"static",
"NodeFilter",
"divWithAttribute",
"(",
"String",
"attr",
",",
"String",
"val",
")",
"{",
"return",
"tagWithAttribute",
"(",
"\"",
"div",
"\"",
",",
"attr",
",",
"val",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * an attribute value matching a regex.\n * @param tag The tagname.\n * @param attr The attribute name.\n * @param valRegexp The pattern to match against the attribute value.\n */",
"public",
"static",
"NodeFilter",
"tagWithAttributeRegex",
"(",
"String",
"tag",
",",
"String",
"attr",
",",
"String",
"valRegexp",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"HasAttributeRegexFilter",
"(",
"attr",
",",
"valRegexp",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * an attribute value matching a regex.\n * @param tag The tagname.\n * @param attr The attribute name.\n * @param valRegexp The pattern to match against the attribute value.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"static",
"NodeFilter",
"tagWithAttributeRegex",
"(",
"String",
"tag",
",",
"String",
"attr",
",",
"String",
"valRegexp",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"HasAttributeRegexFilter",
"(",
"attr",
",",
"valRegexp",
",",
"ignoreCase",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * nested text containing a substring. <i>Eg,</i> in <code>\n * <select><option value=\"1\">Option text\n * 1</option>...</select></code>, <code>tagWithText(\"option\", \"Option text\") </code>would match the <code><option> </code>node.\n * @param tag The tagname.\n * @param text The nested text to match.\n */",
"public",
"static",
"NodeFilter",
"tagWithText",
"(",
"String",
"tag",
",",
"String",
"text",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"CompositeStringFilter",
"(",
"text",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * nested text containing a substring.\n * @param tag The tagname.\n * @param text The nested text to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"static",
"NodeFilter",
"tagWithText",
"(",
"String",
"tag",
",",
"String",
"text",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"CompositeStringFilter",
"(",
"text",
",",
"ignoreCase",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches composite tags with a specified\n * tagname and nested text matching a regex. <i>Eg</i>, <code>\n * @param tag The tagname.\n * @param regex The pattern to match against the nested text.\n */",
"public",
"static",
"NodeFilter",
"tagWithTextRegex",
"(",
"String",
"tag",
",",
"String",
"regex",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"CompositeRegexFilter",
"(",
"regex",
")",
")",
";",
"}",
"/** Create a NodeFilter that matches tags with a specified tagname and\n * nested text matching a regex. Equivalant to\n * <pre>new AndFilter(new TagNameFilter(tag),\n new RegexFilter(regex))</pre>\n * @param tag The tagname.\n * @param regex The pattern to match against the nested text.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"static",
"NodeFilter",
"tagWithTextRegex",
"(",
"String",
"tag",
",",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"new",
"TagNameFilter",
"(",
"tag",
")",
",",
"new",
"CompositeRegexFilter",
"(",
"regex",
",",
"ignoreCase",
")",
")",
";",
"}",
"/**\n * <p>\n * Returns a node filter that selects nodes that have an ancestor node that\n * matches the given ancestor node filter.\n * </p>\n * <p>\n * Note that this filter will match not only the node you might be thinking\n * of but also every node between it and the ancestor you might be thinking\n * of: you should combine it with another filter, probably an AndFilter, to\n * select only the node you might mean.\n * </p>\n * \n * @param ancestorFilter\n * A node filter to be applied to ancestors.\n * @return A node filter that returns true if and only if the examined node is\n * non-null and has an ancestor that matches the given ancestor node\n * filter.\n * @since 1.71\n */",
"public",
"static",
"NodeFilter",
"ancestor",
"(",
"final",
"NodeFilter",
"ancestorFilter",
")",
"{",
"return",
"new",
"NodeFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"==",
"null",
"||",
"!",
"(",
"node",
"instanceof",
"Tag",
")",
"||",
"(",
"(",
"Tag",
")",
"node",
")",
".",
"isEndTag",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"ancestor",
"=",
"node",
".",
"getParent",
"(",
")",
";",
"while",
"(",
"ancestor",
"!=",
"null",
"&&",
"ancestor",
"instanceof",
"Tag",
")",
"{",
"if",
"(",
"ancestorFilter",
".",
"accept",
"(",
"ancestor",
")",
")",
"{",
"return",
"true",
";",
"}",
"ancestor",
"=",
"ancestor",
".",
"getParent",
"(",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
";",
"}",
"/**\n * <p>\n * A node filter that matches any HTML comment.\n * </p>\n * \n * @return A node filter that matches HTML comment nodes.\n * @since 1.64\n */",
"public",
"static",
"NodeFilter",
"comment",
"(",
")",
"{",
"return",
"new",
"NodeFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"return",
"(",
"node",
"instanceof",
"Remark",
")",
";",
"}",
"}",
";",
"}",
"/**\n * Creates a NodeFilter that accepts comment nodes containing the\n * specified string. The match is case sensitive.\n * @param string The string to look for\n */",
"public",
"static",
"NodeFilter",
"commentWithString",
"(",
"String",
"string",
")",
"{",
"return",
"new",
"CommentStringFilter",
"(",
"string",
")",
";",
"}",
"/**\n * Creates a NodeFilter that accepts comment nodes containing the\n * specified string.\n * @param string The string to look for\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"static",
"NodeFilter",
"commentWithString",
"(",
"String",
"string",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"CommentStringFilter",
"(",
"string",
",",
"ignoreCase",
")",
";",
"}",
"/** Create a NodeFilter that matches html comments containing a match for\n * a specified regex. The match is case sensitive.\n * @param regex The pattern to match.\n */",
"public",
"static",
"NodeFilter",
"commentWithRegex",
"(",
"String",
"regex",
")",
"{",
"return",
"new",
"CommentRegexFilter",
"(",
"regex",
")",
";",
"}",
"/** Create a NodeFilter that matches html comments containing a match for\n * a specified regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"static",
"NodeFilter",
"commentWithRegex",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"return",
"new",
"CommentRegexFilter",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"}",
"/** Create a NodeFilter that matches the lowest level node that matches the\n * specified filter. This is useful for searching for text within a tag,\n * because the default is to match parent nodes as well.\n */",
"public",
"static",
"NodeFilter",
"lowestLevelMatchFilter",
"(",
"NodeFilter",
"filter",
")",
"{",
"return",
"new",
"AndFilter",
"(",
"filter",
",",
"new",
"NotFilter",
"(",
"new",
"HasChildFilter",
"(",
"filter",
",",
"true",
")",
")",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of LinkRegexYesXforms\n */",
"public",
"static",
"NodeFilter",
"linkRegexYesXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
",",
"String",
"[",
"]",
"attrs",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"filters",
"[",
"i",
"]",
"=",
"new",
"LinkRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
",",
"attrs",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of LinkRegexNoXforms\n */",
"public",
"static",
"NodeFilter",
"linkRegexNoXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
",",
"String",
"[",
"]",
"attrs",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"filters",
"[",
"i",
"]",
"=",
"new",
"LinkRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
",",
"attrs",
")",
".",
"setNegateFilter",
"(",
"true",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of MetaRegexYesXforms\n */",
"public",
"static",
"NodeFilter",
"metaTagRegexYesXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
",",
"List",
"<",
"String",
">",
"names",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"filters",
"[",
"i",
"]",
"=",
"new",
"MetaTagRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
",",
"names",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/**\n * <p>\n * Returns a node filter that selects tags whose immediate parent tag matches\n * the given parent node filter.\n * </p>\n * \n * @param parentFilter\n * A node filter to be applied to the immediate parent tag.\n * @return A node filter that returns true if and only if the examined node is\n * a non-null tag and has an immediate parent tag that matches the\n * given parent node filter.\n * @since 1.71\n */",
"public",
"static",
"NodeFilter",
"parent",
"(",
"final",
"NodeFilter",
"parentFilter",
")",
"{",
"return",
"new",
"NodeFilter",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"==",
"null",
"||",
"!",
"(",
"node",
"instanceof",
"Tag",
")",
"||",
"(",
"(",
"Tag",
")",
"node",
")",
".",
"isEndTag",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"Node",
"parent",
"=",
"node",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
"==",
"null",
"||",
"!",
"(",
"node",
"instanceof",
"Tag",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"parentFilter",
".",
"accept",
"(",
"parent",
")",
";",
"}",
"}",
";",
"}",
"/** Create a NodeFilter that applies all of an array of StyleRegexYesXforms\n */",
"public",
"static",
"NodeFilter",
"styleRegexYesXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"filters",
"[",
"i",
"]",
"=",
"new",
"StyleRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of StyleRegexNoXforms\n */",
"public",
"static",
"NodeFilter",
"styleRegexNoXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"filters",
"[",
"i",
"]",
"=",
"new",
"StyleRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
")",
".",
"setNegateFilter",
"(",
"true",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of RefreshRegexYesXforms\n */",
"public",
"static",
"NodeFilter",
"refreshRegexYesXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Build meta yes",
"\"",
"+",
"regex",
"[",
"i",
"]",
"+",
"\"",
" targ ",
"\"",
"+",
"target",
"[",
"i",
"]",
"+",
"\"",
" repl ",
"\"",
"+",
"replace",
"[",
"i",
"]",
")",
";",
"}",
"filters",
"[",
"i",
"]",
"=",
"new",
"RefreshRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that applies all of an array of RefreshRegexNoXforms\n */",
"public",
"static",
"NodeFilter",
"refreshRegexNoXforms",
"(",
"String",
"[",
"]",
"regex",
",",
"boolean",
"[",
"]",
"ignoreCase",
",",
"String",
"[",
"]",
"target",
",",
"String",
"[",
"]",
"replace",
")",
"{",
"NodeFilter",
"[",
"]",
"filters",
"=",
"new",
"NodeFilter",
"[",
"regex",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"regex",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Build meta no",
"\"",
"+",
"regex",
"[",
"i",
"]",
"+",
"\"",
" targ ",
"\"",
"+",
"target",
"[",
"i",
"]",
"+",
"\"",
" repl ",
"\"",
"+",
"replace",
"[",
"i",
"]",
")",
";",
"}",
"filters",
"[",
"i",
"]",
"=",
"new",
"RefreshRegexXform",
"(",
"regex",
"[",
"i",
"]",
",",
"ignoreCase",
"[",
"i",
"]",
",",
"target",
"[",
"i",
"]",
",",
"replace",
"[",
"i",
"]",
")",
".",
"setNegateFilter",
"(",
"true",
")",
";",
"}",
"return",
"new",
"OrFilter",
"(",
"filters",
")",
";",
"}",
"/** Create a NodeFilter that matches all parts of a subtree except for a\n * subtree contained within it. This is useful for removing a section of\n * a document except for one or more of its subsections. See {@link\n * AllExceptSubtreeNodeFilter}.\n */",
"public",
"static",
"NodeFilter",
"allExceptSubtree",
"(",
"NodeFilter",
"rootNodeFilter",
",",
"NodeFilter",
"subtreeNodeFilter",
")",
"{",
"return",
"new",
"AllExceptSubtreeNodeFilter",
"(",
"rootNodeFilter",
",",
"subtreeNodeFilter",
")",
";",
"}",
"static",
"String",
"getCompositeStringText",
"(",
"CompositeTag",
"node",
")",
"{",
"if",
"(",
"node",
".",
"getEndTag",
"(",
")",
"!=",
"null",
"&&",
"node",
".",
"getEndPosition",
"(",
")",
"<",
"node",
".",
"getEndTag",
"(",
")",
".",
"getStartPosition",
"(",
")",
")",
"{",
"return",
"node",
".",
"getStringText",
"(",
")",
";",
"}",
"return",
"\"",
"\"",
";",
"}",
"/**\n * This class accepts all comment nodes containing the given string.\n */",
"public",
"static",
"class",
"CommentStringFilter",
"implements",
"NodeFilter",
"{",
"private",
"String",
"string",
";",
"private",
"boolean",
"ignoreCase",
"=",
"false",
";",
"/**\n * Creates a CommentStringFilter that accepts comment nodes containing\n * the specified string. The match is case sensitive.\n * @param substring The string to look for\n */",
"public",
"CommentStringFilter",
"(",
"String",
"substring",
")",
"{",
"this",
"(",
"substring",
",",
"false",
")",
";",
"}",
"/**\n * Creates a CommentStringFilter that accepts comment nodes containing\n * the specified string.\n * @param substring The string to look for\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CommentStringFilter",
"(",
"String",
"substring",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"string",
"=",
"substring",
";",
"this",
".",
"ignoreCase",
"=",
"ignoreCase",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Remark",
")",
"{",
"String",
"nodestr",
"=",
"(",
"(",
"Remark",
")",
"node",
")",
".",
"getText",
"(",
")",
";",
"return",
"-",
"1",
"!=",
"(",
"ignoreCase",
"?",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"nodestr",
",",
"string",
")",
":",
"nodestr",
".",
"indexOf",
"(",
"string",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * This class accepts all composite nodes containing the given string.\n */",
"public",
"static",
"class",
"CompositeStringFilter",
"implements",
"NodeFilter",
"{",
"private",
"String",
"string",
";",
"private",
"boolean",
"ignoreCase",
"=",
"false",
";",
"/**\n * Creates a CompositeStringFilter that accepts composite nodes\n * containing the specified string. The match is case sensitive.\n * @param substring The string to look for\n */",
"public",
"CompositeStringFilter",
"(",
"String",
"substring",
")",
"{",
"this",
"(",
"substring",
",",
"false",
")",
";",
"}",
"/**\n * Creates a CompositeStringFilter that accepts composite nodes\n * containing the specified string.\n * @param substring The string to look for\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CompositeStringFilter",
"(",
"String",
"substring",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"string",
"=",
"substring",
";",
"this",
".",
"ignoreCase",
"=",
"ignoreCase",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"CompositeTag",
")",
"{",
"String",
"nodestr",
"=",
"getCompositeStringText",
"(",
"(",
"CompositeTag",
")",
"node",
")",
";",
"return",
"-",
"1",
"!=",
"(",
"ignoreCase",
"?",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"nodestr",
",",
"string",
")",
":",
"nodestr",
".",
"indexOf",
"(",
"string",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * Abstract class for regex filters\n */",
"public",
"abstract",
"static",
"class",
"BaseRegexFilter",
"implements",
"NodeFilter",
"{",
"protected",
"CachedPattern",
"pat",
";",
"protected",
"boolean",
"negateFilter",
"=",
"false",
";",
"/**\n * Creates a BaseRegexFilter that performs a case sensitive match for\n * the specified regex\n * @param regex The pattern to match.\n */",
"public",
"BaseRegexFilter",
"(",
"String",
"regex",
")",
"{",
"this",
"(",
"regex",
",",
"false",
")",
";",
"}",
"/**\n * Creates a BaseRegexFilter that performs a match for\n * the specified regex\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"BaseRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"pat",
"=",
"new",
"CachedPattern",
"(",
"regex",
")",
";",
"if",
"(",
"ignoreCase",
")",
"{",
"pat",
".",
"setIgnoreCase",
"(",
"true",
")",
";",
"}",
"}",
"public",
"BaseRegexFilter",
"setNegateFilter",
"(",
"boolean",
"val",
")",
"{",
"negateFilter",
"=",
"val",
";",
"return",
"this",
";",
"}",
"protected",
"boolean",
"isFilterMatch",
"(",
"String",
"str",
",",
"CachedPattern",
"pat",
")",
"{",
"boolean",
"isMatch",
"=",
"pat",
".",
"getMatcher",
"(",
"str",
")",
".",
"find",
"(",
")",
";",
"return",
"negateFilter",
"?",
"!",
"isMatch",
":",
"isMatch",
";",
"}",
"public",
"abstract",
"boolean",
"accept",
"(",
"Node",
"node",
")",
";",
"/**\n * URL encode the part of url that represents the original URL\n * @param url the string including the rewritten URL\n * @return the content of url with the original url encoded\n */",
"private",
"static",
"final",
"String",
"tag",
"=",
"\"",
"?url=",
"\"",
";",
"protected",
"String",
"urlEncode",
"(",
"String",
"url",
")",
"{",
"return",
"urlEncode",
"(",
"url",
",",
"false",
")",
";",
"}",
"protected",
"String",
"cssEncode",
"(",
"String",
"url",
")",
"{",
"return",
"urlEncode",
"(",
"url",
",",
"true",
")",
";",
"}",
"protected",
"String",
"urlEncode",
"(",
"String",
"url",
",",
"boolean",
"isCss",
")",
"{",
"int",
"startIx",
"=",
"url",
".",
"indexOf",
"(",
"tag",
")",
";",
"if",
"(",
"startIx",
"<",
"0",
")",
"{",
"log",
".",
"warning",
"(",
"\"",
"urlEncode: no tag (",
"\"",
"+",
"tag",
"+",
"\"",
") in ",
"\"",
"+",
"url",
")",
";",
"return",
"url",
";",
"}",
"startIx",
"+=",
"tag",
".",
"length",
"(",
")",
";",
"String",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
")",
";",
"if",
"(",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"http%",
"\"",
")",
"||",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"ftp%",
"\"",
")",
"||",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"https%",
"\"",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"not encoding ",
"\"",
"+",
"url",
")",
";",
"return",
"url",
";",
"}",
"int",
"endIx",
"=",
"url",
".",
"indexOf",
"(",
"'\"'",
",",
"startIx",
")",
";",
"if",
"(",
"endIx",
">",
"startIx",
")",
"{",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
",",
"endIx",
")",
";",
"}",
"else",
"if",
"(",
"isCss",
"&&",
"(",
"endIx",
"=",
"url",
".",
"indexOf",
"(",
"')'",
",",
"startIx",
")",
")",
">",
"startIx",
")",
"{",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
",",
"endIx",
")",
";",
"}",
"else",
"{",
"endIx",
"=",
"-",
"1",
";",
"}",
"int",
"hashpos",
"=",
"oldUrl",
".",
"indexOf",
"(",
"'#'",
")",
";",
"String",
"hashref",
"=",
"null",
";",
"if",
"(",
"hashpos",
">=",
"0",
")",
"{",
"hashref",
"=",
"oldUrl",
".",
"substring",
"(",
"hashpos",
")",
";",
"oldUrl",
"=",
"oldUrl",
".",
"substring",
"(",
"0",
",",
"hashpos",
")",
";",
"}",
"String",
"newUrl",
"=",
"UrlUtil",
".",
"encodeUrl",
"(",
"oldUrl",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"urlEncode: ",
"\"",
"+",
"oldUrl",
"+",
"\"",
" -> ",
"\"",
"+",
"newUrl",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"url",
",",
"0",
",",
"startIx",
")",
";",
"sb",
".",
"append",
"(",
"newUrl",
")",
";",
"if",
"(",
"hashref",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"hashref",
")",
";",
"}",
"if",
"(",
"endIx",
">=",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"url",
".",
"substring",
"(",
"endIx",
",",
"url",
".",
"length",
"(",
")",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}",
"/**\n * This class accepts all comment nodes whose text contains a match for\n * the regex.\n */",
"public",
"static",
"class",
"CommentRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"/**\n * Creates a CommentRegexFilter that accepts comment nodes whose text\n * contains a match for the regex. The match is case sensitive.\n * @param regex The pattern to match.\n */",
"public",
"CommentRegexFilter",
"(",
"String",
"regex",
")",
"{",
"super",
"(",
"regex",
")",
";",
"}",
"/**\n * Creates a CommentRegexFilter that accepts comment nodes containing\n * the specified string.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CommentRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Remark",
")",
"{",
"String",
"nodestr",
"=",
"(",
"(",
"Remark",
")",
"node",
")",
".",
"getText",
"(",
")",
";",
"return",
"isFilterMatch",
"(",
"nodestr",
",",
"pat",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"/** A regex filter that performs a regex replacement on matching nodes. */",
"public",
"interface",
"RegexXform",
"{",
"void",
"setReplace",
"(",
"String",
"replace",
")",
";",
"}",
"abstract",
"static",
"class",
"BaseRegexXform",
"extends",
"BaseRegexFilter",
"implements",
"RegexXform",
"{",
"protected",
"CachedPattern",
"targetPat",
";",
"protected",
"String",
"replace",
";",
"public",
"BaseRegexXform",
"(",
"String",
"regex",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"this",
"(",
"regex",
",",
"false",
",",
"target",
",",
"replace",
")",
";",
"}",
"public",
"BaseRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"this",
".",
"targetPat",
"=",
"new",
"CachedPattern",
"(",
"target",
")",
";",
"this",
".",
"replace",
"=",
"replace",
";",
"}",
"public",
"void",
"setReplace",
"(",
"String",
"replace",
")",
"{",
"this",
".",
"replace",
"=",
"replace",
";",
"}",
"}",
"/**\n * This class accepts everything but applies a transform to\n * links that match the regex.\n */",
"public",
"static",
"class",
"LinkRegexXform",
"extends",
"BaseRegexXform",
"{",
"private",
"String",
"[",
"]",
"attrs",
";",
"/**\n * Creates a LinkRegexXform that rejects everything but applies\n * a transform to nodes whose text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n * @param attrs Attributes to process\n */",
"public",
"LinkRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
",",
"String",
"[",
"]",
"attrs",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"this",
".",
"attrs",
"=",
"attrs",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"TagNode",
"&&",
"!",
"(",
"node",
"instanceof",
"MetaTag",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attrs",
".",
"length",
";",
"i",
"++",
")",
"{",
"Attribute",
"attribute",
"=",
"(",
"(",
"TagNode",
")",
"node",
")",
".",
"getAttributeEx",
"(",
"attrs",
"[",
"i",
"]",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
"&&",
"attribute",
".",
"getValue",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"url",
"=",
"attribute",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"isFilterMatch",
"(",
"url",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Attribute ",
"\"",
"+",
"attribute",
".",
"getName",
"(",
")",
"+",
"\"",
" old ",
"\"",
"+",
"url",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newUrl",
"=",
"targetPat",
".",
"getMatcher",
"(",
"url",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newUrl",
".",
"equals",
"(",
"url",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newUrl",
")",
";",
"attribute",
".",
"setValue",
"(",
"encoded",
")",
";",
"(",
"(",
"TagNode",
")",
"node",
")",
".",
"setAttributeEx",
"(",
"attribute",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"private",
"static",
"final",
"String",
"importTag",
"=",
"\"",
"@import",
"\"",
";",
"/**\n * This class rejects everything but applies a transform to\n * links is Style tags that match the regex.\n * @deprecated Processes only @import; use {@link StyleTagXformDispatch}\n * instead.\n */",
"@",
"Deprecated",
"public",
"static",
"class",
"StyleRegexXform",
"extends",
"BaseRegexXform",
"{",
"/**\n * Creates a StyleRegexXform that rejects everything but applies\n * a transform to style nodes whose child text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n */",
"public",
"StyleRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"StyleTag",
")",
"{",
"try",
"{",
"NodeIterator",
"it",
";",
"nodeLoop",
":",
"for",
"(",
"it",
"=",
"(",
"(",
"StyleTag",
")",
"node",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"String",
"text",
"=",
"(",
"(",
"TextNode",
")",
"child",
")",
".",
"getText",
"(",
")",
";",
"int",
"startIx",
"=",
"0",
";",
"while",
"(",
"(",
"startIx",
"=",
"text",
".",
"indexOf",
"(",
"importTag",
",",
"startIx",
")",
")",
">=",
"0",
")",
"{",
"int",
"endIx",
"=",
"text",
".",
"indexOf",
"(",
"')'",
",",
"startIx",
")",
";",
"int",
"delta",
"=",
"0",
";",
"if",
"(",
"endIx",
"<",
"0",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't find close paren in ",
"\"",
"+",
"text",
")",
";",
"continue",
"nodeLoop",
";",
"}",
"String",
"oldImport",
"=",
"text",
".",
"substring",
"(",
"startIx",
",",
"endIx",
"+",
"1",
")",
";",
"if",
"(",
"isFilterMatch",
"(",
"oldImport",
",",
"pat",
")",
")",
"{",
"String",
"newImport",
"=",
"targetPat",
".",
"getMatcher",
"(",
"oldImport",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newImport",
".",
"equals",
"(",
"oldImport",
")",
")",
"{",
"String",
"encoded",
"=",
"cssEncode",
"(",
"newImport",
")",
";",
"delta",
"=",
"encoded",
".",
"length",
"(",
")",
"-",
"oldImport",
".",
"length",
"(",
")",
";",
"String",
"newText",
"=",
"text",
".",
"substring",
"(",
"0",
",",
"startIx",
")",
"+",
"encoded",
"+",
"text",
".",
"substring",
"(",
"endIx",
"+",
"1",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Import rewritten ",
"\"",
"+",
"newText",
")",
";",
"text",
"=",
"newText",
";",
"(",
"(",
"TextNode",
")",
"child",
")",
".",
"setText",
"(",
"text",
")",
";",
"}",
"}",
"startIx",
"=",
"endIx",
"+",
"1",
"+",
"delta",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * Base class for rewriting contents of style tag or attr\n */",
"public",
"static",
"class",
"BaseStyleDispatch",
"{",
"protected",
"ArchivalUnit",
"au",
";",
"protected",
"String",
"charset",
";",
"protected",
"String",
"baseUrl",
";",
"protected",
"ServletUtil",
".",
"LinkTransform",
"xform",
";",
"protected",
"LinkRewriterFactory",
"lrf",
";",
"public",
"BaseStyleDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"this",
".",
"au",
"=",
"au",
";",
"if",
"(",
"charset",
"==",
"null",
")",
"{",
"this",
".",
"charset",
"=",
"Constants",
".",
"DEFAULT_ENCODING",
";",
"}",
"else",
"{",
"this",
".",
"charset",
"=",
"charset",
";",
"}",
"this",
".",
"baseUrl",
"=",
"baseUrl",
";",
"this",
".",
"xform",
"=",
"xform",
";",
"}",
"public",
"void",
"setBaseUrl",
"(",
"String",
"newBase",
")",
"{",
"baseUrl",
"=",
"newBase",
";",
"}",
"protected",
"static",
"String",
"DEFAULT_STYLE_MIME_TYPE",
"=",
"\"",
"text/css",
"\"",
";",
"protected",
"String",
"rewriteStyleDispatch",
"(",
"String",
"text",
",",
"LinkRewriterFactory",
"lrf",
",",
"String",
"mime",
")",
"throws",
"PluginException",
",",
"IOException",
"{",
"InputStream",
"rewritten",
"=",
"null",
";",
"try",
"{",
"rewritten",
"=",
"lrf",
".",
"createLinkRewriter",
"(",
"mime",
",",
"au",
",",
"new",
"ReaderInputStream",
"(",
"new",
"StringReader",
"(",
"text",
")",
",",
"charset",
")",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"String",
"res",
"=",
"StringUtil",
".",
"fromReader",
"(",
"new",
"InputStreamReader",
"(",
"rewritten",
",",
"charset",
")",
")",
";",
"return",
"res",
";",
"}",
"finally",
"{",
"IOUtil",
".",
"safeClose",
"(",
"rewritten",
")",
";",
"}",
"}",
"}",
"/**\n * Rejects everything and applies a CSS LinkRewriter to the text in\n * style tags\n */",
"public",
"static",
"class",
"StyleTagXformDispatch",
"extends",
"BaseStyleDispatch",
"implements",
"NodeFilter",
"{",
"public",
"StyleTagXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"StyleTag",
")",
"{",
"StyleTag",
"tag",
"=",
"(",
"StyleTag",
")",
"node",
";",
"if",
"(",
"tag",
".",
"getAttribute",
"(",
"\"",
"src",
"\"",
")",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"String",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"type",
"\"",
")",
";",
"if",
"(",
"mime",
"==",
"null",
")",
"{",
"log",
".",
"warning",
"(",
"\"",
"<style> tag with no type attribute",
"\"",
")",
";",
"mime",
"=",
"DEFAULT_STYLE_MIME_TYPE",
";",
"}",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"for",
"(",
"NodeIterator",
"it",
"=",
"(",
"tag",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"TextNode",
"textChild",
"=",
"(",
"TextNode",
")",
"child",
";",
"String",
"source",
"=",
"textChild",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isNullString",
"(",
"source",
")",
")",
"{",
"try",
"{",
"String",
"res",
"=",
"rewriteStyleDispatch",
"(",
"source",
",",
"lrf",
",",
"mime",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"source",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Style rewritten ",
"\"",
"+",
"res",
")",
";",
"textChild",
".",
"setText",
"(",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * @deprecated Here only to keep old class name used by\n * taylorandfrancis.NodeFilterHtmlLinkRewriterFactory. Should be removed\n * once no references.\n */",
"public",
"static",
"class",
"StyleXformDispatch",
"extends",
"StyleTagXformDispatch",
"{",
"public",
"StyleXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"}",
"/**\n * Rejects everything and applies a CSS LinkRewriter to the text in\n * style attributes\n */",
"public",
"static",
"class",
"StyleAttrXformDispatch",
"extends",
"BaseStyleDispatch",
"implements",
"NodeFilter",
"{",
"public",
"StyleAttrXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"TagNode",
"&&",
"!",
"(",
"node",
"instanceof",
"MetaTag",
")",
")",
"{",
"TagNode",
"tag",
"=",
"(",
"TagNode",
")",
"node",
";",
"Attribute",
"attribute",
"=",
"tag",
".",
"getAttributeEx",
"(",
"\"",
"style",
"\"",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
")",
"{",
"String",
"style",
"=",
"attribute",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"style",
"!=",
"null",
"&&",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"style",
",",
"\"",
"url(",
"\"",
")",
">=",
"0",
")",
"{",
"String",
"mime",
"=",
"DEFAULT_STYLE_MIME_TYPE",
";",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"String",
"res",
"=",
"rewriteStyleDispatch",
"(",
"style",
",",
"lrf",
",",
"mime",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"style",
")",
")",
"{",
"attribute",
".",
"setValue",
"(",
"res",
")",
";",
"tag",
".",
"setAttributeEx",
"(",
"attribute",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * Rejects everything and applies a CSS LinkRewriter to the text in\n * script tags\n */",
"public",
"static",
"class",
"ScriptXformDispatch",
"implements",
"NodeFilter",
"{",
"private",
"ArchivalUnit",
"au",
";",
"private",
"String",
"charset",
";",
"private",
"String",
"baseUrl",
";",
"private",
"ServletUtil",
".",
"LinkTransform",
"xform",
";",
"public",
"ScriptXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"this",
".",
"au",
"=",
"au",
";",
"if",
"(",
"charset",
"==",
"null",
")",
"{",
"this",
".",
"charset",
"=",
"Constants",
".",
"DEFAULT_ENCODING",
";",
"}",
"else",
"{",
"this",
".",
"charset",
"=",
"charset",
";",
"}",
"this",
".",
"baseUrl",
"=",
"baseUrl",
";",
"this",
".",
"xform",
"=",
"xform",
";",
"}",
"public",
"void",
"setBaseUrl",
"(",
"String",
"newBase",
")",
"{",
"baseUrl",
"=",
"newBase",
";",
"}",
"static",
"String",
"DEFAULT_SCRIPT_MIME_TYPE",
"=",
"\"",
"text/javascript",
"\"",
";",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"ScriptTag",
")",
"{",
"ScriptTag",
"tag",
"=",
"(",
"ScriptTag",
")",
"node",
";",
"if",
"(",
"tag",
".",
"getAttribute",
"(",
"\"",
"src",
"\"",
")",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"String",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"type",
"\"",
")",
";",
"if",
"(",
"mime",
"==",
"null",
")",
"{",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"language",
"\"",
")",
";",
"if",
"(",
"mime",
"!=",
"null",
")",
"{",
"if",
"(",
"mime",
".",
"indexOf",
"(",
"\"",
"/",
"\"",
")",
"<",
"0",
")",
"{",
"mime",
"=",
"\"",
"text/",
"\"",
"+",
"mime",
";",
"}",
"}",
"else",
"{",
"log",
".",
"warning",
"(",
"\"",
"<script> tag with no type or language attribute",
"\"",
")",
";",
"mime",
"=",
"DEFAULT_SCRIPT_MIME_TYPE",
";",
"}",
"}",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"for",
"(",
"NodeIterator",
"it",
"=",
"(",
"tag",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"TextNode",
"textChild",
"=",
"(",
"TextNode",
")",
"child",
";",
"String",
"source",
"=",
"textChild",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isNullString",
"(",
"source",
")",
")",
"{",
"InputStream",
"rewritten",
"=",
"null",
";",
"try",
"{",
"rewritten",
"=",
"lrf",
".",
"createLinkRewriter",
"(",
"mime",
",",
"au",
",",
"new",
"ReaderInputStream",
"(",
"new",
"StringReader",
"(",
"source",
")",
",",
"charset",
")",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"String",
"res",
"=",
"StringUtil",
".",
"fromReader",
"(",
"new",
"InputStreamReader",
"(",
"rewritten",
",",
"charset",
")",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"source",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Script rewritten ",
"\"",
"+",
"res",
")",
";",
"textChild",
".",
"setText",
"(",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtil",
".",
"safeClose",
"(",
"rewritten",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * This class rejects everything but applies a transform to\n * meta refresh tags that match the regex.\n */",
"public",
"static",
"class",
"RefreshRegexXform",
"extends",
"BaseRegexXform",
"{",
"/**\n * Creates a RefreshRegexXform that rejects everything but applies\n * a transform to nodes whose text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n */",
"public",
"RefreshRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"MetaTag",
")",
"{",
"String",
"equiv",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"http-equiv",
"\"",
")",
";",
"if",
"(",
"\"",
"refresh",
"\"",
".",
"equalsIgnoreCase",
"(",
"equiv",
")",
")",
"{",
"String",
"contentVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"content",
"\"",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"RefreshRegexXform: ",
"\"",
"+",
"contentVal",
")",
";",
"if",
"(",
"contentVal",
"!=",
"null",
"&&",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Refresh old ",
"\"",
"+",
"contentVal",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newVal",
"=",
"targetPat",
".",
"getMatcher",
"(",
"contentVal",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newVal",
".",
"equals",
"(",
"contentVal",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newVal",
")",
";",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"setAttribute",
"(",
"\"",
"content",
"\"",
",",
"encoded",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * This class rejects everything but applies a transform to the content\n * attr of meta tags whose name attr matches one of the supplied names.\n */",
"public",
"static",
"class",
"MetaTagRegexXform",
"extends",
"BaseRegexXform",
"{",
"private",
"List",
"<",
"String",
">",
"names",
";",
"/**\n * Creates a MetaTagRegexXform that rejects everything but applies a\n * transform to the content attr of meta tags whose name attr matches\n * one of the supplied names.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n * @param names List of <code>name</code> attributes for which to\n * rewrite the <code>content</code> URL.\n */",
"public",
"MetaTagRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
",",
"List",
"<",
"String",
">",
"names",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"this",
".",
"names",
"=",
"names",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"MetaTag",
")",
"{",
"String",
"nameVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"name",
"\"",
")",
";",
"if",
"(",
"names",
".",
"contains",
"(",
"nameVal",
")",
")",
"{",
"String",
"contentVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"content",
"\"",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"MetaTagRegexXform: ",
"\"",
"+",
"nameVal",
"+",
"\"",
" = ",
"\"",
"+",
"contentVal",
"+",
"(",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
"?",
"\"",
" metches ",
"\"",
":",
"\"",
" does not match ",
"\"",
")",
"+",
"pat",
".",
"getPattern",
"(",
")",
")",
";",
"}",
"if",
"(",
"contentVal",
"!=",
"null",
"&&",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Meta old ",
"\"",
"+",
"contentVal",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newVal",
"=",
"targetPat",
".",
"getMatcher",
"(",
"contentVal",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newVal",
".",
"equals",
"(",
"contentVal",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newVal",
")",
";",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"setAttribute",
"(",
"\"",
"content",
"\"",
",",
"encoded",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * This class accepts all composite nodes whose text contains a match for\n * the regex.\n */",
"public",
"static",
"class",
"CompositeRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"/**\n * Creates a CompositeRegexFilter that accepts composite nodes whose\n * text contains a match for the regex. The match is case sensitive.\n * @param regex The pattern to match.\n */",
"public",
"CompositeRegexFilter",
"(",
"String",
"regex",
")",
"{",
"super",
"(",
"regex",
")",
";",
"}",
"/**\n * Creates a CompositeRegexFilter that accepts composite nodes whose\n * text contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CompositeRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"CompositeTag",
")",
"{",
"String",
"nodestr",
"=",
"getCompositeStringText",
"(",
"(",
"CompositeTag",
")",
"node",
")",
";",
"return",
"isFilterMatch",
"(",
"nodestr",
",",
"pat",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * A filter that matches tags that have a specified attribute whose value\n * matches a regex\n */",
"public",
"static",
"class",
"HasAttributeRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"private",
"String",
"attr",
";",
"/**\n * Creates a HasAttributeRegexFilter that accepts nodes whose specified\n * attribute value matches a regex.\n * The match is case insensitive.\n * @param attr The attribute name\n * @param regex The regex to match against the attribute value.\n */",
"public",
"HasAttributeRegexFilter",
"(",
"String",
"attr",
",",
"String",
"regex",
")",
"{",
"this",
"(",
"attr",
",",
"regex",
",",
"true",
")",
";",
"}",
"/**\n * Creates a HasAttributeRegexFilter that accepts nodes whose specified\n * attribute value matches a regex.\n * @param attr The attribute name\n * @param regex The regex to match against the attribute value.\n * @param ignoreCase if true match is case insensitive\n */",
"public",
"HasAttributeRegexFilter",
"(",
"String",
"attr",
",",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"this",
".",
"attr",
"=",
"attr",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Tag",
")",
"{",
"Tag",
"tag",
"=",
"(",
"Tag",
")",
"node",
";",
"String",
"attribute",
"=",
"tag",
".",
"getAttribute",
"(",
"attr",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
")",
"{",
"return",
"isFilterMatch",
"(",
"attribute",
",",
"pat",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"/**\n * <p>\n * This node filter selects all nodes in a target tree (characterized by a\n * target root node filter), except for the nodes in a designated subtree\n * (characterized by a designated subtree node filter) and all nodes on the\n * direct path from the target root to the designated subtree.\n * </p>\n * <p>\n * If used as the underlying node filter of an\n * {@link HtmlNodeFilterTransform#exclude(NodeFilter)} transform, everything\n * in the target tree will be excluded except for the designated subtree and\n * the direct path to it from the target root (just enough to retain the\n * original structure).\n * </p>\n * <p>\n * Sample document:\n * </p>\n<pre>\n<div id=\"a1\">\n <div id=\"a11\">\n <div id=\"a111\">...</div>\n <div id=\"a112\">...</div>\n <div id=\"a113\">...</div>\n </div>\n <div id=\"a12\">\n <div id=\"a121\">\n <div id=\"a1211\">...</div>\n <div id=\"a1212\">...</div>\n <div id=\"a1213\">...</div>\n </div>\n <div id=\"a122\">\n <div id=\"a1221\">...</div>\n <div id=\"a1222\">...</div>\n <div id=\"a1223\">...</div>\n </div>\n <div id=\"a123\">\n <div id=\"a1231\">...</div>\n <div id=\"a1232\">...</div>\n <div id=\"a1233\">...</div>\n </div>\n </div>\n <div id=\"a13\">\n <div id=\"a131\">...</div>\n <div id=\"a132\">...</div>\n <div id=\"a133\">...</div>\n </div>\n</div>\n</pre>\n * <p>\n * This code will focus its attention on the tree rooted at a12 but will\n * protect the subtree rooted at a122, by selecting a121, a1211, a1212, a1213,\n * a123, a1231, a1232, a1233, but not a122, a1221, a1222, a1223, nor a12, nor\n * anything higher than a12 (like a11 and all its contents and a13 and all its\n * contents):\n * </p>\n<pre>\n NodeFilter nf =\n new AllExceptSubtreeNodeFilter(\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a12\"),\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a122\"));\n</pre>\n * <p>\n * This code will select absolutely everything in the tree rooted at a12,\n * because there is no subtree \"a99\" to protect, nor a path to it:\n * </p>\n<pre>\n NodeFilter nf =\n new AllExceptSubtreeNodeFilter(\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a12\"),\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a99\"));\n</pre>\n * <p>\n * This code will select absolutely nothing, because there is no target tree\n * \"a99\" to flag:\n * </p>\n<pre>\n NodeFilter nf =\n new AllExceptSubtreeNodeFilter(\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a99\"),\n HtmlNodeFilters.tagWithAttribute(\"div\", \"id\", \"a122\"));\n</pre>\n * \n * @since 1.65.4\n */",
"public",
"static",
"class",
"AllExceptSubtreeNodeFilter",
"implements",
"NodeFilter",
"{",
"/**\n * <p>\n * A node filter characterizing the target root.\n * </p>\n */",
"protected",
"NodeFilter",
"rootNodeFilter",
";",
"/**\n * <p>\n * A node filter characterizing the designated subtree.\n * </p>\n */",
"protected",
"NodeFilter",
"subtreeNodeFilter",
";",
"/**\n * <p>\n * Builds a node filter that will select all nodes in the target tree\n * (rooted at the node characterized by the target root node filter), except\n * for the nodes in the designated subtree characterized by the subtree node\n * filter and any nodes in the direct path from the target root node to the\n * designated subtree.\n * </p>\n * \n * @param rootNodeFilter\n * A node filter characterizing the target root.\n * @param subtreeNodeFilter\n * A node filter characterizing the designated subtree.\n */",
"public",
"AllExceptSubtreeNodeFilter",
"(",
"NodeFilter",
"rootNodeFilter",
",",
"NodeFilter",
"subtreeNodeFilter",
")",
"{",
"this",
".",
"rootNodeFilter",
"=",
"rootNodeFilter",
";",
"this",
".",
"subtreeNodeFilter",
"=",
"subtreeNodeFilter",
";",
"}",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"for",
"(",
"Node",
"current",
"=",
"node",
";",
"current",
"!=",
"null",
";",
"current",
"=",
"current",
".",
"getParent",
"(",
")",
")",
"{",
"if",
"(",
"subtreeNodeFilter",
".",
"accept",
"(",
"current",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"rootNodeFilter",
".",
"accept",
"(",
"current",
")",
")",
"{",
"NodeList",
"nl",
"=",
"new",
"NodeList",
"(",
")",
";",
"node",
".",
"collectInto",
"(",
"nl",
",",
"subtreeNodeFilter",
")",
";",
"return",
"nl",
".",
"size",
"(",
")",
"==",
"0",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}",
"}"
] | Factory methods for making various useful combinations of NodeFilters,
and additional {@link NodeFilter}s to supplement those in
{@link org.htmlparser.filters} | [
"Factory",
"methods",
"for",
"making",
"various",
"useful",
"combinations",
"of",
"NodeFilters",
"and",
"additional",
"{",
"@link",
"NodeFilter",
"}",
"s",
"to",
"supplement",
"those",
"in",
"{",
"@link",
"org",
".",
"htmlparser",
".",
"filters",
"}"
] | [
"// end tags return as their parent the matching opening tag",
"// pat.getPattern();",
"// If it is already encoded, leave it alone",
"// meta tag content attribute",
"// CSS @import",
"// Normal tag attribute",
"// return url.substring(0, startIx) + newUrl +",
"// \t(endIx < 0 ? \"\" : url.substring(endIx));",
"// Rewrite this attribute",
"// \t return false;",
"// Find each instance of @import.*)",
"// \t\t return false;",
"// shouldn't happen - type attr is required",
"// Check for style attribute",
"// style attr is very common, invoking css rewriter is expensive,",
"// do only if evidence of URLs",
"// \t\t res = BaseRegexFilter.urlEncode(res);",
"// shouldn't happen - type attr is required",
"// Rewrite the attribute",
"// Rewrite the content attribute",
"// Inspect the node's ancestors",
"// The node is in the designated subtree: don't select it (meaning,",
"// return false).",
"// The node is in the target tree. Selecting it or not depends on",
"// whether it is on the path from the target root to the designated",
"// subtree or not.",
"// If the node list is empty, the node is not on the path from the",
"// target root to the designated subtree: select it (meaning, return",
"// true). If the node list is non-empty, the node is on the path from",
"// the target root to the designated subtree: don't select it",
"// (meaning, return false). In other words, return the result of",
"// asking if the node list is empty.",
"// The node is not under the target root: don't select it (meaning,",
"// return false)."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | CommentStringFilter | /**
* This class accepts all comment nodes containing the given string.
*/ | This class accepts all comment nodes containing the given string. | [
"This",
"class",
"accepts",
"all",
"comment",
"nodes",
"containing",
"the",
"given",
"string",
"."
] | public static class CommentStringFilter implements NodeFilter {
private String string;
private boolean ignoreCase = false;
/**
* Creates a CommentStringFilter that accepts comment nodes containing
* the specified string. The match is case sensitive.
* @param substring The string to look for
*/
public CommentStringFilter(String substring) {
this(substring, false);
}
/**
* Creates a CommentStringFilter that accepts comment nodes containing
* the specified string.
* @param substring The string to look for
* @param ignoreCase If true, match is case insensitive
*/
public CommentStringFilter(String substring, boolean ignoreCase) {
this.string = substring;
this.ignoreCase = ignoreCase;
}
public boolean accept(Node node) {
if (node instanceof Remark) {
String nodestr = ((Remark)node).getText();
return -1 != (ignoreCase
? StringUtil.indexOfIgnoreCase(nodestr, string)
: nodestr.indexOf(string));
}
return false;
}
} | [
"public",
"static",
"class",
"CommentStringFilter",
"implements",
"NodeFilter",
"{",
"private",
"String",
"string",
";",
"private",
"boolean",
"ignoreCase",
"=",
"false",
";",
"/**\n * Creates a CommentStringFilter that accepts comment nodes containing\n * the specified string. The match is case sensitive.\n * @param substring The string to look for\n */",
"public",
"CommentStringFilter",
"(",
"String",
"substring",
")",
"{",
"this",
"(",
"substring",
",",
"false",
")",
";",
"}",
"/**\n * Creates a CommentStringFilter that accepts comment nodes containing\n * the specified string.\n * @param substring The string to look for\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CommentStringFilter",
"(",
"String",
"substring",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"string",
"=",
"substring",
";",
"this",
".",
"ignoreCase",
"=",
"ignoreCase",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Remark",
")",
"{",
"String",
"nodestr",
"=",
"(",
"(",
"Remark",
")",
"node",
")",
".",
"getText",
"(",
")",
";",
"return",
"-",
"1",
"!=",
"(",
"ignoreCase",
"?",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"nodestr",
",",
"string",
")",
":",
"nodestr",
".",
"indexOf",
"(",
"string",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | This class accepts all comment nodes containing the given string. | [
"This",
"class",
"accepts",
"all",
"comment",
"nodes",
"containing",
"the",
"given",
"string",
"."
] | [] | [
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | CompositeStringFilter | /**
* This class accepts all composite nodes containing the given string.
*/ | This class accepts all composite nodes containing the given string. | [
"This",
"class",
"accepts",
"all",
"composite",
"nodes",
"containing",
"the",
"given",
"string",
"."
] | public static class CompositeStringFilter implements NodeFilter {
private String string;
private boolean ignoreCase = false;
/**
* Creates a CompositeStringFilter that accepts composite nodes
* containing the specified string. The match is case sensitive.
* @param substring The string to look for
*/
public CompositeStringFilter(String substring) {
this(substring, false);
}
/**
* Creates a CompositeStringFilter that accepts composite nodes
* containing the specified string.
* @param substring The string to look for
* @param ignoreCase If true, match is case insensitive
*/
public CompositeStringFilter(String substring, boolean ignoreCase) {
this.string = substring;
this.ignoreCase = ignoreCase;
}
public boolean accept(Node node) {
if (node instanceof CompositeTag) {
String nodestr = getCompositeStringText((CompositeTag)node);
return -1 != (ignoreCase
? StringUtil.indexOfIgnoreCase(nodestr, string)
: nodestr.indexOf(string));
}
return false;
}
} | [
"public",
"static",
"class",
"CompositeStringFilter",
"implements",
"NodeFilter",
"{",
"private",
"String",
"string",
";",
"private",
"boolean",
"ignoreCase",
"=",
"false",
";",
"/**\n * Creates a CompositeStringFilter that accepts composite nodes\n * containing the specified string. The match is case sensitive.\n * @param substring The string to look for\n */",
"public",
"CompositeStringFilter",
"(",
"String",
"substring",
")",
"{",
"this",
"(",
"substring",
",",
"false",
")",
";",
"}",
"/**\n * Creates a CompositeStringFilter that accepts composite nodes\n * containing the specified string.\n * @param substring The string to look for\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CompositeStringFilter",
"(",
"String",
"substring",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"string",
"=",
"substring",
";",
"this",
".",
"ignoreCase",
"=",
"ignoreCase",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"CompositeTag",
")",
"{",
"String",
"nodestr",
"=",
"getCompositeStringText",
"(",
"(",
"CompositeTag",
")",
"node",
")",
";",
"return",
"-",
"1",
"!=",
"(",
"ignoreCase",
"?",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"nodestr",
",",
"string",
")",
":",
"nodestr",
".",
"indexOf",
"(",
"string",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | This class accepts all composite nodes containing the given string. | [
"This",
"class",
"accepts",
"all",
"composite",
"nodes",
"containing",
"the",
"given",
"string",
"."
] | [] | [
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | BaseRegexFilter | /**
* Abstract class for regex filters
*/ | Abstract class for regex filters | [
"Abstract",
"class",
"for",
"regex",
"filters"
] | public abstract static class BaseRegexFilter implements NodeFilter {
protected CachedPattern pat;
protected boolean negateFilter = false;
/**
* Creates a BaseRegexFilter that performs a case sensitive match for
* the specified regex
* @param regex The pattern to match.
*/
public BaseRegexFilter(String regex) {
this(regex, false);
}
/**
* Creates a BaseRegexFilter that performs a match for
* the specified regex
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public BaseRegexFilter(String regex, boolean ignoreCase) {
this.pat = new CachedPattern(regex);
if (ignoreCase) {
pat.setIgnoreCase(true);
}
// pat.getPattern();
}
public BaseRegexFilter setNegateFilter(boolean val) {
negateFilter = val;
return this;
}
protected boolean isFilterMatch(String str, CachedPattern pat) {
boolean isMatch = pat.getMatcher(str).find();
return negateFilter ? !isMatch : isMatch;
}
public abstract boolean accept(Node node);
/**
* URL encode the part of url that represents the original URL
* @param url the string including the rewritten URL
* @return the content of url with the original url encoded
*/
private static final String tag = "?url=";
protected String urlEncode(String url) {
return urlEncode(url, false);
}
protected String cssEncode(String url) {
return urlEncode(url, true);
}
protected String urlEncode(String url, boolean isCss) {
int startIx = url.indexOf(tag);
if (startIx < 0) {
log.warning("urlEncode: no tag (" + tag + ") in " + url);
return url;
}
startIx += tag.length();
String oldUrl = url.substring(startIx);
// If it is already encoded, leave it alone
if (StringUtil.startsWithIgnoreCase(oldUrl, "http%") ||
StringUtil.startsWithIgnoreCase(oldUrl, "ftp%") ||
StringUtil.startsWithIgnoreCase(oldUrl, "https%")) {
log.debug3("not encoding " + url);
return url;
}
int endIx = url.indexOf('"', startIx);
if (endIx > startIx) {
// meta tag content attribute
oldUrl = url.substring(startIx, endIx);
} else if (isCss && (endIx = url.indexOf(')', startIx)) > startIx) {
// CSS @import
oldUrl = url.substring(startIx, endIx);
} else {
// Normal tag attribute
endIx = -1;
}
int hashpos = oldUrl.indexOf('#');
String hashref = null;
if (hashpos >= 0) {
hashref = oldUrl.substring(hashpos);
oldUrl = oldUrl.substring(0, hashpos);
}
String newUrl = UrlUtil.encodeUrl(oldUrl);
if (log.isDebug3()) log.debug3("urlEncode: " + oldUrl + " -> " + newUrl);
StringBuilder sb = new StringBuilder();
sb.append(url, 0, startIx);
sb.append(newUrl);
if (hashref != null) {
sb.append(hashref);
}
if (endIx >= 0) {
sb.append(url.substring(endIx, url.length()));
}
return sb.toString();
// return url.substring(0, startIx) + newUrl +
// (endIx < 0 ? "" : url.substring(endIx));
}
} | [
"public",
"abstract",
"static",
"class",
"BaseRegexFilter",
"implements",
"NodeFilter",
"{",
"protected",
"CachedPattern",
"pat",
";",
"protected",
"boolean",
"negateFilter",
"=",
"false",
";",
"/**\n * Creates a BaseRegexFilter that performs a case sensitive match for\n * the specified regex\n * @param regex The pattern to match.\n */",
"public",
"BaseRegexFilter",
"(",
"String",
"regex",
")",
"{",
"this",
"(",
"regex",
",",
"false",
")",
";",
"}",
"/**\n * Creates a BaseRegexFilter that performs a match for\n * the specified regex\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"BaseRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"this",
".",
"pat",
"=",
"new",
"CachedPattern",
"(",
"regex",
")",
";",
"if",
"(",
"ignoreCase",
")",
"{",
"pat",
".",
"setIgnoreCase",
"(",
"true",
")",
";",
"}",
"}",
"public",
"BaseRegexFilter",
"setNegateFilter",
"(",
"boolean",
"val",
")",
"{",
"negateFilter",
"=",
"val",
";",
"return",
"this",
";",
"}",
"protected",
"boolean",
"isFilterMatch",
"(",
"String",
"str",
",",
"CachedPattern",
"pat",
")",
"{",
"boolean",
"isMatch",
"=",
"pat",
".",
"getMatcher",
"(",
"str",
")",
".",
"find",
"(",
")",
";",
"return",
"negateFilter",
"?",
"!",
"isMatch",
":",
"isMatch",
";",
"}",
"public",
"abstract",
"boolean",
"accept",
"(",
"Node",
"node",
")",
";",
"/**\n * URL encode the part of url that represents the original URL\n * @param url the string including the rewritten URL\n * @return the content of url with the original url encoded\n */",
"private",
"static",
"final",
"String",
"tag",
"=",
"\"",
"?url=",
"\"",
";",
"protected",
"String",
"urlEncode",
"(",
"String",
"url",
")",
"{",
"return",
"urlEncode",
"(",
"url",
",",
"false",
")",
";",
"}",
"protected",
"String",
"cssEncode",
"(",
"String",
"url",
")",
"{",
"return",
"urlEncode",
"(",
"url",
",",
"true",
")",
";",
"}",
"protected",
"String",
"urlEncode",
"(",
"String",
"url",
",",
"boolean",
"isCss",
")",
"{",
"int",
"startIx",
"=",
"url",
".",
"indexOf",
"(",
"tag",
")",
";",
"if",
"(",
"startIx",
"<",
"0",
")",
"{",
"log",
".",
"warning",
"(",
"\"",
"urlEncode: no tag (",
"\"",
"+",
"tag",
"+",
"\"",
") in ",
"\"",
"+",
"url",
")",
";",
"return",
"url",
";",
"}",
"startIx",
"+=",
"tag",
".",
"length",
"(",
")",
";",
"String",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
")",
";",
"if",
"(",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"http%",
"\"",
")",
"||",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"ftp%",
"\"",
")",
"||",
"StringUtil",
".",
"startsWithIgnoreCase",
"(",
"oldUrl",
",",
"\"",
"https%",
"\"",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"not encoding ",
"\"",
"+",
"url",
")",
";",
"return",
"url",
";",
"}",
"int",
"endIx",
"=",
"url",
".",
"indexOf",
"(",
"'\"'",
",",
"startIx",
")",
";",
"if",
"(",
"endIx",
">",
"startIx",
")",
"{",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
",",
"endIx",
")",
";",
"}",
"else",
"if",
"(",
"isCss",
"&&",
"(",
"endIx",
"=",
"url",
".",
"indexOf",
"(",
"')'",
",",
"startIx",
")",
")",
">",
"startIx",
")",
"{",
"oldUrl",
"=",
"url",
".",
"substring",
"(",
"startIx",
",",
"endIx",
")",
";",
"}",
"else",
"{",
"endIx",
"=",
"-",
"1",
";",
"}",
"int",
"hashpos",
"=",
"oldUrl",
".",
"indexOf",
"(",
"'#'",
")",
";",
"String",
"hashref",
"=",
"null",
";",
"if",
"(",
"hashpos",
">=",
"0",
")",
"{",
"hashref",
"=",
"oldUrl",
".",
"substring",
"(",
"hashpos",
")",
";",
"oldUrl",
"=",
"oldUrl",
".",
"substring",
"(",
"0",
",",
"hashpos",
")",
";",
"}",
"String",
"newUrl",
"=",
"UrlUtil",
".",
"encodeUrl",
"(",
"oldUrl",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"urlEncode: ",
"\"",
"+",
"oldUrl",
"+",
"\"",
" -> ",
"\"",
"+",
"newUrl",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"url",
",",
"0",
",",
"startIx",
")",
";",
"sb",
".",
"append",
"(",
"newUrl",
")",
";",
"if",
"(",
"hashref",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"hashref",
")",
";",
"}",
"if",
"(",
"endIx",
">=",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"url",
".",
"substring",
"(",
"endIx",
",",
"url",
".",
"length",
"(",
")",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Abstract class for regex filters | [
"Abstract",
"class",
"for",
"regex",
"filters"
] | [
"// pat.getPattern();",
"// If it is already encoded, leave it alone",
"// meta tag content attribute",
"// CSS @import",
"// Normal tag attribute",
"// return url.substring(0, startIx) + newUrl +",
"// \t(endIx < 0 ? \"\" : url.substring(endIx));"
] | [
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | CommentRegexFilter | /**
* This class accepts all comment nodes whose text contains a match for
* the regex.
*/ | This class accepts all comment nodes whose text contains a match for
the regex. | [
"This",
"class",
"accepts",
"all",
"comment",
"nodes",
"whose",
"text",
"contains",
"a",
"match",
"for",
"the",
"regex",
"."
] | public static class CommentRegexFilter extends BaseRegexFilter {
/**
* Creates a CommentRegexFilter that accepts comment nodes whose text
* contains a match for the regex. The match is case sensitive.
* @param regex The pattern to match.
*/
public CommentRegexFilter(String regex) {
super(regex);
}
/**
* Creates a CommentRegexFilter that accepts comment nodes containing
* the specified string.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public CommentRegexFilter(String regex, boolean ignoreCase) {
super(regex, ignoreCase);
}
public boolean accept(Node node) {
if (node instanceof Remark) {
String nodestr = ((Remark)node).getText();
return isFilterMatch(nodestr, pat);
}
return false;
}
} | [
"public",
"static",
"class",
"CommentRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"/**\n * Creates a CommentRegexFilter that accepts comment nodes whose text\n * contains a match for the regex. The match is case sensitive.\n * @param regex The pattern to match.\n */",
"public",
"CommentRegexFilter",
"(",
"String",
"regex",
")",
"{",
"super",
"(",
"regex",
")",
";",
"}",
"/**\n * Creates a CommentRegexFilter that accepts comment nodes containing\n * the specified string.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CommentRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Remark",
")",
"{",
"String",
"nodestr",
"=",
"(",
"(",
"Remark",
")",
"node",
")",
".",
"getText",
"(",
")",
";",
"return",
"isFilterMatch",
"(",
"nodestr",
",",
"pat",
")",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | This class accepts all comment nodes whose text contains a match for
the regex. | [
"This",
"class",
"accepts",
"all",
"comment",
"nodes",
"whose",
"text",
"contains",
"a",
"match",
"for",
"the",
"regex",
"."
] | [] | [
{
"param": "BaseRegexFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | LinkRegexXform | /**
* This class accepts everything but applies a transform to
* links that match the regex.
*/ | This class accepts everything but applies a transform to
links that match the regex. | [
"This",
"class",
"accepts",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"links",
"that",
"match",
"the",
"regex",
"."
] | public static class LinkRegexXform extends BaseRegexXform {
private String[] attrs;
/**
* Creates a LinkRegexXform that rejects everything but applies
* a transform to nodes whose text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
* @param attrs Attributes to process
*/
public LinkRegexXform(String regex, boolean ignoreCase,
String target, String replace, String[] attrs) {
super(regex, ignoreCase, target, replace);
this.attrs = attrs;
}
public boolean accept(Node node) {
if (node instanceof TagNode &&
!(node instanceof MetaTag)) {
for (int i = 0; i < attrs.length; i++) {
Attribute attribute = ((TagNode)node).getAttributeEx(attrs[i]);
if (attribute != null && attribute.getValue() != null) {
// Rewrite this attribute
String url = attribute.getValue();
if (isFilterMatch(url, pat)) {
if (log.isDebug3()) {
log.debug3("Attribute " + attribute.getName() + " old " + url +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newUrl = targetPat.getMatcher(url).replaceFirst(replace);
if (!newUrl.equals(url)) {
String encoded = urlEncode(newUrl);
attribute.setValue(encoded);
((TagNode)node).setAttributeEx(attribute);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
// return false;
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"LinkRegexXform",
"extends",
"BaseRegexXform",
"{",
"private",
"String",
"[",
"]",
"attrs",
";",
"/**\n * Creates a LinkRegexXform that rejects everything but applies\n * a transform to nodes whose text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n * @param attrs Attributes to process\n */",
"public",
"LinkRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
",",
"String",
"[",
"]",
"attrs",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"this",
".",
"attrs",
"=",
"attrs",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"TagNode",
"&&",
"!",
"(",
"node",
"instanceof",
"MetaTag",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"attrs",
".",
"length",
";",
"i",
"++",
")",
"{",
"Attribute",
"attribute",
"=",
"(",
"(",
"TagNode",
")",
"node",
")",
".",
"getAttributeEx",
"(",
"attrs",
"[",
"i",
"]",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
"&&",
"attribute",
".",
"getValue",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"url",
"=",
"attribute",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"isFilterMatch",
"(",
"url",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Attribute ",
"\"",
"+",
"attribute",
".",
"getName",
"(",
")",
"+",
"\"",
" old ",
"\"",
"+",
"url",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newUrl",
"=",
"targetPat",
".",
"getMatcher",
"(",
"url",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newUrl",
".",
"equals",
"(",
"url",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newUrl",
")",
";",
"attribute",
".",
"setValue",
"(",
"encoded",
")",
";",
"(",
"(",
"TagNode",
")",
"node",
")",
".",
"setAttributeEx",
"(",
"attribute",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | This class accepts everything but applies a transform to
links that match the regex. | [
"This",
"class",
"accepts",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"links",
"that",
"match",
"the",
"regex",
"."
] | [
"// Rewrite this attribute",
"// \t return false;"
] | [
{
"param": "BaseRegexXform",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexXform",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | StyleRegexXform | /**
* This class rejects everything but applies a transform to
* links is Style tags that match the regex.
* @deprecated Processes only @import; use {@link StyleTagXformDispatch}
* instead.
*/ | This class rejects everything but applies a transform to
links is Style tags that match the regex.
@deprecated Processes only @import; use StyleTagXformDispatch
instead. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"links",
"is",
"Style",
"tags",
"that",
"match",
"the",
"regex",
".",
"@deprecated",
"Processes",
"only",
"@import",
";",
"use",
"StyleTagXformDispatch",
"instead",
"."
] | @Deprecated
public static class StyleRegexXform extends BaseRegexXform {
/**
* Creates a StyleRegexXform that rejects everything but applies
* a transform to style nodes whose child text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
*/
public StyleRegexXform(String regex, boolean ignoreCase,
String target, String replace) {
super(regex, ignoreCase, target, replace);
}
public boolean accept(Node node) {
if (node instanceof StyleTag) {
try {
NodeIterator it;
nodeLoop:
for (it = ((StyleTag)node).children(); it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
// Find each instance of @import.*)
String text = ((TextNode)child).getText();
int startIx = 0;
while ((startIx = text.indexOf(importTag, startIx)) >= 0) {
int endIx = text.indexOf(')', startIx);
int delta = 0;
if (endIx < 0) {
log.error("Can't find close paren in " + text);
continue nodeLoop;
// return false;
}
String oldImport = text.substring(startIx, endIx + 1);
if (isFilterMatch(oldImport, pat)) {
String newImport = targetPat.getMatcher(oldImport).replaceFirst(replace);
if (!newImport.equals(oldImport)) {
String encoded = cssEncode(newImport);
delta = encoded.length() - oldImport.length();
String newText = text.substring(0, startIx) +
encoded + text.substring(endIx + 1);
if (log.isDebug3())
log.debug3("Import rewritten " + newText);
text = newText;
((TextNode)child).setText(text);
}
}
startIx = endIx + 1 + delta;
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
return false;
}
} | [
"@",
"Deprecated",
"public",
"static",
"class",
"StyleRegexXform",
"extends",
"BaseRegexXform",
"{",
"/**\n * Creates a StyleRegexXform that rejects everything but applies\n * a transform to style nodes whose child text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n */",
"public",
"StyleRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"StyleTag",
")",
"{",
"try",
"{",
"NodeIterator",
"it",
";",
"nodeLoop",
":",
"for",
"(",
"it",
"=",
"(",
"(",
"StyleTag",
")",
"node",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"String",
"text",
"=",
"(",
"(",
"TextNode",
")",
"child",
")",
".",
"getText",
"(",
")",
";",
"int",
"startIx",
"=",
"0",
";",
"while",
"(",
"(",
"startIx",
"=",
"text",
".",
"indexOf",
"(",
"importTag",
",",
"startIx",
")",
")",
">=",
"0",
")",
"{",
"int",
"endIx",
"=",
"text",
".",
"indexOf",
"(",
"')'",
",",
"startIx",
")",
";",
"int",
"delta",
"=",
"0",
";",
"if",
"(",
"endIx",
"<",
"0",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't find close paren in ",
"\"",
"+",
"text",
")",
";",
"continue",
"nodeLoop",
";",
"}",
"String",
"oldImport",
"=",
"text",
".",
"substring",
"(",
"startIx",
",",
"endIx",
"+",
"1",
")",
";",
"if",
"(",
"isFilterMatch",
"(",
"oldImport",
",",
"pat",
")",
")",
"{",
"String",
"newImport",
"=",
"targetPat",
".",
"getMatcher",
"(",
"oldImport",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newImport",
".",
"equals",
"(",
"oldImport",
")",
")",
"{",
"String",
"encoded",
"=",
"cssEncode",
"(",
"newImport",
")",
";",
"delta",
"=",
"encoded",
".",
"length",
"(",
")",
"-",
"oldImport",
".",
"length",
"(",
")",
";",
"String",
"newText",
"=",
"text",
".",
"substring",
"(",
"0",
",",
"startIx",
")",
"+",
"encoded",
"+",
"text",
".",
"substring",
"(",
"endIx",
"+",
"1",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Import rewritten ",
"\"",
"+",
"newText",
")",
";",
"text",
"=",
"newText",
";",
"(",
"(",
"TextNode",
")",
"child",
")",
".",
"setText",
"(",
"text",
")",
";",
"}",
"}",
"startIx",
"=",
"endIx",
"+",
"1",
"+",
"delta",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | This class rejects everything but applies a transform to
links is Style tags that match the regex. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"links",
"is",
"Style",
"tags",
"that",
"match",
"the",
"regex",
"."
] | [
"// Find each instance of @import.*)",
"// \t\t return false;"
] | [
{
"param": "BaseRegexXform",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexXform",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | BaseStyleDispatch | /**
* Base class for rewriting contents of style tag or attr
*/ | Base class for rewriting contents of style tag or attr | [
"Base",
"class",
"for",
"rewriting",
"contents",
"of",
"style",
"tag",
"or",
"attr"
] | public static class BaseStyleDispatch {
protected ArchivalUnit au;
protected String charset;
protected String baseUrl;
protected ServletUtil.LinkTransform xform;
protected LinkRewriterFactory lrf;
public BaseStyleDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
this.au = au;
if (charset == null) {
this.charset = Constants.DEFAULT_ENCODING;
} else {
this.charset = charset;
}
this.baseUrl = baseUrl;
this.xform = xform;
}
public void setBaseUrl(String newBase) {
baseUrl = newBase;
}
protected static String DEFAULT_STYLE_MIME_TYPE = "text/css";
protected String rewriteStyleDispatch(String text,
LinkRewriterFactory lrf,
String mime)
throws PluginException, IOException {
InputStream rewritten = null;
try {
rewritten =
lrf.createLinkRewriter(mime,
au,
new ReaderInputStream(new StringReader(text),
charset),
charset,
baseUrl,
xform);
String res =
StringUtil.fromReader(new InputStreamReader(rewritten, charset));
return res;
} finally {
IOUtil.safeClose(rewritten);
}
}
} | [
"public",
"static",
"class",
"BaseStyleDispatch",
"{",
"protected",
"ArchivalUnit",
"au",
";",
"protected",
"String",
"charset",
";",
"protected",
"String",
"baseUrl",
";",
"protected",
"ServletUtil",
".",
"LinkTransform",
"xform",
";",
"protected",
"LinkRewriterFactory",
"lrf",
";",
"public",
"BaseStyleDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"this",
".",
"au",
"=",
"au",
";",
"if",
"(",
"charset",
"==",
"null",
")",
"{",
"this",
".",
"charset",
"=",
"Constants",
".",
"DEFAULT_ENCODING",
";",
"}",
"else",
"{",
"this",
".",
"charset",
"=",
"charset",
";",
"}",
"this",
".",
"baseUrl",
"=",
"baseUrl",
";",
"this",
".",
"xform",
"=",
"xform",
";",
"}",
"public",
"void",
"setBaseUrl",
"(",
"String",
"newBase",
")",
"{",
"baseUrl",
"=",
"newBase",
";",
"}",
"protected",
"static",
"String",
"DEFAULT_STYLE_MIME_TYPE",
"=",
"\"",
"text/css",
"\"",
";",
"protected",
"String",
"rewriteStyleDispatch",
"(",
"String",
"text",
",",
"LinkRewriterFactory",
"lrf",
",",
"String",
"mime",
")",
"throws",
"PluginException",
",",
"IOException",
"{",
"InputStream",
"rewritten",
"=",
"null",
";",
"try",
"{",
"rewritten",
"=",
"lrf",
".",
"createLinkRewriter",
"(",
"mime",
",",
"au",
",",
"new",
"ReaderInputStream",
"(",
"new",
"StringReader",
"(",
"text",
")",
",",
"charset",
")",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"String",
"res",
"=",
"StringUtil",
".",
"fromReader",
"(",
"new",
"InputStreamReader",
"(",
"rewritten",
",",
"charset",
")",
")",
";",
"return",
"res",
";",
"}",
"finally",
"{",
"IOUtil",
".",
"safeClose",
"(",
"rewritten",
")",
";",
"}",
"}",
"}"
] | Base class for rewriting contents of style tag or attr | [
"Base",
"class",
"for",
"rewriting",
"contents",
"of",
"style",
"tag",
"or",
"attr"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | StyleTagXformDispatch | /**
* Rejects everything and applies a CSS LinkRewriter to the text in
* style tags
*/ | Rejects everything and applies a CSS LinkRewriter to the text in
style tags | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"style",
"tags"
] | public static class StyleTagXformDispatch
extends BaseStyleDispatch implements NodeFilter
{
public StyleTagXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
public boolean accept(Node node) {
if (node instanceof StyleTag) {
StyleTag tag = (StyleTag)node;
if (tag.getAttribute("src") != null) {
return false;
}
String mime = tag.getAttribute("type");
if (mime == null) {
// shouldn't happen - type attr is required
log.warning("<style> tag with no type attribute");
mime = DEFAULT_STYLE_MIME_TYPE;
}
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
for (NodeIterator it = (tag).children();
it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
TextNode textChild = (TextNode)child;
String source = textChild.getText();
if (!StringUtil.isNullString(source)) {
try {
String res = rewriteStyleDispatch(source, lrf, mime);
if (!res.equals(source)) {
if (log.isDebug3()) log.debug3("Style rewritten " + res);
textChild.setText(res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
}
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"StyleTagXformDispatch",
"extends",
"BaseStyleDispatch",
"implements",
"NodeFilter",
"{",
"public",
"StyleTagXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"StyleTag",
")",
"{",
"StyleTag",
"tag",
"=",
"(",
"StyleTag",
")",
"node",
";",
"if",
"(",
"tag",
".",
"getAttribute",
"(",
"\"",
"src",
"\"",
")",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"String",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"type",
"\"",
")",
";",
"if",
"(",
"mime",
"==",
"null",
")",
"{",
"log",
".",
"warning",
"(",
"\"",
"<style> tag with no type attribute",
"\"",
")",
";",
"mime",
"=",
"DEFAULT_STYLE_MIME_TYPE",
";",
"}",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"for",
"(",
"NodeIterator",
"it",
"=",
"(",
"tag",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"TextNode",
"textChild",
"=",
"(",
"TextNode",
")",
"child",
";",
"String",
"source",
"=",
"textChild",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isNullString",
"(",
"source",
")",
")",
"{",
"try",
"{",
"String",
"res",
"=",
"rewriteStyleDispatch",
"(",
"source",
",",
"lrf",
",",
"mime",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"source",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Style rewritten ",
"\"",
"+",
"res",
")",
";",
"textChild",
".",
"setText",
"(",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | Rejects everything and applies a CSS LinkRewriter to the text in
style tags | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"style",
"tags"
] | [
"// shouldn't happen - type attr is required"
] | [
{
"param": "BaseStyleDispatch",
"type": null
},
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseStyleDispatch",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | StyleXformDispatch | /**
* @deprecated Here only to keep old class name used by
* taylorandfrancis.NodeFilterHtmlLinkRewriterFactory. Should be removed
* once no references.
*/ | @deprecated Here only to keep old class name used by
taylorandfrancis.NodeFilterHtmlLinkRewriterFactory. Should be removed
once no references. | [
"@deprecated",
"Here",
"only",
"to",
"keep",
"old",
"class",
"name",
"used",
"by",
"taylorandfrancis",
".",
"NodeFilterHtmlLinkRewriterFactory",
".",
"Should",
"be",
"removed",
"once",
"no",
"references",
"."
] | public static class StyleXformDispatch
extends StyleTagXformDispatch {
public StyleXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
} | [
"public",
"static",
"class",
"StyleXformDispatch",
"extends",
"StyleTagXformDispatch",
"{",
"public",
"StyleXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"}"
] | @deprecated Here only to keep old class name used by
taylorandfrancis.NodeFilterHtmlLinkRewriterFactory. | [
"@deprecated",
"Here",
"only",
"to",
"keep",
"old",
"class",
"name",
"used",
"by",
"taylorandfrancis",
".",
"NodeFilterHtmlLinkRewriterFactory",
"."
] | [] | [
{
"param": "StyleTagXformDispatch",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "StyleTagXformDispatch",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | StyleAttrXformDispatch | /**
* Rejects everything and applies a CSS LinkRewriter to the text in
* style attributes
*/ | Rejects everything and applies a CSS LinkRewriter to the text in
style attributes | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"style",
"attributes"
] | public static class StyleAttrXformDispatch
extends BaseStyleDispatch implements NodeFilter {
public StyleAttrXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
super(au, charset, baseUrl, xform);
}
public boolean accept(Node node) {
if (node instanceof TagNode &&
!(node instanceof MetaTag)) {
TagNode tag = (TagNode)node;
// Check for style attribute
Attribute attribute = tag.getAttributeEx("style");
if (attribute != null) {
String style = attribute.getValue();
// style attr is very common, invoking css rewriter is expensive,
// do only if evidence of URLs
if (style != null
&& StringUtil.indexOfIgnoreCase(style, "url(") >= 0) {
String mime = DEFAULT_STYLE_MIME_TYPE;
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
String res = rewriteStyleDispatch(style, lrf, mime);
if (!res.equals(style)) {
// res = BaseRegexFilter.urlEncode(res);
attribute.setValue(res);
tag.setAttributeEx(attribute);
if (log.isDebug3()) log.debug3("new " + res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
}
}
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"StyleAttrXformDispatch",
"extends",
"BaseStyleDispatch",
"implements",
"NodeFilter",
"{",
"public",
"StyleAttrXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"super",
"(",
"au",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"TagNode",
"&&",
"!",
"(",
"node",
"instanceof",
"MetaTag",
")",
")",
"{",
"TagNode",
"tag",
"=",
"(",
"TagNode",
")",
"node",
";",
"Attribute",
"attribute",
"=",
"tag",
".",
"getAttributeEx",
"(",
"\"",
"style",
"\"",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
")",
"{",
"String",
"style",
"=",
"attribute",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"style",
"!=",
"null",
"&&",
"StringUtil",
".",
"indexOfIgnoreCase",
"(",
"style",
",",
"\"",
"url(",
"\"",
")",
">=",
"0",
")",
"{",
"String",
"mime",
"=",
"DEFAULT_STYLE_MIME_TYPE",
";",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"String",
"res",
"=",
"rewriteStyleDispatch",
"(",
"style",
",",
"lrf",
",",
"mime",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"style",
")",
")",
"{",
"attribute",
".",
"setValue",
"(",
"res",
")",
";",
"tag",
".",
"setAttributeEx",
"(",
"attribute",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | Rejects everything and applies a CSS LinkRewriter to the text in
style attributes | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"style",
"attributes"
] | [
"// Check for style attribute",
"// style attr is very common, invoking css rewriter is expensive,",
"// do only if evidence of URLs",
"// \t\t res = BaseRegexFilter.urlEncode(res);"
] | [
{
"param": "BaseStyleDispatch",
"type": null
},
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseStyleDispatch",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | ScriptXformDispatch | /**
* Rejects everything and applies a CSS LinkRewriter to the text in
* script tags
*/ | Rejects everything and applies a CSS LinkRewriter to the text in
script tags | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"script",
"tags"
] | public static class ScriptXformDispatch implements NodeFilter {
private ArchivalUnit au;
private String charset;
private String baseUrl;
private ServletUtil.LinkTransform xform;
public ScriptXformDispatch(ArchivalUnit au,
String charset,
String baseUrl,
ServletUtil.LinkTransform xform) {
this.au = au;
if (charset == null) {
this.charset = Constants.DEFAULT_ENCODING;
} else {
this.charset = charset;
}
this.baseUrl = baseUrl;
this.xform = xform;
}
public void setBaseUrl(String newBase) {
baseUrl = newBase;
}
static String DEFAULT_SCRIPT_MIME_TYPE = "text/javascript";
public boolean accept(Node node) {
if (node instanceof ScriptTag) {
ScriptTag tag = (ScriptTag)node;
if (tag.getAttribute("src") != null) {
return false;
}
String mime = tag.getAttribute("type");
if (mime == null) {
mime = tag.getAttribute("language");
if (mime != null) {
if (mime.indexOf("/") < 0) {
mime = "text/" + mime;
}
} else {
// shouldn't happen - type attr is required
log.warning("<script> tag with no type or language attribute");
mime = DEFAULT_SCRIPT_MIME_TYPE;
}
}
LinkRewriterFactory lrf = au.getLinkRewriterFactory(mime);
if (lrf != null) {
try {
for (NodeIterator it = (tag).children();
it.hasMoreNodes(); ) {
Node child = it.nextNode();
if (child instanceof TextNode) {
TextNode textChild = (TextNode)child;
String source = textChild.getText();
if (!StringUtil.isNullString(source)) {
InputStream rewritten = null;
try {
rewritten =
lrf.createLinkRewriter(mime,
au,
new ReaderInputStream(new StringReader(source),
charset),
charset,
baseUrl,
xform);
String res =
StringUtil.fromReader(new InputStreamReader(rewritten,
charset));
if (!res.equals(source)) {
if (log.isDebug3()) log.debug3("Script rewritten " + res);
textChild.setText(res);
}
} catch (PluginException e) {
log.error("Can't create link rewriter, not rewriting", e);
} catch (IOException e) {
log.error("Can't create link rewriter, not rewriting", e);
} finally {
IOUtil.safeClose(rewritten);
}
}
}
}
} catch (ParserException ex) {
log.error("Node " + node.toString() + " threw " + ex);
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"ScriptXformDispatch",
"implements",
"NodeFilter",
"{",
"private",
"ArchivalUnit",
"au",
";",
"private",
"String",
"charset",
";",
"private",
"String",
"baseUrl",
";",
"private",
"ServletUtil",
".",
"LinkTransform",
"xform",
";",
"public",
"ScriptXformDispatch",
"(",
"ArchivalUnit",
"au",
",",
"String",
"charset",
",",
"String",
"baseUrl",
",",
"ServletUtil",
".",
"LinkTransform",
"xform",
")",
"{",
"this",
".",
"au",
"=",
"au",
";",
"if",
"(",
"charset",
"==",
"null",
")",
"{",
"this",
".",
"charset",
"=",
"Constants",
".",
"DEFAULT_ENCODING",
";",
"}",
"else",
"{",
"this",
".",
"charset",
"=",
"charset",
";",
"}",
"this",
".",
"baseUrl",
"=",
"baseUrl",
";",
"this",
".",
"xform",
"=",
"xform",
";",
"}",
"public",
"void",
"setBaseUrl",
"(",
"String",
"newBase",
")",
"{",
"baseUrl",
"=",
"newBase",
";",
"}",
"static",
"String",
"DEFAULT_SCRIPT_MIME_TYPE",
"=",
"\"",
"text/javascript",
"\"",
";",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"ScriptTag",
")",
"{",
"ScriptTag",
"tag",
"=",
"(",
"ScriptTag",
")",
"node",
";",
"if",
"(",
"tag",
".",
"getAttribute",
"(",
"\"",
"src",
"\"",
")",
"!=",
"null",
")",
"{",
"return",
"false",
";",
"}",
"String",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"type",
"\"",
")",
";",
"if",
"(",
"mime",
"==",
"null",
")",
"{",
"mime",
"=",
"tag",
".",
"getAttribute",
"(",
"\"",
"language",
"\"",
")",
";",
"if",
"(",
"mime",
"!=",
"null",
")",
"{",
"if",
"(",
"mime",
".",
"indexOf",
"(",
"\"",
"/",
"\"",
")",
"<",
"0",
")",
"{",
"mime",
"=",
"\"",
"text/",
"\"",
"+",
"mime",
";",
"}",
"}",
"else",
"{",
"log",
".",
"warning",
"(",
"\"",
"<script> tag with no type or language attribute",
"\"",
")",
";",
"mime",
"=",
"DEFAULT_SCRIPT_MIME_TYPE",
";",
"}",
"}",
"LinkRewriterFactory",
"lrf",
"=",
"au",
".",
"getLinkRewriterFactory",
"(",
"mime",
")",
";",
"if",
"(",
"lrf",
"!=",
"null",
")",
"{",
"try",
"{",
"for",
"(",
"NodeIterator",
"it",
"=",
"(",
"tag",
")",
".",
"children",
"(",
")",
";",
"it",
".",
"hasMoreNodes",
"(",
")",
";",
")",
"{",
"Node",
"child",
"=",
"it",
".",
"nextNode",
"(",
")",
";",
"if",
"(",
"child",
"instanceof",
"TextNode",
")",
"{",
"TextNode",
"textChild",
"=",
"(",
"TextNode",
")",
"child",
";",
"String",
"source",
"=",
"textChild",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isNullString",
"(",
"source",
")",
")",
"{",
"InputStream",
"rewritten",
"=",
"null",
";",
"try",
"{",
"rewritten",
"=",
"lrf",
".",
"createLinkRewriter",
"(",
"mime",
",",
"au",
",",
"new",
"ReaderInputStream",
"(",
"new",
"StringReader",
"(",
"source",
")",
",",
"charset",
")",
",",
"charset",
",",
"baseUrl",
",",
"xform",
")",
";",
"String",
"res",
"=",
"StringUtil",
".",
"fromReader",
"(",
"new",
"InputStreamReader",
"(",
"rewritten",
",",
"charset",
")",
")",
";",
"if",
"(",
"!",
"res",
".",
"equals",
"(",
"source",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"Script rewritten ",
"\"",
"+",
"res",
")",
";",
"textChild",
".",
"setText",
"(",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"PluginException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Can't create link rewriter, not rewriting",
"\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtil",
".",
"safeClose",
"(",
"rewritten",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"ParserException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Node ",
"\"",
"+",
"node",
".",
"toString",
"(",
")",
"+",
"\"",
" threw ",
"\"",
"+",
"ex",
")",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | Rejects everything and applies a CSS LinkRewriter to the text in
script tags | [
"Rejects",
"everything",
"and",
"applies",
"a",
"CSS",
"LinkRewriter",
"to",
"the",
"text",
"in",
"script",
"tags"
] | [
"// shouldn't happen - type attr is required"
] | [
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | RefreshRegexXform | /**
* This class rejects everything but applies a transform to
* meta refresh tags that match the regex.
*/ | This class rejects everything but applies a transform to
meta refresh tags that match the regex. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"meta",
"refresh",
"tags",
"that",
"match",
"the",
"regex",
"."
] | public static class RefreshRegexXform extends BaseRegexXform {
/**
* Creates a RefreshRegexXform that rejects everything but applies
* a transform to nodes whose text
* contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
*/
public RefreshRegexXform(String regex, boolean ignoreCase,
String target, String replace) {
super(regex, ignoreCase, target, replace);
}
public boolean accept(Node node) {
if (node instanceof MetaTag) {
String equiv = ((MetaTag)node).getAttribute("http-equiv");
if ("refresh".equalsIgnoreCase(equiv)) {
String contentVal = ((MetaTag)node).getAttribute("content");
if (log.isDebug3()) log.debug3("RefreshRegexXform: " + contentVal);
if (contentVal != null && isFilterMatch(contentVal, pat)) {
// Rewrite the attribute
if (log.isDebug3()) {
log.debug3("Refresh old " + contentVal +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newVal = targetPat.getMatcher(contentVal).replaceFirst(replace);
if (!newVal.equals(contentVal)) {
String encoded = urlEncode(newVal);
((MetaTag)node).setAttribute("content", encoded);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"RefreshRegexXform",
"extends",
"BaseRegexXform",
"{",
"/**\n * Creates a RefreshRegexXform that rejects everything but applies\n * a transform to nodes whose text\n * contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n */",
"public",
"RefreshRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"MetaTag",
")",
"{",
"String",
"equiv",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"http-equiv",
"\"",
")",
";",
"if",
"(",
"\"",
"refresh",
"\"",
".",
"equalsIgnoreCase",
"(",
"equiv",
")",
")",
"{",
"String",
"contentVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"content",
"\"",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"RefreshRegexXform: ",
"\"",
"+",
"contentVal",
")",
";",
"if",
"(",
"contentVal",
"!=",
"null",
"&&",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Refresh old ",
"\"",
"+",
"contentVal",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newVal",
"=",
"targetPat",
".",
"getMatcher",
"(",
"contentVal",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newVal",
".",
"equals",
"(",
"contentVal",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newVal",
")",
";",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"setAttribute",
"(",
"\"",
"content",
"\"",
",",
"encoded",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | This class rejects everything but applies a transform to
meta refresh tags that match the regex. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"meta",
"refresh",
"tags",
"that",
"match",
"the",
"regex",
"."
] | [
"// Rewrite the attribute"
] | [
{
"param": "BaseRegexXform",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexXform",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | MetaTagRegexXform | /**
* This class rejects everything but applies a transform to the content
* attr of meta tags whose name attr matches one of the supplied names.
*/ | This class rejects everything but applies a transform to the content
attr of meta tags whose name attr matches one of the supplied names. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"the",
"content",
"attr",
"of",
"meta",
"tags",
"whose",
"name",
"attr",
"matches",
"one",
"of",
"the",
"supplied",
"names",
"."
] | public static class MetaTagRegexXform extends BaseRegexXform {
private List<String> names;
/**
* Creates a MetaTagRegexXform that rejects everything but applies a
* transform to the content attr of meta tags whose name attr matches
* one of the supplied names.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
* @param target Regex to replace
* @param replace Text to replace it with
* @param names List of <code>name</code> attributes for which to
* rewrite the <code>content</code> URL.
*/
public MetaTagRegexXform(String regex, boolean ignoreCase,
String target, String replace,
List<String> names) {
super(regex, ignoreCase, target, replace);
this.names = names;
}
public boolean accept(Node node) {
if (node instanceof MetaTag) {
String nameVal = ((MetaTag)node).getAttribute("name");
if (names.contains(nameVal)) {
String contentVal = ((MetaTag)node).getAttribute("content");
if (log.isDebug3()) {
log.debug3("MetaTagRegexXform: " + nameVal
+ " = " + contentVal +
( isFilterMatch(contentVal, pat)
? " metches " : " does not match ") +
pat.getPattern());
}
if (contentVal != null && isFilterMatch(contentVal, pat)) {
// Rewrite the content attribute
if (log.isDebug3()) {
log.debug3("Meta old " + contentVal +
" target " + targetPat.getPattern() +
" replace " + replace);
}
String newVal =
targetPat.getMatcher(contentVal).replaceFirst(replace);
if (!newVal.equals(contentVal)) {
String encoded = urlEncode(newVal);
((MetaTag)node).setAttribute("content", encoded);
if (log.isDebug3()) log.debug3("new " + encoded);
}
}
}
}
return false;
}
} | [
"public",
"static",
"class",
"MetaTagRegexXform",
"extends",
"BaseRegexXform",
"{",
"private",
"List",
"<",
"String",
">",
"names",
";",
"/**\n * Creates a MetaTagRegexXform that rejects everything but applies a\n * transform to the content attr of meta tags whose name attr matches\n * one of the supplied names.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n * @param target Regex to replace\n * @param replace Text to replace it with\n * @param names List of <code>name</code> attributes for which to\n * rewrite the <code>content</code> URL.\n */",
"public",
"MetaTagRegexXform",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
",",
"String",
"target",
",",
"String",
"replace",
",",
"List",
"<",
"String",
">",
"names",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
",",
"target",
",",
"replace",
")",
";",
"this",
".",
"names",
"=",
"names",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"MetaTag",
")",
"{",
"String",
"nameVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"name",
"\"",
")",
";",
"if",
"(",
"names",
".",
"contains",
"(",
"nameVal",
")",
")",
"{",
"String",
"contentVal",
"=",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"getAttribute",
"(",
"\"",
"content",
"\"",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"MetaTagRegexXform: ",
"\"",
"+",
"nameVal",
"+",
"\"",
" = ",
"\"",
"+",
"contentVal",
"+",
"(",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
"?",
"\"",
" metches ",
"\"",
":",
"\"",
" does not match ",
"\"",
")",
"+",
"pat",
".",
"getPattern",
"(",
")",
")",
";",
"}",
"if",
"(",
"contentVal",
"!=",
"null",
"&&",
"isFilterMatch",
"(",
"contentVal",
",",
"pat",
")",
")",
"{",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"{",
"log",
".",
"debug3",
"(",
"\"",
"Meta old ",
"\"",
"+",
"contentVal",
"+",
"\"",
" target ",
"\"",
"+",
"targetPat",
".",
"getPattern",
"(",
")",
"+",
"\"",
" replace ",
"\"",
"+",
"replace",
")",
";",
"}",
"String",
"newVal",
"=",
"targetPat",
".",
"getMatcher",
"(",
"contentVal",
")",
".",
"replaceFirst",
"(",
"replace",
")",
";",
"if",
"(",
"!",
"newVal",
".",
"equals",
"(",
"contentVal",
")",
")",
"{",
"String",
"encoded",
"=",
"urlEncode",
"(",
"newVal",
")",
";",
"(",
"(",
"MetaTag",
")",
"node",
")",
".",
"setAttribute",
"(",
"\"",
"content",
"\"",
",",
"encoded",
")",
";",
"if",
"(",
"log",
".",
"isDebug3",
"(",
")",
")",
"log",
".",
"debug3",
"(",
"\"",
"new ",
"\"",
"+",
"encoded",
")",
";",
"}",
"}",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | This class rejects everything but applies a transform to the content
attr of meta tags whose name attr matches one of the supplied names. | [
"This",
"class",
"rejects",
"everything",
"but",
"applies",
"a",
"transform",
"to",
"the",
"content",
"attr",
"of",
"meta",
"tags",
"whose",
"name",
"attr",
"matches",
"one",
"of",
"the",
"supplied",
"names",
"."
] | [
"// Rewrite the content attribute"
] | [
{
"param": "BaseRegexXform",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexXform",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | CompositeRegexFilter | /**
* This class accepts all composite nodes whose text contains a match for
* the regex.
*/ | This class accepts all composite nodes whose text contains a match for
the regex. | [
"This",
"class",
"accepts",
"all",
"composite",
"nodes",
"whose",
"text",
"contains",
"a",
"match",
"for",
"the",
"regex",
"."
] | public static class CompositeRegexFilter extends BaseRegexFilter {
/**
* Creates a CompositeRegexFilter that accepts composite nodes whose
* text contains a match for the regex. The match is case sensitive.
* @param regex The pattern to match.
*/
public CompositeRegexFilter(String regex) {
super(regex);
}
/**
* Creates a CompositeRegexFilter that accepts composite nodes whose
* text contains a match for the regex.
* @param regex The pattern to match.
* @param ignoreCase If true, match is case insensitive
*/
public CompositeRegexFilter(String regex, boolean ignoreCase) {
super(regex, ignoreCase);
}
public boolean accept(Node node) {
if (node instanceof CompositeTag) {
String nodestr = getCompositeStringText((CompositeTag)node);
return isFilterMatch(nodestr, pat);
}
return false;
}
} | [
"public",
"static",
"class",
"CompositeRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"/**\n * Creates a CompositeRegexFilter that accepts composite nodes whose\n * text contains a match for the regex. The match is case sensitive.\n * @param regex The pattern to match.\n */",
"public",
"CompositeRegexFilter",
"(",
"String",
"regex",
")",
"{",
"super",
"(",
"regex",
")",
";",
"}",
"/**\n * Creates a CompositeRegexFilter that accepts composite nodes whose\n * text contains a match for the regex.\n * @param regex The pattern to match.\n * @param ignoreCase If true, match is case insensitive\n */",
"public",
"CompositeRegexFilter",
"(",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"CompositeTag",
")",
"{",
"String",
"nodestr",
"=",
"getCompositeStringText",
"(",
"(",
"CompositeTag",
")",
"node",
")",
";",
"return",
"isFilterMatch",
"(",
"nodestr",
",",
"pat",
")",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | This class accepts all composite nodes whose text contains a match for
the regex. | [
"This",
"class",
"accepts",
"all",
"composite",
"nodes",
"whose",
"text",
"contains",
"a",
"match",
"for",
"the",
"regex",
"."
] | [] | [
{
"param": "BaseRegexFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | HasAttributeRegexFilter | /**
* A filter that matches tags that have a specified attribute whose value
* matches a regex
*/ | A filter that matches tags that have a specified attribute whose value
matches a regex | [
"A",
"filter",
"that",
"matches",
"tags",
"that",
"have",
"a",
"specified",
"attribute",
"whose",
"value",
"matches",
"a",
"regex"
] | public static class HasAttributeRegexFilter extends BaseRegexFilter {
private String attr;
/**
* Creates a HasAttributeRegexFilter that accepts nodes whose specified
* attribute value matches a regex.
* The match is case insensitive.
* @param attr The attribute name
* @param regex The regex to match against the attribute value.
*/
public HasAttributeRegexFilter(String attr, String regex) {
this(attr, regex, true);
}
/**
* Creates a HasAttributeRegexFilter that accepts nodes whose specified
* attribute value matches a regex.
* @param attr The attribute name
* @param regex The regex to match against the attribute value.
* @param ignoreCase if true match is case insensitive
*/
public HasAttributeRegexFilter(String attr, String regex,
boolean ignoreCase) {
super(regex, ignoreCase);
this.attr = attr;
}
public boolean accept(Node node) {
if (node instanceof Tag) {
Tag tag = (Tag)node;
String attribute = tag.getAttribute(attr);
if (attribute != null) {
return isFilterMatch(attribute, pat);
}
}
return false;
}
} | [
"public",
"static",
"class",
"HasAttributeRegexFilter",
"extends",
"BaseRegexFilter",
"{",
"private",
"String",
"attr",
";",
"/**\n * Creates a HasAttributeRegexFilter that accepts nodes whose specified\n * attribute value matches a regex.\n * The match is case insensitive.\n * @param attr The attribute name\n * @param regex The regex to match against the attribute value.\n */",
"public",
"HasAttributeRegexFilter",
"(",
"String",
"attr",
",",
"String",
"regex",
")",
"{",
"this",
"(",
"attr",
",",
"regex",
",",
"true",
")",
";",
"}",
"/**\n * Creates a HasAttributeRegexFilter that accepts nodes whose specified\n * attribute value matches a regex.\n * @param attr The attribute name\n * @param regex The regex to match against the attribute value.\n * @param ignoreCase if true match is case insensitive\n */",
"public",
"HasAttributeRegexFilter",
"(",
"String",
"attr",
",",
"String",
"regex",
",",
"boolean",
"ignoreCase",
")",
"{",
"super",
"(",
"regex",
",",
"ignoreCase",
")",
";",
"this",
".",
"attr",
"=",
"attr",
";",
"}",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
"instanceof",
"Tag",
")",
"{",
"Tag",
"tag",
"=",
"(",
"Tag",
")",
"node",
";",
"String",
"attribute",
"=",
"tag",
".",
"getAttribute",
"(",
"attr",
")",
";",
"if",
"(",
"attribute",
"!=",
"null",
")",
"{",
"return",
"isFilterMatch",
"(",
"attribute",
",",
"pat",
")",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | A filter that matches tags that have a specified attribute whose value
matches a regex | [
"A",
"filter",
"that",
"matches",
"tags",
"that",
"have",
"a",
"specified",
"attribute",
"whose",
"value",
"matches",
"a",
"regex"
] | [] | [
{
"param": "BaseRegexFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseRegexFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3640126f6ace1b1d5bded2876cfa18e6d982ae | lockss/laaws-daemon | src/org/lockss/filter/html/HtmlNodeFilters.java | [
"BSD-3-Clause"
] | Java | AllExceptSubtreeNodeFilter | /**
* <p>
* This node filter selects all nodes in a target tree (characterized by a
* target root node filter), except for the nodes in a designated subtree
* (characterized by a designated subtree node filter) and all nodes on the
* direct path from the target root to the designated subtree.
* </p>
* <p>
* If used as the underlying node filter of an
* {@link HtmlNodeFilterTransform#exclude(NodeFilter)} transform, everything
* in the target tree will be excluded except for the designated subtree and
* the direct path to it from the target root (just enough to retain the
* original structure).
* </p>
* <p>
* Sample document:
* </p>
<pre>
<div id="a1">
<div id="a11">
<div id="a111">...</div>
<div id="a112">...</div>
<div id="a113">...</div>
</div>
<div id="a12">
<div id="a121">
<div id="a1211">...</div>
<div id="a1212">...</div>
<div id="a1213">...</div>
</div>
<div id="a122">
<div id="a1221">...</div>
<div id="a1222">...</div>
<div id="a1223">...</div>
</div>
<div id="a123">
<div id="a1231">...</div>
<div id="a1232">...</div>
<div id="a1233">...</div>
</div>
</div>
<div id="a13">
<div id="a131">...</div>
<div id="a132">...</div>
<div id="a133">...</div>
</div>
</div>
</pre>
* <p>
* This code will focus its attention on the tree rooted at a12 but will
* protect the subtree rooted at a122, by selecting a121, a1211, a1212, a1213,
* a123, a1231, a1232, a1233, but not a122, a1221, a1222, a1223, nor a12, nor
* anything higher than a12 (like a11 and all its contents and a13 and all its
* contents):
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a12"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a122"));
</pre>
* <p>
* This code will select absolutely everything in the tree rooted at a12,
* because there is no subtree "a99" to protect, nor a path to it:
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a12"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a99"));
</pre>
* <p>
* This code will select absolutely nothing, because there is no target tree
* "a99" to flag:
* </p>
<pre>
NodeFilter nf =
new AllExceptSubtreeNodeFilter(
HtmlNodeFilters.tagWithAttribute("div", "id", "a99"),
HtmlNodeFilters.tagWithAttribute("div", "id", "a122"));
</pre>
*
* @since 1.65.4
*/ |
This node filter selects all nodes in a target tree (characterized by a
target root node filter), except for the nodes in a designated subtree
(characterized by a designated subtree node filter) and all nodes on the
direct path from the target root to the designated subtree.
If used as the underlying node filter of an
HtmlNodeFilterTransform#exclude(NodeFilter) transform, everything
in the target tree will be excluded except for the designated subtree and
the direct path to it from the target root (just enough to retain the
original structure).
| [
"This",
"node",
"filter",
"selects",
"all",
"nodes",
"in",
"a",
"target",
"tree",
"(",
"characterized",
"by",
"a",
"target",
"root",
"node",
"filter",
")",
"except",
"for",
"the",
"nodes",
"in",
"a",
"designated",
"subtree",
"(",
"characterized",
"by",
"a",
"designated",
"subtree",
"node",
"filter",
")",
"and",
"all",
"nodes",
"on",
"the",
"direct",
"path",
"from",
"the",
"target",
"root",
"to",
"the",
"designated",
"subtree",
".",
"If",
"used",
"as",
"the",
"underlying",
"node",
"filter",
"of",
"an",
"HtmlNodeFilterTransform#exclude",
"(",
"NodeFilter",
")",
"transform",
"everything",
"in",
"the",
"target",
"tree",
"will",
"be",
"excluded",
"except",
"for",
"the",
"designated",
"subtree",
"and",
"the",
"direct",
"path",
"to",
"it",
"from",
"the",
"target",
"root",
"(",
"just",
"enough",
"to",
"retain",
"the",
"original",
"structure",
")",
"."
] | public static class AllExceptSubtreeNodeFilter implements NodeFilter {
/**
* <p>
* A node filter characterizing the target root.
* </p>
*/
protected NodeFilter rootNodeFilter;
/**
* <p>
* A node filter characterizing the designated subtree.
* </p>
*/
protected NodeFilter subtreeNodeFilter;
/**
* <p>
* Builds a node filter that will select all nodes in the target tree
* (rooted at the node characterized by the target root node filter), except
* for the nodes in the designated subtree characterized by the subtree node
* filter and any nodes in the direct path from the target root node to the
* designated subtree.
* </p>
*
* @param rootNodeFilter
* A node filter characterizing the target root.
* @param subtreeNodeFilter
* A node filter characterizing the designated subtree.
*/
public AllExceptSubtreeNodeFilter(NodeFilter rootNodeFilter,
NodeFilter subtreeNodeFilter) {
this.rootNodeFilter = rootNodeFilter;
this.subtreeNodeFilter = subtreeNodeFilter;
}
@Override
public boolean accept(Node node) {
// Inspect the node's ancestors
for (Node current = node ; current != null ; current = current.getParent()) {
if (subtreeNodeFilter.accept(current)) {
// The node is in the designated subtree: don't select it (meaning,
// return false).
return false;
}
if (rootNodeFilter.accept(current)) {
// The node is in the target tree. Selecting it or not depends on
// whether it is on the path from the target root to the designated
// subtree or not.
NodeList nl = new NodeList();
node.collectInto(nl, subtreeNodeFilter);
// If the node list is empty, the node is not on the path from the
// target root to the designated subtree: select it (meaning, return
// true). If the node list is non-empty, the node is on the path from
// the target root to the designated subtree: don't select it
// (meaning, return false). In other words, return the result of
// asking if the node list is empty.
return nl.size() == 0;
}
}
// The node is not under the target root: don't select it (meaning,
// return false).
return false;
}
} | [
"public",
"static",
"class",
"AllExceptSubtreeNodeFilter",
"implements",
"NodeFilter",
"{",
"/**\n * <p>\n * A node filter characterizing the target root.\n * </p>\n */",
"protected",
"NodeFilter",
"rootNodeFilter",
";",
"/**\n * <p>\n * A node filter characterizing the designated subtree.\n * </p>\n */",
"protected",
"NodeFilter",
"subtreeNodeFilter",
";",
"/**\n * <p>\n * Builds a node filter that will select all nodes in the target tree\n * (rooted at the node characterized by the target root node filter), except\n * for the nodes in the designated subtree characterized by the subtree node\n * filter and any nodes in the direct path from the target root node to the\n * designated subtree.\n * </p>\n * \n * @param rootNodeFilter\n * A node filter characterizing the target root.\n * @param subtreeNodeFilter\n * A node filter characterizing the designated subtree.\n */",
"public",
"AllExceptSubtreeNodeFilter",
"(",
"NodeFilter",
"rootNodeFilter",
",",
"NodeFilter",
"subtreeNodeFilter",
")",
"{",
"this",
".",
"rootNodeFilter",
"=",
"rootNodeFilter",
";",
"this",
".",
"subtreeNodeFilter",
"=",
"subtreeNodeFilter",
";",
"}",
"@",
"Override",
"public",
"boolean",
"accept",
"(",
"Node",
"node",
")",
"{",
"for",
"(",
"Node",
"current",
"=",
"node",
";",
"current",
"!=",
"null",
";",
"current",
"=",
"current",
".",
"getParent",
"(",
")",
")",
"{",
"if",
"(",
"subtreeNodeFilter",
".",
"accept",
"(",
"current",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"rootNodeFilter",
".",
"accept",
"(",
"current",
")",
")",
"{",
"NodeList",
"nl",
"=",
"new",
"NodeList",
"(",
")",
";",
"node",
".",
"collectInto",
"(",
"nl",
",",
"subtreeNodeFilter",
")",
";",
"return",
"nl",
".",
"size",
"(",
")",
"==",
"0",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] | <p>
This node filter selects all nodes in a target tree (characterized by a
target root node filter), except for the nodes in a designated subtree
(characterized by a designated subtree node filter) and all nodes on the
direct path from the target root to the designated subtree. | [
"<p",
">",
"This",
"node",
"filter",
"selects",
"all",
"nodes",
"in",
"a",
"target",
"tree",
"(",
"characterized",
"by",
"a",
"target",
"root",
"node",
"filter",
")",
"except",
"for",
"the",
"nodes",
"in",
"a",
"designated",
"subtree",
"(",
"characterized",
"by",
"a",
"designated",
"subtree",
"node",
"filter",
")",
"and",
"all",
"nodes",
"on",
"the",
"direct",
"path",
"from",
"the",
"target",
"root",
"to",
"the",
"designated",
"subtree",
"."
] | [
"// Inspect the node's ancestors",
"// The node is in the designated subtree: don't select it (meaning,",
"// return false).",
"// The node is in the target tree. Selecting it or not depends on",
"// whether it is on the path from the target root to the designated",
"// subtree or not.",
"// If the node list is empty, the node is not on the path from the",
"// target root to the designated subtree: select it (meaning, return",
"// true). If the node list is non-empty, the node is on the path from",
"// the target root to the designated subtree: don't select it",
"// (meaning, return false). In other words, return the result of",
"// asking if the node list is empty.",
"// The node is not under the target root: don't select it (meaning,",
"// return false)."
] | [
{
"param": "NodeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd380441376a0b6974ca97b556068545f6be8581 | OpenBEL/openbel-framework | org.openbel.bel/src/main/java/org/openbel/bel/model/BELStatementGroup.java | [
"Apache-2.0"
] | Java | BELStatementGroup | /**
* BELStatementGroup represents a grouping {@link BELStatement} objects
* captured in BEL Script.
*
* @author Anthony Bargnesi {@code <abargnesi@selventa.com>}
*/ | BELStatementGroup represents a grouping BELStatement objects
captured in BEL Script.
@author Anthony Bargnesi | [
"BELStatementGroup",
"represents",
"a",
"grouping",
"BELStatement",
"objects",
"captured",
"in",
"BEL",
"Script",
".",
"@author",
"Anthony",
"Bargnesi"
] | public class BELStatementGroup extends BELObject {
private static final long serialVersionUID = 6692242897768495050L;
private final String name;
private final List<BELStatement> statements = new ArrayList<BELStatement>();
private List<BELStatementGroup> childStatementGroups =
new ArrayList<BELStatementGroup>();
public BELStatementGroup() {
this.name = null;
}
public BELStatementGroup(final String name) {
this.name = name;
}
/**
* Returns the statement group's name.
*
* @return {@link String} the statement group name, which may be null
*/
public String getName() {
return name;
}
/**
* Returns the statement group's statements.
*
* @return {@link List} of {@link BELStatement}s, which may be null
*/
public List<BELStatement> getStatements() {
return statements;
}
/**
* Returns the statement group's child statement groups.
*
* @return {@link List} of {@link BELStatementGroup}, which may be null
*/
public List<BELStatementGroup> getChildStatementGroups() {
return childStatementGroups;
}
/**
* Sets the statement group's child statement groups.
*
* @param childStatementGroups {@link List} of {@link BELStatementGroup} the
* child statement groups, which can be null
*/
public void setChildStatementGroups(
List<BELStatementGroup> childStatementGroups) {
this.childStatementGroups = childStatementGroups;
}
} | [
"public",
"class",
"BELStatementGroup",
"extends",
"BELObject",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"6692242897768495050L",
";",
"private",
"final",
"String",
"name",
";",
"private",
"final",
"List",
"<",
"BELStatement",
">",
"statements",
"=",
"new",
"ArrayList",
"<",
"BELStatement",
">",
"(",
")",
";",
"private",
"List",
"<",
"BELStatementGroup",
">",
"childStatementGroups",
"=",
"new",
"ArrayList",
"<",
"BELStatementGroup",
">",
"(",
")",
";",
"public",
"BELStatementGroup",
"(",
")",
"{",
"this",
".",
"name",
"=",
"null",
";",
"}",
"public",
"BELStatementGroup",
"(",
"final",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"/**\n * Returns the statement group's name.\n *\n * @return {@link String} the statement group name, which may be null\n */",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"name",
";",
"}",
"/**\n * Returns the statement group's statements.\n *\n * @return {@link List} of {@link BELStatement}s, which may be null\n */",
"public",
"List",
"<",
"BELStatement",
">",
"getStatements",
"(",
")",
"{",
"return",
"statements",
";",
"}",
"/**\n * Returns the statement group's child statement groups.\n *\n * @return {@link List} of {@link BELStatementGroup}, which may be null\n */",
"public",
"List",
"<",
"BELStatementGroup",
">",
"getChildStatementGroups",
"(",
")",
"{",
"return",
"childStatementGroups",
";",
"}",
"/**\n * Sets the statement group's child statement groups.\n *\n * @param childStatementGroups {@link List} of {@link BELStatementGroup} the\n * child statement groups, which can be null\n */",
"public",
"void",
"setChildStatementGroups",
"(",
"List",
"<",
"BELStatementGroup",
">",
"childStatementGroups",
")",
"{",
"this",
".",
"childStatementGroups",
"=",
"childStatementGroups",
";",
"}",
"}"
] | BELStatementGroup represents a grouping {@link BELStatement} objects
captured in BEL Script. | [
"BELStatementGroup",
"represents",
"a",
"grouping",
"{",
"@link",
"BELStatement",
"}",
"objects",
"captured",
"in",
"BEL",
"Script",
"."
] | [] | [
{
"param": "BELObject",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BELObject",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd38d058da84e814f9e71c7cbb4783c4dd1ee4a2 | InsightEdge/xap | xap-core/xap-openspaces/src/main/java/org/openspaces/core/properties/BeanLevelProperties.java | [
"Apache-2.0"
] | Java | BeanLevelProperties | /**
* An extension to Spring support for properties based configuration. This is a properties holder
* that can have both context level properties and bean specific (mapped based on the bean name)
* properties.
*
* @author kimchy
* @see BeanLevelPropertiesAware
* @see BeanLevelPropertyPlaceholderConfigurer
*/ | An extension to Spring support for properties based configuration. This is a properties holder
that can have both context level properties and bean specific (mapped based on the bean name)
properties.
| [
"An",
"extension",
"to",
"Spring",
"support",
"for",
"properties",
"based",
"configuration",
".",
"This",
"is",
"a",
"properties",
"holder",
"that",
"can",
"have",
"both",
"context",
"level",
"properties",
"and",
"bean",
"specific",
"(",
"mapped",
"based",
"on",
"the",
"bean",
"name",
")",
"properties",
"."
] | public class BeanLevelProperties implements Serializable {
private static final long serialVersionUID = -5373882281270584863L;
private Properties contextProperties = new Properties();
private Map<String, Properties> beanProperties = new HashMap<String, Properties>();
/**
* Returns the Spring context level properties.
*/
public Properties getContextProperties() {
return contextProperties;
}
/**
* Sets the Spring context level properties.
*/
public void setContextProperties(Properties contextProperties) {
this.contextProperties = contextProperties;
}
/**
* Returns properties that are associated with a specific bean name. If the properties do not
* exists, they will be created and bounded to the bean name.
*
* @param beanName The bean name to get the properties for
* @return The properties assigned to the bean
*/
public Properties getBeanProperties(String beanName) {
Properties props = beanProperties.get(beanName);
if (props == null) {
props = new Properties();
beanProperties.put(beanName, props);
}
return props;
}
/**
* Sets properties that will be associated with the given bean name.
*
* @param beanName The bean name to bind the properties to
* @param nameBasedProperties The properties associated with the bean name
*/
public void setBeanProperties(String beanName, Properties nameBasedProperties) {
this.beanProperties.put(beanName, nameBasedProperties);
}
/**
* Returns <code>true</code> if there are properties associated with the given bean name.
*
* @param beanName The bean name to check if there are properties associated with it
* @return <code>true</code> if there are properties associated with the bean name
*/
public boolean hasBeanProperties(String beanName) {
return getBeanProperties(beanName).size() != 0;
}
/**
* Returns merged properties between the Spring context level properties and the bean level
* properties associated with the provided bean name. The bean level properties will override
* existing properties defined in the context level properties.
*
* @param beanName The bean name to return the merged properties for
* @return Merged properties of the bean level properties and context properties for the given
* bean name
*/
public Properties getMergedBeanProperties(String beanName) {
Properties props = new Properties();
props.putAll(contextProperties);
Properties nameBasedProperties = getBeanProperties(beanName);
if (nameBasedProperties != null) {
props.putAll(nameBasedProperties);
}
return props;
}
public Map<String, Properties> getBeans() {
return Collections.synchronizedMap(beanProperties);
}
public String toString() {
return "Context " + SanitizeUtil.sanitize(contextProperties, "password", "EncryptionKey")
+ " Beans " + SanitizeUtil.sanitize(beanProperties, "password", "EncryptionKey");
}
} | [
"public",
"class",
"BeanLevelProperties",
"implements",
"Serializable",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"-",
"5373882281270584863L",
";",
"private",
"Properties",
"contextProperties",
"=",
"new",
"Properties",
"(",
")",
";",
"private",
"Map",
"<",
"String",
",",
"Properties",
">",
"beanProperties",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Properties",
">",
"(",
")",
";",
"/**\n * Returns the Spring context level properties.\n */",
"public",
"Properties",
"getContextProperties",
"(",
")",
"{",
"return",
"contextProperties",
";",
"}",
"/**\n * Sets the Spring context level properties.\n */",
"public",
"void",
"setContextProperties",
"(",
"Properties",
"contextProperties",
")",
"{",
"this",
".",
"contextProperties",
"=",
"contextProperties",
";",
"}",
"/**\n * Returns properties that are associated with a specific bean name. If the properties do not\n * exists, they will be created and bounded to the bean name.\n *\n * @param beanName The bean name to get the properties for\n * @return The properties assigned to the bean\n */",
"public",
"Properties",
"getBeanProperties",
"(",
"String",
"beanName",
")",
"{",
"Properties",
"props",
"=",
"beanProperties",
".",
"get",
"(",
"beanName",
")",
";",
"if",
"(",
"props",
"==",
"null",
")",
"{",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"beanProperties",
".",
"put",
"(",
"beanName",
",",
"props",
")",
";",
"}",
"return",
"props",
";",
"}",
"/**\n * Sets properties that will be associated with the given bean name.\n *\n * @param beanName The bean name to bind the properties to\n * @param nameBasedProperties The properties associated with the bean name\n */",
"public",
"void",
"setBeanProperties",
"(",
"String",
"beanName",
",",
"Properties",
"nameBasedProperties",
")",
"{",
"this",
".",
"beanProperties",
".",
"put",
"(",
"beanName",
",",
"nameBasedProperties",
")",
";",
"}",
"/**\n * Returns <code>true</code> if there are properties associated with the given bean name.\n *\n * @param beanName The bean name to check if there are properties associated with it\n * @return <code>true</code> if there are properties associated with the bean name\n */",
"public",
"boolean",
"hasBeanProperties",
"(",
"String",
"beanName",
")",
"{",
"return",
"getBeanProperties",
"(",
"beanName",
")",
".",
"size",
"(",
")",
"!=",
"0",
";",
"}",
"/**\n * Returns merged properties between the Spring context level properties and the bean level\n * properties associated with the provided bean name. The bean level properties will override\n * existing properties defined in the context level properties.\n *\n * @param beanName The bean name to return the merged properties for\n * @return Merged properties of the bean level properties and context properties for the given\n * bean name\n */",
"public",
"Properties",
"getMergedBeanProperties",
"(",
"String",
"beanName",
")",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"props",
".",
"putAll",
"(",
"contextProperties",
")",
";",
"Properties",
"nameBasedProperties",
"=",
"getBeanProperties",
"(",
"beanName",
")",
";",
"if",
"(",
"nameBasedProperties",
"!=",
"null",
")",
"{",
"props",
".",
"putAll",
"(",
"nameBasedProperties",
")",
";",
"}",
"return",
"props",
";",
"}",
"public",
"Map",
"<",
"String",
",",
"Properties",
">",
"getBeans",
"(",
")",
"{",
"return",
"Collections",
".",
"synchronizedMap",
"(",
"beanProperties",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"Context ",
"\"",
"+",
"SanitizeUtil",
".",
"sanitize",
"(",
"contextProperties",
",",
"\"",
"password",
"\"",
",",
"\"",
"EncryptionKey",
"\"",
")",
"+",
"\"",
" Beans ",
"\"",
"+",
"SanitizeUtil",
".",
"sanitize",
"(",
"beanProperties",
",",
"\"",
"password",
"\"",
",",
"\"",
"EncryptionKey",
"\"",
")",
";",
"}",
"}"
] | An extension to Spring support for properties based configuration. | [
"An",
"extension",
"to",
"Spring",
"support",
"for",
"properties",
"based",
"configuration",
"."
] | [] | [
{
"param": "Serializable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd39a63722869e896efc652dd63959f2e00fff15 | computingfoundation/android-client-server-application-development | main/core/modules/commons/src/java/com/organization/commons/base/LowercaseEnumDeserializerModifier.java | [
"MIT"
] | Java | LowercaseEnumDeserializerModifier | /**
* Allows lowercase to be used when deserializing enums
*/ | Allows lowercase to be used when deserializing enums | [
"Allows",
"lowercase",
"to",
"be",
"used",
"when",
"deserializing",
"enums"
] | public class LowercaseEnumDeserializerModifier extends BeanDeserializerModifier {
@Override
public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config, final JavaType type,
BeanDescription beanDesc,
final JsonDeserializer<?> deserializer) {
return new JsonDeserializer<Enum>() {
@Override
public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
}
};
}
} | [
"public",
"class",
"LowercaseEnumDeserializerModifier",
"extends",
"BeanDeserializerModifier",
"{",
"@",
"Override",
"public",
"JsonDeserializer",
"<",
"Enum",
">",
"modifyEnumDeserializer",
"(",
"DeserializationConfig",
"config",
",",
"final",
"JavaType",
"type",
",",
"BeanDescription",
"beanDesc",
",",
"final",
"JsonDeserializer",
"<",
"?",
">",
"deserializer",
")",
"{",
"return",
"new",
"JsonDeserializer",
"<",
"Enum",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Enum",
"deserialize",
"(",
"JsonParser",
"jp",
",",
"DeserializationContext",
"ctxt",
")",
"throws",
"IOException",
"{",
"Class",
"<",
"?",
"extends",
"Enum",
">",
"rawClass",
"=",
"(",
"Class",
"<",
"Enum",
"<",
"?",
">",
">",
")",
"type",
".",
"getRawClass",
"(",
")",
";",
"return",
"Enum",
".",
"valueOf",
"(",
"rawClass",
",",
"jp",
".",
"getValueAsString",
"(",
")",
".",
"toUpperCase",
"(",
")",
")",
";",
"}",
"}",
";",
"}",
"}"
] | Allows lowercase to be used when deserializing enums | [
"Allows",
"lowercase",
"to",
"be",
"used",
"when",
"deserializing",
"enums"
] | [] | [
{
"param": "BeanDeserializerModifier",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BeanDeserializerModifier",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd3d8e2dec5907840dd9f8c16149fb8f785c15eb | aclowkey/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlCompleteLogoutRequest.java | [
"Apache-2.0"
] | Java | SamlCompleteLogoutRequest | /**
* Represents a request to complete SAML LogoutResponse
*/ | Represents a request to complete SAML LogoutResponse | [
"Represents",
"a",
"request",
"to",
"complete",
"SAML",
"LogoutResponse"
] | public final class SamlCompleteLogoutRequest extends ActionRequest {
@Nullable
private String queryString;
@Nullable
private String content;
private List<String> validRequestIds;
private String realm;
public SamlCompleteLogoutRequest(StreamInput in) throws IOException {
super(in);
}
public SamlCompleteLogoutRequest() {
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (Strings.hasText(realm) == false) {
validationException = addValidationError("realm may not be empty", validationException);
}
if (Strings.hasText(queryString) == false && Strings.hasText(content) == false) {
validationException = addValidationError("queryString and content may not both be empty", validationException);
}
if (Strings.hasText(queryString) && Strings.hasText(content)) {
validationException = addValidationError("queryString and content may not both present", validationException);
}
return validationException;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getValidRequestIds() {
return validRequestIds;
}
public void setValidRequestIds(List<String> validRequestIds) {
this.validRequestIds = validRequestIds;
}
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
public boolean isHttpRedirect() {
return queryString != null;
}
public String getPayload() {
return isHttpRedirect() ? queryString : content;
}
} | [
"public",
"final",
"class",
"SamlCompleteLogoutRequest",
"extends",
"ActionRequest",
"{",
"@",
"Nullable",
"private",
"String",
"queryString",
";",
"@",
"Nullable",
"private",
"String",
"content",
";",
"private",
"List",
"<",
"String",
">",
"validRequestIds",
";",
"private",
"String",
"realm",
";",
"public",
"SamlCompleteLogoutRequest",
"(",
"StreamInput",
"in",
")",
"throws",
"IOException",
"{",
"super",
"(",
"in",
")",
";",
"}",
"public",
"SamlCompleteLogoutRequest",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"ActionRequestValidationException",
"validate",
"(",
")",
"{",
"ActionRequestValidationException",
"validationException",
"=",
"null",
";",
"if",
"(",
"Strings",
".",
"hasText",
"(",
"realm",
")",
"==",
"false",
")",
"{",
"validationException",
"=",
"addValidationError",
"(",
"\"",
"realm may not be empty",
"\"",
",",
"validationException",
")",
";",
"}",
"if",
"(",
"Strings",
".",
"hasText",
"(",
"queryString",
")",
"==",
"false",
"&&",
"Strings",
".",
"hasText",
"(",
"content",
")",
"==",
"false",
")",
"{",
"validationException",
"=",
"addValidationError",
"(",
"\"",
"queryString and content may not both be empty",
"\"",
",",
"validationException",
")",
";",
"}",
"if",
"(",
"Strings",
".",
"hasText",
"(",
"queryString",
")",
"&&",
"Strings",
".",
"hasText",
"(",
"content",
")",
")",
"{",
"validationException",
"=",
"addValidationError",
"(",
"\"",
"queryString and content may not both present",
"\"",
",",
"validationException",
")",
";",
"}",
"return",
"validationException",
";",
"}",
"public",
"String",
"getQueryString",
"(",
")",
"{",
"return",
"queryString",
";",
"}",
"public",
"void",
"setQueryString",
"(",
"String",
"queryString",
")",
"{",
"this",
".",
"queryString",
"=",
"queryString",
";",
"}",
"public",
"String",
"getContent",
"(",
")",
"{",
"return",
"content",
";",
"}",
"public",
"void",
"setContent",
"(",
"String",
"content",
")",
"{",
"this",
".",
"content",
"=",
"content",
";",
"}",
"public",
"List",
"<",
"String",
">",
"getValidRequestIds",
"(",
")",
"{",
"return",
"validRequestIds",
";",
"}",
"public",
"void",
"setValidRequestIds",
"(",
"List",
"<",
"String",
">",
"validRequestIds",
")",
"{",
"this",
".",
"validRequestIds",
"=",
"validRequestIds",
";",
"}",
"public",
"String",
"getRealm",
"(",
")",
"{",
"return",
"realm",
";",
"}",
"public",
"void",
"setRealm",
"(",
"String",
"realm",
")",
"{",
"this",
".",
"realm",
"=",
"realm",
";",
"}",
"public",
"boolean",
"isHttpRedirect",
"(",
")",
"{",
"return",
"queryString",
"!=",
"null",
";",
"}",
"public",
"String",
"getPayload",
"(",
")",
"{",
"return",
"isHttpRedirect",
"(",
")",
"?",
"queryString",
":",
"content",
";",
"}",
"}"
] | Represents a request to complete SAML LogoutResponse | [
"Represents",
"a",
"request",
"to",
"complete",
"SAML",
"LogoutResponse"
] | [] | [
{
"param": "ActionRequest",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ActionRequest",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd4012a50568d126bcc8f9fd7b2d2f7f6bca8b86 | iamckn-mobile/Catlog | Catlog/src/com/nolanlawson/logcat/data/LogLineViewWrapper.java | [
"WTFPL"
] | Java | LogLineViewWrapper | /**
* Improves performance of the ListView. Watch Romain Guy's video about ListView to learn more.
* @author nlawson
*
*/ | Improves performance of the ListView. Watch Romain Guy's video about ListView to learn more.
@author nlawson | [
"Improves",
"performance",
"of",
"the",
"ListView",
".",
"Watch",
"Romain",
"Guy",
"'",
"s",
"video",
"about",
"ListView",
"to",
"learn",
"more",
".",
"@author",
"nlawson"
] | public class LogLineViewWrapper {
private View view;
private TextView levelTextView;
private TextView outputTextView;
private TextView tagTextView;
private TextView pidTextView;
private TextView timestampTextView;
public LogLineViewWrapper(View view) {
this.view = view;
}
public TextView getPidTextView() {
if (pidTextView == null) {
pidTextView = (TextView) view.findViewById(R.id.pid_text);
}
return pidTextView;
}
public TextView getTimestampTextView() {
if (timestampTextView == null) {
timestampTextView = (TextView) view.findViewById(R.id.timestamp_text);
}
return timestampTextView;
}
public TextView getTagTextView() {
if (tagTextView == null) {
tagTextView = (TextView) view.findViewById(R.id.tag_text);
}
return tagTextView;
}
public TextView getLevelTextView() {
if (levelTextView == null) {
levelTextView = (TextView) view.findViewById(R.id.log_level_text);
}
return levelTextView;
}
public TextView getOutputTextView() {
if (outputTextView == null) {
outputTextView = (TextView) view.findViewById(R.id.log_output_text);
}
return outputTextView;
}
} | [
"public",
"class",
"LogLineViewWrapper",
"{",
"private",
"View",
"view",
";",
"private",
"TextView",
"levelTextView",
";",
"private",
"TextView",
"outputTextView",
";",
"private",
"TextView",
"tagTextView",
";",
"private",
"TextView",
"pidTextView",
";",
"private",
"TextView",
"timestampTextView",
";",
"public",
"LogLineViewWrapper",
"(",
"View",
"view",
")",
"{",
"this",
".",
"view",
"=",
"view",
";",
"}",
"public",
"TextView",
"getPidTextView",
"(",
")",
"{",
"if",
"(",
"pidTextView",
"==",
"null",
")",
"{",
"pidTextView",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"pid_text",
")",
";",
"}",
"return",
"pidTextView",
";",
"}",
"public",
"TextView",
"getTimestampTextView",
"(",
")",
"{",
"if",
"(",
"timestampTextView",
"==",
"null",
")",
"{",
"timestampTextView",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"timestamp_text",
")",
";",
"}",
"return",
"timestampTextView",
";",
"}",
"public",
"TextView",
"getTagTextView",
"(",
")",
"{",
"if",
"(",
"tagTextView",
"==",
"null",
")",
"{",
"tagTextView",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"tag_text",
")",
";",
"}",
"return",
"tagTextView",
";",
"}",
"public",
"TextView",
"getLevelTextView",
"(",
")",
"{",
"if",
"(",
"levelTextView",
"==",
"null",
")",
"{",
"levelTextView",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"log_level_text",
")",
";",
"}",
"return",
"levelTextView",
";",
"}",
"public",
"TextView",
"getOutputTextView",
"(",
")",
"{",
"if",
"(",
"outputTextView",
"==",
"null",
")",
"{",
"outputTextView",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"log_output_text",
")",
";",
"}",
"return",
"outputTextView",
";",
"}",
"}"
] | Improves performance of the ListView. | [
"Improves",
"performance",
"of",
"the",
"ListView",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd40dfebb43dd93e83015c4dd84dbbf2c9b4fc0a | brettdavidson3/eclipselink.runtime | jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/UpdateItem.java | [
"BSD-3-Clause"
] | Java | UpdateItem | /**
* The <code>new_value</code> specified for an update operation must be compatible in type with the
* field to which it is assigned.
*
* <div nowrap><b>BNF:</b> <code>update_item ::= [identification_variable.]{state_field | single_valued_association_field} = new_value</code><p>
*
* @see UpdateClause
*
* @version 2.5
* @since 2.3
* @author Pascal Filion
*/ | The new_value specified for an update operation must be compatible in type with the
field to which it is assigned.
| [
"The",
"new_value",
"specified",
"for",
"an",
"update",
"operation",
"must",
"be",
"compatible",
"in",
"type",
"with",
"the",
"field",
"to",
"which",
"it",
"is",
"assigned",
"."
] | public final class UpdateItem extends AbstractExpression {
/**
* Determines whether the equal sign was parsed or not.
*/
private boolean hasEqualSign;
/**
* Determines whether a whitespace was parsed after the equal sign or not.
*/
private boolean hasSpaceAfterEqualSign;
/**
* Determines whether a whitespace was parsed before the equal sign or not
*/
private boolean hasSpaceAfterStateFieldPathExpression;
/**
* The expression representing the new value.
*/
private AbstractExpression newValue;
/**
* The expression representing the state field to have its value updated.
*/
private AbstractExpression stateFieldExpression;
/**
* Creates a new <code>UpdateItem</code>.
*
* @param parent The parent of this expression
*/
public UpdateItem(AbstractExpression parent) {
super(parent);
}
/**
* {@inheritDoc}
*/
public void accept(ExpressionVisitor visitor) {
visitor.visit(this);
}
/**
* {@inheritDoc}
*/
public void acceptChildren(ExpressionVisitor visitor) {
getStateFieldPathExpression().accept(visitor);
getNewValue().accept(visitor);
}
/**
* {@inheritDoc}
*/
@Override
protected void addChildrenTo(Collection<Expression> children) {
children.add(getStateFieldPathExpression());
children.add(getNewValue());
}
/**
* {@inheritDoc}
*/
@Override
protected void addOrderedChildrenTo(List<Expression> children) {
// State field expression
if (stateFieldExpression != null) {
children.add(stateFieldExpression);
}
if (hasSpaceAfterStateFieldPathExpression) {
children.add(buildStringExpression(SPACE));
}
// '='
if (hasEqualSign) {
children.add(buildStringExpression(EQUAL));
}
if (hasSpaceAfterEqualSign) {
children.add(buildStringExpression(SPACE));
}
// New value
if (newValue != null) {
children.add(newValue);
}
}
/**
* {@inheritDoc}
*/
@Override
public JPQLQueryBNF findQueryBNF(Expression expression) {
if ((stateFieldExpression != null) && stateFieldExpression.isAncestor(expression)) {
return getQueryBNF(UpdateItemStateFieldPathExpressionBNF.ID);
}
if ((newValue != null) && newValue.isAncestor(expression)) {
return getQueryBNF(NewValueBNF.ID);
}
return super.findQueryBNF(expression);
}
/**
* Returns the {@link Expression} representing the new value, which is the new value of the property.
*
* @return The expression for the new value
*/
public Expression getNewValue() {
if (newValue == null) {
newValue = buildNullExpression();
}
return newValue;
}
/**
* {@inheritDoc}
*/
public JPQLQueryBNF getQueryBNF() {
return getQueryBNF(UpdateItemBNF.ID);
}
/**
* Returns the {@link Expression} representing the state field path expression, which is the
* property that should get updated.
*
* @return The expression for the state field path expression
*/
public Expression getStateFieldPathExpression() {
if (stateFieldExpression == null) {
stateFieldExpression = buildNullExpression();
}
return stateFieldExpression;
}
/**
* Determines whether the equal sign was parsed or not.
*
* @return <code>true</code> if the equal sign was parsed; <code>false</code> otherwise
*/
public boolean hasEqualSign() {
return hasEqualSign;
}
/**
* Determines whether the new value section of the query was parsed.
*
* @return <code>true</code> the new value was parsed; <code>false</code> if nothing was parsed
*/
public boolean hasNewValue() {
return newValue != null &&
!newValue.isNull();
}
/**
* Determines whether a whitespace was parsed after the equal sign or not.
*
* @return <code>true</code> if there was a whitespace after the equal sign; <code>false</code> otherwise
*/
public boolean hasSpaceAfterEqualSign() {
return hasSpaceAfterEqualSign;
}
/**
* Determines whether a whitespace was parsed after the state field path expression not.
*
* @return <code>true</code> if there was a whitespace after the state field path expression;
* <code>false</code> otherwise
*/
public boolean hasSpaceAfterStateFieldPathExpression() {
return hasSpaceAfterStateFieldPathExpression;
}
/**
* Determines whether the state field was parsed.
*
* @return <code>true</code> the state field was parsed; <code>false</code> otherwise
*/
public boolean hasStateFieldPathExpression() {
return stateFieldExpression != null &&
!stateFieldExpression.isNull();
}
/**
* {@inheritDoc}
*/
@Override
protected boolean isParsingComplete(WordParser wordParser, String word, Expression expression) {
return word.equals(EQUAL) ||
super.isParsingComplete(wordParser, word, expression);
}
/**
* {@inheritDoc}
*/
@Override
protected void parse(WordParser wordParser, boolean tolerant) {
// Parse state field
if (tolerant) {
stateFieldExpression = parse(wordParser, UpdateItemStateFieldPathExpressionBNF.ID, tolerant);
}
else {
stateFieldExpression = new StateFieldPathExpression(this, wordParser.word());
stateFieldExpression.parse(wordParser, tolerant);
}
hasSpaceAfterStateFieldPathExpression = wordParser.skipLeadingWhitespace() > 0;
// Parse '='
hasEqualSign = wordParser.startsWith(EQUAL);
if (hasEqualSign) {
wordParser.moveForward(1);
hasSpaceAfterEqualSign = wordParser.skipLeadingWhitespace() > 0;
if (stateFieldExpression != null) {
hasSpaceAfterStateFieldPathExpression = true;
}
}
// Parse new value
newValue = parse(wordParser, NewValueBNF.ID, tolerant);
if (!hasSpaceAfterEqualSign && (newValue != null)) {
hasSpaceAfterEqualSign = true;
}
}
/**
* {@inheritDoc}
*/
@Override
protected void toParsedText(StringBuilder writer, boolean actual) {
// State field expression
if (stateFieldExpression != null) {
stateFieldExpression.toParsedText(writer, actual);
}
if (hasSpaceAfterStateFieldPathExpression) {
writer.append(SPACE);
}
// '='
if (hasEqualSign) {
writer.append(EQUAL);
}
if (hasSpaceAfterEqualSign) {
writer.append(SPACE);
}
// New value
if (newValue != null) {
newValue.toParsedText(writer, actual);
}
}
} | [
"public",
"final",
"class",
"UpdateItem",
"extends",
"AbstractExpression",
"{",
"/**\r\n\t * Determines whether the equal sign was parsed or not.\r\n\t */",
"private",
"boolean",
"hasEqualSign",
";",
"/**\r\n\t * Determines whether a whitespace was parsed after the equal sign or not.\r\n\t */",
"private",
"boolean",
"hasSpaceAfterEqualSign",
";",
"/**\r\n\t * Determines whether a whitespace was parsed before the equal sign or not\r\n\t */",
"private",
"boolean",
"hasSpaceAfterStateFieldPathExpression",
";",
"/**\r\n\t * The expression representing the new value.\r\n\t */",
"private",
"AbstractExpression",
"newValue",
";",
"/**\r\n\t * The expression representing the state field to have its value updated.\r\n\t */",
"private",
"AbstractExpression",
"stateFieldExpression",
";",
"/**\r\n\t * Creates a new <code>UpdateItem</code>.\r\n\t *\r\n\t * @param parent The parent of this expression\r\n\t */",
"public",
"UpdateItem",
"(",
"AbstractExpression",
"parent",
")",
"{",
"super",
"(",
"parent",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"public",
"void",
"accept",
"(",
"ExpressionVisitor",
"visitor",
")",
"{",
"visitor",
".",
"visit",
"(",
"this",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"public",
"void",
"acceptChildren",
"(",
"ExpressionVisitor",
"visitor",
")",
"{",
"getStateFieldPathExpression",
"(",
")",
".",
"accept",
"(",
"visitor",
")",
";",
"getNewValue",
"(",
")",
".",
"accept",
"(",
"visitor",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"protected",
"void",
"addChildrenTo",
"(",
"Collection",
"<",
"Expression",
">",
"children",
")",
"{",
"children",
".",
"add",
"(",
"getStateFieldPathExpression",
"(",
")",
")",
";",
"children",
".",
"add",
"(",
"getNewValue",
"(",
")",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"protected",
"void",
"addOrderedChildrenTo",
"(",
"List",
"<",
"Expression",
">",
"children",
")",
"{",
"if",
"(",
"stateFieldExpression",
"!=",
"null",
")",
"{",
"children",
".",
"add",
"(",
"stateFieldExpression",
")",
";",
"}",
"if",
"(",
"hasSpaceAfterStateFieldPathExpression",
")",
"{",
"children",
".",
"add",
"(",
"buildStringExpression",
"(",
"SPACE",
")",
")",
";",
"}",
"if",
"(",
"hasEqualSign",
")",
"{",
"children",
".",
"add",
"(",
"buildStringExpression",
"(",
"EQUAL",
")",
")",
";",
"}",
"if",
"(",
"hasSpaceAfterEqualSign",
")",
"{",
"children",
".",
"add",
"(",
"buildStringExpression",
"(",
"SPACE",
")",
")",
";",
"}",
"if",
"(",
"newValue",
"!=",
"null",
")",
"{",
"children",
".",
"add",
"(",
"newValue",
")",
";",
"}",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"public",
"JPQLQueryBNF",
"findQueryBNF",
"(",
"Expression",
"expression",
")",
"{",
"if",
"(",
"(",
"stateFieldExpression",
"!=",
"null",
")",
"&&",
"stateFieldExpression",
".",
"isAncestor",
"(",
"expression",
")",
")",
"{",
"return",
"getQueryBNF",
"(",
"UpdateItemStateFieldPathExpressionBNF",
".",
"ID",
")",
";",
"}",
"if",
"(",
"(",
"newValue",
"!=",
"null",
")",
"&&",
"newValue",
".",
"isAncestor",
"(",
"expression",
")",
")",
"{",
"return",
"getQueryBNF",
"(",
"NewValueBNF",
".",
"ID",
")",
";",
"}",
"return",
"super",
".",
"findQueryBNF",
"(",
"expression",
")",
";",
"}",
"/**\r\n\t * Returns the {@link Expression} representing the new value, which is the new value of the property.\r\n\t *\r\n\t * @return The expression for the new value\r\n\t */",
"public",
"Expression",
"getNewValue",
"(",
")",
"{",
"if",
"(",
"newValue",
"==",
"null",
")",
"{",
"newValue",
"=",
"buildNullExpression",
"(",
")",
";",
"}",
"return",
"newValue",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"public",
"JPQLQueryBNF",
"getQueryBNF",
"(",
")",
"{",
"return",
"getQueryBNF",
"(",
"UpdateItemBNF",
".",
"ID",
")",
";",
"}",
"/**\r\n\t * Returns the {@link Expression} representing the state field path expression, which is the\r\n\t * property that should get updated.\r\n\t *\r\n\t * @return The expression for the state field path expression\r\n\t */",
"public",
"Expression",
"getStateFieldPathExpression",
"(",
")",
"{",
"if",
"(",
"stateFieldExpression",
"==",
"null",
")",
"{",
"stateFieldExpression",
"=",
"buildNullExpression",
"(",
")",
";",
"}",
"return",
"stateFieldExpression",
";",
"}",
"/**\r\n\t * Determines whether the equal sign was parsed or not.\r\n\t *\r\n\t * @return <code>true</code> if the equal sign was parsed; <code>false</code> otherwise\r\n\t */",
"public",
"boolean",
"hasEqualSign",
"(",
")",
"{",
"return",
"hasEqualSign",
";",
"}",
"/**\r\n\t * Determines whether the new value section of the query was parsed.\r\n\t *\r\n\t * @return <code>true</code> the new value was parsed; <code>false</code> if nothing was parsed\r\n\t */",
"public",
"boolean",
"hasNewValue",
"(",
")",
"{",
"return",
"newValue",
"!=",
"null",
"&&",
"!",
"newValue",
".",
"isNull",
"(",
")",
";",
"}",
"/**\r\n\t * Determines whether a whitespace was parsed after the equal sign or not.\r\n\t *\r\n\t * @return <code>true</code> if there was a whitespace after the equal sign; <code>false</code> otherwise\r\n\t */",
"public",
"boolean",
"hasSpaceAfterEqualSign",
"(",
")",
"{",
"return",
"hasSpaceAfterEqualSign",
";",
"}",
"/**\r\n\t * Determines whether a whitespace was parsed after the state field path expression not.\r\n\t *\r\n\t * @return <code>true</code> if there was a whitespace after the state field path expression;\r\n\t * <code>false</code> otherwise\r\n\t */",
"public",
"boolean",
"hasSpaceAfterStateFieldPathExpression",
"(",
")",
"{",
"return",
"hasSpaceAfterStateFieldPathExpression",
";",
"}",
"/**\r\n\t * Determines whether the state field was parsed.\r\n\t *\r\n\t * @return <code>true</code> the state field was parsed; <code>false</code> otherwise\r\n\t */",
"public",
"boolean",
"hasStateFieldPathExpression",
"(",
")",
"{",
"return",
"stateFieldExpression",
"!=",
"null",
"&&",
"!",
"stateFieldExpression",
".",
"isNull",
"(",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"protected",
"boolean",
"isParsingComplete",
"(",
"WordParser",
"wordParser",
",",
"String",
"word",
",",
"Expression",
"expression",
")",
"{",
"return",
"word",
".",
"equals",
"(",
"EQUAL",
")",
"||",
"super",
".",
"isParsingComplete",
"(",
"wordParser",
",",
"word",
",",
"expression",
")",
";",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"protected",
"void",
"parse",
"(",
"WordParser",
"wordParser",
",",
"boolean",
"tolerant",
")",
"{",
"if",
"(",
"tolerant",
")",
"{",
"stateFieldExpression",
"=",
"parse",
"(",
"wordParser",
",",
"UpdateItemStateFieldPathExpressionBNF",
".",
"ID",
",",
"tolerant",
")",
";",
"}",
"else",
"{",
"stateFieldExpression",
"=",
"new",
"StateFieldPathExpression",
"(",
"this",
",",
"wordParser",
".",
"word",
"(",
")",
")",
";",
"stateFieldExpression",
".",
"parse",
"(",
"wordParser",
",",
"tolerant",
")",
";",
"}",
"hasSpaceAfterStateFieldPathExpression",
"=",
"wordParser",
".",
"skipLeadingWhitespace",
"(",
")",
">",
"0",
";",
"hasEqualSign",
"=",
"wordParser",
".",
"startsWith",
"(",
"EQUAL",
")",
";",
"if",
"(",
"hasEqualSign",
")",
"{",
"wordParser",
".",
"moveForward",
"(",
"1",
")",
";",
"hasSpaceAfterEqualSign",
"=",
"wordParser",
".",
"skipLeadingWhitespace",
"(",
")",
">",
"0",
";",
"if",
"(",
"stateFieldExpression",
"!=",
"null",
")",
"{",
"hasSpaceAfterStateFieldPathExpression",
"=",
"true",
";",
"}",
"}",
"newValue",
"=",
"parse",
"(",
"wordParser",
",",
"NewValueBNF",
".",
"ID",
",",
"tolerant",
")",
";",
"if",
"(",
"!",
"hasSpaceAfterEqualSign",
"&&",
"(",
"newValue",
"!=",
"null",
")",
")",
"{",
"hasSpaceAfterEqualSign",
"=",
"true",
";",
"}",
"}",
"/**\r\n\t * {@inheritDoc}\r\n\t */",
"@",
"Override",
"protected",
"void",
"toParsedText",
"(",
"StringBuilder",
"writer",
",",
"boolean",
"actual",
")",
"{",
"if",
"(",
"stateFieldExpression",
"!=",
"null",
")",
"{",
"stateFieldExpression",
".",
"toParsedText",
"(",
"writer",
",",
"actual",
")",
";",
"}",
"if",
"(",
"hasSpaceAfterStateFieldPathExpression",
")",
"{",
"writer",
".",
"append",
"(",
"SPACE",
")",
";",
"}",
"if",
"(",
"hasEqualSign",
")",
"{",
"writer",
".",
"append",
"(",
"EQUAL",
")",
";",
"}",
"if",
"(",
"hasSpaceAfterEqualSign",
")",
"{",
"writer",
".",
"append",
"(",
"SPACE",
")",
";",
"}",
"if",
"(",
"newValue",
"!=",
"null",
")",
"{",
"newValue",
".",
"toParsedText",
"(",
"writer",
",",
"actual",
")",
";",
"}",
"}",
"}"
] | The <code>new_value</code> specified for an update operation must be compatible in type with the
field to which it is assigned. | [
"The",
"<code",
">",
"new_value<",
"/",
"code",
">",
"specified",
"for",
"an",
"update",
"operation",
"must",
"be",
"compatible",
"in",
"type",
"with",
"the",
"field",
"to",
"which",
"it",
"is",
"assigned",
"."
] | [
"// State field expression\r",
"// '='\r",
"// New value\r",
"// Parse state field\r",
"// Parse '='\r",
"// Parse new value\r",
"// State field expression\r",
"// '='\r",
"// New value\r"
] | [
{
"param": "AbstractExpression",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractExpression",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd4301057b2b7191c859bf4b0886c6e5de85e9ba | tapis-project/tapis-java | tapis-jobslib/src/main/java/edu/utexas/tacc/tapis/jobs/queue/messages/recover/JobRecoverMsg.java | [
"BSD-3-Clause"
] | Java | JobRecoverMsg | /** The recovery message used to populate the job_recovery and job_blocked
* tables. This class calculates a hash of the tester type and parameters
* to identify jobs that are blocked on the same condition.
*
* @author rcardone
*/ | The recovery message used to populate the job_recovery and job_blocked
tables. This class calculates a hash of the tester type and parameters
to identify jobs that are blocked on the same condition.
@author rcardone | [
"The",
"recovery",
"message",
"used",
"to",
"populate",
"the",
"job_recovery",
"and",
"job_blocked",
"tables",
".",
"This",
"class",
"calculates",
"a",
"hash",
"of",
"the",
"tester",
"type",
"and",
"parameters",
"to",
"identify",
"jobs",
"that",
"are",
"blocked",
"on",
"the",
"same",
"condition",
".",
"@author",
"rcardone"
] | public class JobRecoverMsg
extends RecoverMsg
{
/* ********************************************************************** */
/* Constructor */
/* ********************************************************************** */
// For testing only.
public JobRecoverMsg() {super(RecoverMsgType.RECOVER, "UnknownSender");}
// Use static create method.
private JobRecoverMsg(String senderId) {super(RecoverMsgType.RECOVER, senderId);}
/* ********************************************************************** */
/* Fields */
/* ********************************************************************** */
// We use TreeMap as the concrete Map type for parameters so that the
// parameters maintain the same order during iteration. This provides an
// extra level of assurance when comparing parameters from different sources.
//
// The testerHash comprises the tenant, tester type and its parameters to uniquely
// identify a condition on which one or more jobs may be blocked. The strict
// ordering of test parameter keys makes the hashes that incorporate those
// parameters stable.
//
private String jobUuid; // Job in wait state
private String jobOwner; // Job's owner
private String tenantId; // Job's tenant ID
private RecoverConditionCode conditionCode; // Reason for waiting
private RecoverPolicyType policyType; // Next attempt policy
private TreeMap<String,String> policyParameters; // Policy parms
private JobStatusType successStatus; // New status for job after success
private String statusMessage; // The message inserted in the job record
// There's a single setter for these fields.
private RecoverTesterType testerType; // Condition tester name
private TreeMap<String,String> testerParameters; // Tester parms
private String testerHash; // Hash of tenant, testerType & testerParameters
/* ********************************************************************** */
/* Public Methods */
/* ********************************************************************** */
/* ---------------------------------------------------------------------- */
/* setTesterInfo: */
/* ---------------------------------------------------------------------- */
/** Control access to the tester fields since we need to create a hash
* from their values. Each of the input fields are incorporated into a
* hash value used to group jobs blocked on the same condition.
*
* Note that it is possible that two recovery messages with different condition
* codes code have the same tester type and parameters. In that case, the first
* message's recovery record would take priority and all jobs would be blocked
* under that record. In practice this problem should not arise because
* different conditions are expected to use different monitoring tests.
*
* @param tenant the job's tenant
* @param type the tester type processor
* @param parms parameters used by the test type processor
*/
public void setTesterInfo(String tenant, RecoverTesterType type, TreeMap<String,String> parms)
{
// Don't allow a null type.
if (type == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "setTesterInfo", "type");
throw new TapisRuntimeException(msg);
}
testerType = type;
// Null parms are replaced with the empty string.
if (parms == null) testerParameters = new TreeMap<>();
else testerParameters = parms;
// Calculate the hash for this combination of tester information.
String data = tenant + "|" + type.name() + "|" + TapisGsonUtils.getGson().toJson(testerParameters);
testerHash = DigestUtils.sha1Hex(data);
}
/* ---------------------------------------------------------------------- */
/* validate: */
/* ---------------------------------------------------------------------- */
/** Basic validation of all required fields.
*
* @throws JobException on an invalid field value
*/
public void validate()
throws JobInputException
{
// Many null checks.
if (jobUuid == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "jobUuid");
throw new JobInputException(msg);
}
if (jobOwner == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "jobOwner");
throw new JobInputException(msg);
}
if (tenantId == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "tenantId");
throw new JobInputException(msg);
}
if (conditionCode == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "conditionCode");
throw new JobInputException(msg);
}
if (testerType == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "testerType");
throw new JobInputException(msg);
}
if (testerParameters == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "testerParameters");
throw new JobInputException(msg);
}
if (testerHash == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "testerHash");
throw new JobInputException(msg);
}
if (policyType == null) {
String msg = MsgUtils.getMsg("TAPISE_NULL_PARAMETER", "validate", "policyType");
throw new JobInputException(msg);
}
if (policyParameters == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "policyParameters");
throw new JobInputException(msg);
}
if (successStatus == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "successStatus");
throw new JobInputException(msg);
}
if (statusMessage == null) {
String msg = MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "validate", "statusMessage");
throw new JobInputException(msg);
}
}
/* ---------------------------------------------------------------------- */
/* create: */
/* ---------------------------------------------------------------------- */
public static JobRecoverMsg create(Job job,
String senderId,
RecoverConditionCode conditionCode,
RecoverPolicyType policyType,
TreeMap<String,String> policyParameters,
JobStatusType successStatus,
String statusMessage,
RecoverTesterType testerType,
TreeMap<String,String> testerParms)
{
// Create the new job recover message.
JobRecoverMsg rmsg = new JobRecoverMsg(senderId);
// Check input.
if (job == null)
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "job"));
if (StringUtils.isBlank(senderId))
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "senderId"));
if (conditionCode == null)
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "conditionCode"));
if (policyType == null)
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "policyType"));
if (successStatus == null)
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "successStatus"));
if (StringUtils.isBlank(statusMessage))
throw new IllegalArgumentException(MsgUtils.getMsg("TAPISE_NULL_PARAMETER", "JobRecoverMsg", "statusMessage"));
if (testerType == null)
throw new IllegalArgumentException(MsgUtils.getMsg("TAPIS_NULL_PARAMETER", "JobRecoverMsg", "testerType"));
// Create empty policy parameters if necessary.
// Null testerParms are handled later.
if (policyParameters == null) policyParameters = new TreeMap<>();
// Fill in the other message fields.
rmsg.setJobUuid(job.getUuid());
rmsg.setJobOwner(job.getOwner());
rmsg.setTenantId(job.getTenant());
rmsg.setConditionCode(conditionCode);
rmsg.setPolicyType(policyType);
rmsg.setPolicyParameters(policyParameters);
rmsg.setSuccessStatus(successStatus);
rmsg.setStatusMessage(statusMessage);
rmsg.setTesterInfo(job.getTenant(), testerType, testerParms);
return rmsg;
}
/* ********************************************************************** */
/* Accessors */
/* ********************************************************************** */
public RecoverTesterType getTesterType() {return testerType;}
public TreeMap<String, String> getTesterParameters() {return testerParameters;}
public String getTesterHash() {return testerHash;}
public String getJobUuid() {
return jobUuid;
}
public void setJobUuid(String jobUuid) {
this.jobUuid = jobUuid;
}
public String getJobOwner() {
return jobOwner;
}
public void setJobOwner(String jobOwner) {
this.jobOwner = jobOwner;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public RecoverConditionCode getConditionCode() {
return conditionCode;
}
public void setConditionCode(RecoverConditionCode conditionCode) {
this.conditionCode = conditionCode;
}
public RecoverPolicyType getPolicyType() {
return policyType;
}
public void setPolicyType(RecoverPolicyType policyType) {
this.policyType = policyType;
}
public TreeMap<String, String> getPolicyParameters() {
return policyParameters;
}
public void setPolicyParameters(TreeMap<String, String> policyParameters) {
this.policyParameters = policyParameters;
}
public JobStatusType getSuccessStatus() {
return successStatus;
}
public void setSuccessStatus(JobStatusType successStatus) {
this.successStatus = successStatus;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
} | [
"public",
"class",
"JobRecoverMsg",
"extends",
"RecoverMsg",
"{",
"/* ********************************************************************** */",
"/* Constructor */",
"/* ********************************************************************** */",
"public",
"JobRecoverMsg",
"(",
")",
"{",
"super",
"(",
"RecoverMsgType",
".",
"RECOVER",
",",
"\"",
"UnknownSender",
"\"",
")",
";",
"}",
"private",
"JobRecoverMsg",
"(",
"String",
"senderId",
")",
"{",
"super",
"(",
"RecoverMsgType",
".",
"RECOVER",
",",
"senderId",
")",
";",
"}",
"/* ********************************************************************** */",
"/* Fields */",
"/* ********************************************************************** */",
"private",
"String",
"jobUuid",
";",
"private",
"String",
"jobOwner",
";",
"private",
"String",
"tenantId",
";",
"private",
"RecoverConditionCode",
"conditionCode",
";",
"private",
"RecoverPolicyType",
"policyType",
";",
"private",
"TreeMap",
"<",
"String",
",",
"String",
">",
"policyParameters",
";",
"private",
"JobStatusType",
"successStatus",
";",
"private",
"String",
"statusMessage",
";",
"private",
"RecoverTesterType",
"testerType",
";",
"private",
"TreeMap",
"<",
"String",
",",
"String",
">",
"testerParameters",
";",
"private",
"String",
"testerHash",
";",
"/* ********************************************************************** */",
"/* Public Methods */",
"/* ********************************************************************** */",
"/* ---------------------------------------------------------------------- */",
"/* setTesterInfo: */",
"/* ---------------------------------------------------------------------- */",
"/** Control access to the tester fields since we need to create a hash\n * from their values. Each of the input fields are incorporated into a \n * hash value used to group jobs blocked on the same condition.\n * \n * Note that it is possible that two recovery messages with different condition\n * codes code have the same tester type and parameters. In that case, the first\n * message's recovery record would take priority and all jobs would be blocked\n * under that record. In practice this problem should not arise because\n * different conditions are expected to use different monitoring tests. \n * \n * @param tenant the job's tenant\n * @param type the tester type processor\n * @param parms parameters used by the test type processor\n */",
"public",
"void",
"setTesterInfo",
"(",
"String",
"tenant",
",",
"RecoverTesterType",
"type",
",",
"TreeMap",
"<",
"String",
",",
"String",
">",
"parms",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"setTesterInfo",
"\"",
",",
"\"",
"type",
"\"",
")",
";",
"throw",
"new",
"TapisRuntimeException",
"(",
"msg",
")",
";",
"}",
"testerType",
"=",
"type",
";",
"if",
"(",
"parms",
"==",
"null",
")",
"testerParameters",
"=",
"new",
"TreeMap",
"<",
">",
"(",
")",
";",
"else",
"testerParameters",
"=",
"parms",
";",
"String",
"data",
"=",
"tenant",
"+",
"\"",
"|",
"\"",
"+",
"type",
".",
"name",
"(",
")",
"+",
"\"",
"|",
"\"",
"+",
"TapisGsonUtils",
".",
"getGson",
"(",
")",
".",
"toJson",
"(",
"testerParameters",
")",
";",
"testerHash",
"=",
"DigestUtils",
".",
"sha1Hex",
"(",
"data",
")",
";",
"}",
"/* ---------------------------------------------------------------------- */",
"/* validate: */",
"/* ---------------------------------------------------------------------- */",
"/** Basic validation of all required fields.\n * \n * @throws JobException on an invalid field value\n */",
"public",
"void",
"validate",
"(",
")",
"throws",
"JobInputException",
"{",
"if",
"(",
"jobUuid",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"jobUuid",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"jobOwner",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"jobOwner",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"tenantId",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"tenantId",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"conditionCode",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"conditionCode",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"testerType",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"testerType",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"testerParameters",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"testerParameters",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"testerHash",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"testerHash",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"policyType",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPISE_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"policyType",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"policyParameters",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"policyParameters",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"successStatus",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"successStatus",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"statusMessage",
"==",
"null",
")",
"{",
"String",
"msg",
"=",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"validate",
"\"",
",",
"\"",
"statusMessage",
"\"",
")",
";",
"throw",
"new",
"JobInputException",
"(",
"msg",
")",
";",
"}",
"}",
"/* ---------------------------------------------------------------------- */",
"/* create: */",
"/* ---------------------------------------------------------------------- */",
"public",
"static",
"JobRecoverMsg",
"create",
"(",
"Job",
"job",
",",
"String",
"senderId",
",",
"RecoverConditionCode",
"conditionCode",
",",
"RecoverPolicyType",
"policyType",
",",
"TreeMap",
"<",
"String",
",",
"String",
">",
"policyParameters",
",",
"JobStatusType",
"successStatus",
",",
"String",
"statusMessage",
",",
"RecoverTesterType",
"testerType",
",",
"TreeMap",
"<",
"String",
",",
"String",
">",
"testerParms",
")",
"{",
"JobRecoverMsg",
"rmsg",
"=",
"new",
"JobRecoverMsg",
"(",
"senderId",
")",
";",
"if",
"(",
"job",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"job",
"\"",
")",
")",
";",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"senderId",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"senderId",
"\"",
")",
")",
";",
"if",
"(",
"conditionCode",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"conditionCode",
"\"",
")",
")",
";",
"if",
"(",
"policyType",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"policyType",
"\"",
")",
")",
";",
"if",
"(",
"successStatus",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"successStatus",
"\"",
")",
")",
";",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"statusMessage",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPISE_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"statusMessage",
"\"",
")",
")",
";",
"if",
"(",
"testerType",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"MsgUtils",
".",
"getMsg",
"(",
"\"",
"TAPIS_NULL_PARAMETER",
"\"",
",",
"\"",
"JobRecoverMsg",
"\"",
",",
"\"",
"testerType",
"\"",
")",
")",
";",
"if",
"(",
"policyParameters",
"==",
"null",
")",
"policyParameters",
"=",
"new",
"TreeMap",
"<",
">",
"(",
")",
";",
"rmsg",
".",
"setJobUuid",
"(",
"job",
".",
"getUuid",
"(",
")",
")",
";",
"rmsg",
".",
"setJobOwner",
"(",
"job",
".",
"getOwner",
"(",
")",
")",
";",
"rmsg",
".",
"setTenantId",
"(",
"job",
".",
"getTenant",
"(",
")",
")",
";",
"rmsg",
".",
"setConditionCode",
"(",
"conditionCode",
")",
";",
"rmsg",
".",
"setPolicyType",
"(",
"policyType",
")",
";",
"rmsg",
".",
"setPolicyParameters",
"(",
"policyParameters",
")",
";",
"rmsg",
".",
"setSuccessStatus",
"(",
"successStatus",
")",
";",
"rmsg",
".",
"setStatusMessage",
"(",
"statusMessage",
")",
";",
"rmsg",
".",
"setTesterInfo",
"(",
"job",
".",
"getTenant",
"(",
")",
",",
"testerType",
",",
"testerParms",
")",
";",
"return",
"rmsg",
";",
"}",
"/* ********************************************************************** */",
"/* Accessors */",
"/* ********************************************************************** */",
"public",
"RecoverTesterType",
"getTesterType",
"(",
")",
"{",
"return",
"testerType",
";",
"}",
"public",
"TreeMap",
"<",
"String",
",",
"String",
">",
"getTesterParameters",
"(",
")",
"{",
"return",
"testerParameters",
";",
"}",
"public",
"String",
"getTesterHash",
"(",
")",
"{",
"return",
"testerHash",
";",
"}",
"public",
"String",
"getJobUuid",
"(",
")",
"{",
"return",
"jobUuid",
";",
"}",
"public",
"void",
"setJobUuid",
"(",
"String",
"jobUuid",
")",
"{",
"this",
".",
"jobUuid",
"=",
"jobUuid",
";",
"}",
"public",
"String",
"getJobOwner",
"(",
")",
"{",
"return",
"jobOwner",
";",
"}",
"public",
"void",
"setJobOwner",
"(",
"String",
"jobOwner",
")",
"{",
"this",
".",
"jobOwner",
"=",
"jobOwner",
";",
"}",
"public",
"String",
"getTenantId",
"(",
")",
"{",
"return",
"tenantId",
";",
"}",
"public",
"void",
"setTenantId",
"(",
"String",
"tenantId",
")",
"{",
"this",
".",
"tenantId",
"=",
"tenantId",
";",
"}",
"public",
"RecoverConditionCode",
"getConditionCode",
"(",
")",
"{",
"return",
"conditionCode",
";",
"}",
"public",
"void",
"setConditionCode",
"(",
"RecoverConditionCode",
"conditionCode",
")",
"{",
"this",
".",
"conditionCode",
"=",
"conditionCode",
";",
"}",
"public",
"RecoverPolicyType",
"getPolicyType",
"(",
")",
"{",
"return",
"policyType",
";",
"}",
"public",
"void",
"setPolicyType",
"(",
"RecoverPolicyType",
"policyType",
")",
"{",
"this",
".",
"policyType",
"=",
"policyType",
";",
"}",
"public",
"TreeMap",
"<",
"String",
",",
"String",
">",
"getPolicyParameters",
"(",
")",
"{",
"return",
"policyParameters",
";",
"}",
"public",
"void",
"setPolicyParameters",
"(",
"TreeMap",
"<",
"String",
",",
"String",
">",
"policyParameters",
")",
"{",
"this",
".",
"policyParameters",
"=",
"policyParameters",
";",
"}",
"public",
"JobStatusType",
"getSuccessStatus",
"(",
")",
"{",
"return",
"successStatus",
";",
"}",
"public",
"void",
"setSuccessStatus",
"(",
"JobStatusType",
"successStatus",
")",
"{",
"this",
".",
"successStatus",
"=",
"successStatus",
";",
"}",
"public",
"String",
"getStatusMessage",
"(",
")",
"{",
"return",
"statusMessage",
";",
"}",
"public",
"void",
"setStatusMessage",
"(",
"String",
"statusMessage",
")",
"{",
"this",
".",
"statusMessage",
"=",
"statusMessage",
";",
"}",
"}"
] | The recovery message used to populate the job_recovery and job_blocked
tables. | [
"The",
"recovery",
"message",
"used",
"to",
"populate",
"the",
"job_recovery",
"and",
"job_blocked",
"tables",
"."
] | [
"// For testing only.",
"// Use static create method.",
"// We use TreeMap as the concrete Map type for parameters so that the ",
"// parameters maintain the same order during iteration. This provides an",
"// extra level of assurance when comparing parameters from different sources.",
"//",
"// The testerHash comprises the tenant, tester type and its parameters to uniquely",
"// identify a condition on which one or more jobs may be blocked. The strict",
"// ordering of test parameter keys makes the hashes that incorporate those",
"// parameters stable.",
"//",
"// Job in wait state",
"// Job's owner",
"// Job's tenant ID",
"// Reason for waiting",
"// Next attempt policy ",
"// Policy parms",
"// New status for job after success",
"// The message inserted in the job record",
"// There's a single setter for these fields.",
"// Condition tester name",
"// Tester parms",
"// Hash of tenant, testerType & testerParameters",
"// Don't allow a null type.",
"// Null parms are replaced with the empty string.",
"// Calculate the hash for this combination of tester information.",
"// Many null checks.",
"// Create the new job recover message.",
"// Check input.",
"// Create empty policy parameters if necessary.",
"// Null testerParms are handled later.",
"// Fill in the other message fields."
] | [
{
"param": "RecoverMsg",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "RecoverMsg",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd4bfe0d1ae80eb1fe92fb1735ac13002d05406f | wangyunxizhe/strata-root-study | modules/product/src/main/java/com/opengamma/strata/product/AttributeType.java | [
"Apache-2.0"
] | Java | AttributeType | /**
* The type that provides meaning to an attribute.
* <p>
* Attributes provide the ability to associate arbitrary information with the trade model in a key-value map.
* For example, it might be used to provide information about the trading platform.
* <p>
* Applications that wish to use attributes should declare a static constant declaring the
* {@code AttributeType} instance, the type parameter and a lowerCamelCase name. For example:
* <pre>
* public static final AttributeType<String> DEALER = AttributeType.of("dealer");
* </pre>
*
* @param <T> the type of the attribute value
*/ | The type that provides meaning to an attribute.
Attributes provide the ability to associate arbitrary information with the trade model in a key-value map.
For example, it might be used to provide information about the trading platform.
Applications that wish to use attributes should declare a static constant declaring the
AttributeType instance, the type parameter and a lowerCamelCase name. For example:
public static final AttributeType<String> DEALER = AttributeType.of("dealer");
@param the type of the attribute value | [
"The",
"type",
"that",
"provides",
"meaning",
"to",
"an",
"attribute",
".",
"Attributes",
"provide",
"the",
"ability",
"to",
"associate",
"arbitrary",
"information",
"with",
"the",
"trade",
"model",
"in",
"a",
"key",
"-",
"value",
"map",
".",
"For",
"example",
"it",
"might",
"be",
"used",
"to",
"provide",
"information",
"about",
"the",
"trading",
"platform",
".",
"Applications",
"that",
"wish",
"to",
"use",
"attributes",
"should",
"declare",
"a",
"static",
"constant",
"declaring",
"the",
"AttributeType",
"instance",
"the",
"type",
"parameter",
"and",
"a",
"lowerCamelCase",
"name",
".",
"For",
"example",
":",
"public",
"static",
"final",
"AttributeType<String",
">",
"DEALER",
"=",
"AttributeType",
".",
"of",
"(",
"\"",
"dealer",
"\"",
")",
";",
"@param",
"the",
"type",
"of",
"the",
"attribute",
"value"
] | public final class AttributeType<T>
extends TypedString<AttributeType<T>> {
/**
* Key used to access the description.
*/
public static final AttributeType<String> DESCRIPTION = AttributeType.of("description");
/**
* Key used to access the name.
*/
public static final AttributeType<String> NAME = AttributeType.of("name");
/** Serialization version. */
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Obtains an instance from the specified name.
* <p>
* The name may contain any character, but must not be empty.
*
* @param <T> the type associated with the info
* @param name the name
* @return a type instance with the specified name
*/
@FromString
public static <T> AttributeType<T> of(String name) {
return new AttributeType<T>(name);
}
/**
* Creates an instance.
*
* @param name the name
*/
private AttributeType(String name) {
super(name);
}
} | [
"public",
"final",
"class",
"AttributeType",
"<",
"T",
">",
"extends",
"TypedString",
"<",
"AttributeType",
"<",
"T",
">",
">",
"{",
"/**\n * Key used to access the description.\n */",
"public",
"static",
"final",
"AttributeType",
"<",
"String",
">",
"DESCRIPTION",
"=",
"AttributeType",
".",
"of",
"(",
"\"",
"description",
"\"",
")",
";",
"/**\n * Key used to access the name.\n */",
"public",
"static",
"final",
"AttributeType",
"<",
"String",
">",
"NAME",
"=",
"AttributeType",
".",
"of",
"(",
"\"",
"name",
"\"",
")",
";",
"/** Serialization version. */",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"/**\n * Obtains an instance from the specified name.\n * <p>\n * The name may contain any character, but must not be empty.\n *\n * @param <T> the type associated with the info\n * @param name the name\n * @return a type instance with the specified name\n */",
"@",
"FromString",
"public",
"static",
"<",
"T",
">",
"AttributeType",
"<",
"T",
">",
"of",
"(",
"String",
"name",
")",
"{",
"return",
"new",
"AttributeType",
"<",
"T",
">",
"(",
"name",
")",
";",
"}",
"/**\n * Creates an instance.\n * \n * @param name the name\n */",
"private",
"AttributeType",
"(",
"String",
"name",
")",
"{",
"super",
"(",
"name",
")",
";",
"}",
"}"
] | The type that provides meaning to an attribute. | [
"The",
"type",
"that",
"provides",
"meaning",
"to",
"an",
"attribute",
"."
] | [
"//-------------------------------------------------------------------------"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd501d0b63a11d55b30f734027ecd13f68df86b3 | code-lab-org/sipg | src/main/java/edu/mit/sipg/core/social/population/TableLookupModel.java | [
"Apache-2.0"
] | Java | TableLookupModel | /**
* A population model implementation that looks up values from a table.
*
* @author Roi Guinto
* @author Paul T. Grogan
*/ | A population model implementation that looks up values from a table.
@author Roi Guinto
@author Paul T. Grogan | [
"A",
"population",
"model",
"implementation",
"that",
"looks",
"up",
"values",
"from",
"a",
"table",
".",
"@author",
"Roi",
"Guinto",
"@author",
"Paul",
"T",
".",
"Grogan"
] | public class TableLookupModel implements PopulationModel {
private long time, nextTime;
private final Map<Long, Long> populationMap;
/**
* Instantiates a new table lookup model.
*/
protected TableLookupModel() {
this(new TreeMap<Long, Long>());
}
/**
* Instantiates a new table lookup model.
*
* @param initialTime the initial time
* @param timeStep the time step
* @param populationValues the population values
*/
public TableLookupModel(int initialTime, int timeStep, long[] populationValues) {
this.populationMap = new HashMap<Long, Long>();
for(int i = initialTime; i < populationValues.length; i += timeStep) {
populationMap.put(new Long(i), populationValues[i]);
}
}
/**
* Instantiates a new table lookup model.
*
* @param populationMap the population map
*/
public TableLookupModel(Map<Long, Long> populationMap) {
this.populationMap = Collections.unmodifiableMap(
new TreeMap<Long, Long>(populationMap));
}
@Override
public long getPopulation() {
Long populationValue = populationMap.get(time);
if(populationValue == null) {
return 0;
} else {
return populationValue.longValue();
}
}
@Override
public void initialize(long time) {
this.time = time;
}
@Override
public void tick() {
nextTime = time + 1;
}
@Override
public void tock() {
time = nextTime;
}
} | [
"public",
"class",
"TableLookupModel",
"implements",
"PopulationModel",
"{",
"private",
"long",
"time",
",",
"nextTime",
";",
"private",
"final",
"Map",
"<",
"Long",
",",
"Long",
">",
"populationMap",
";",
"/**\r\n\t * Instantiates a new table lookup model.\r\n\t */",
"protected",
"TableLookupModel",
"(",
")",
"{",
"this",
"(",
"new",
"TreeMap",
"<",
"Long",
",",
"Long",
">",
"(",
")",
")",
";",
"}",
"/**\r\n\t * Instantiates a new table lookup model.\r\n\t *\r\n\t * @param initialTime the initial time\r\n\t * @param timeStep the time step\r\n\t * @param populationValues the population values\r\n\t */",
"public",
"TableLookupModel",
"(",
"int",
"initialTime",
",",
"int",
"timeStep",
",",
"long",
"[",
"]",
"populationValues",
")",
"{",
"this",
".",
"populationMap",
"=",
"new",
"HashMap",
"<",
"Long",
",",
"Long",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"initialTime",
";",
"i",
"<",
"populationValues",
".",
"length",
";",
"i",
"+=",
"timeStep",
")",
"{",
"populationMap",
".",
"put",
"(",
"new",
"Long",
"(",
"i",
")",
",",
"populationValues",
"[",
"i",
"]",
")",
";",
"}",
"}",
"/**\r\n\t * Instantiates a new table lookup model.\r\n\t *\r\n\t * @param populationMap the population map\r\n\t */",
"public",
"TableLookupModel",
"(",
"Map",
"<",
"Long",
",",
"Long",
">",
"populationMap",
")",
"{",
"this",
".",
"populationMap",
"=",
"Collections",
".",
"unmodifiableMap",
"(",
"new",
"TreeMap",
"<",
"Long",
",",
"Long",
">",
"(",
"populationMap",
")",
")",
";",
"}",
"@",
"Override",
"public",
"long",
"getPopulation",
"(",
")",
"{",
"Long",
"populationValue",
"=",
"populationMap",
".",
"get",
"(",
"time",
")",
";",
"if",
"(",
"populationValue",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"else",
"{",
"return",
"populationValue",
".",
"longValue",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"initialize",
"(",
"long",
"time",
")",
"{",
"this",
".",
"time",
"=",
"time",
";",
"}",
"@",
"Override",
"public",
"void",
"tick",
"(",
")",
"{",
"nextTime",
"=",
"time",
"+",
"1",
";",
"}",
"@",
"Override",
"public",
"void",
"tock",
"(",
")",
"{",
"time",
"=",
"nextTime",
";",
"}",
"}"
] | A population model implementation that looks up values from a table. | [
"A",
"population",
"model",
"implementation",
"that",
"looks",
"up",
"values",
"from",
"a",
"table",
"."
] | [] | [
{
"param": "PopulationModel",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "PopulationModel",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd51a53fd206551a55f5dbcaae11871ac2a52121 | QualiMaster/QM-IConf | QualiMasterApplication/src/de/uni_hildesheim/sse/qmApp/treeView/ConfigurableElement.java | [
"Apache-2.0"
] | Java | ConfigurableElement | /**
* Class manages a list of configurable elements which we populate in order to show these elements
* in the {@link ConfigurableElementsView} of the QualiMaster-App.
* Using a given configuration we populate this list with machines, specialized Hardware, pipelines.
* Moreover this class provides methods to manipulate this list.
* Thus it is possible to remove certain elements from the list.
*
* @author Niko Nowatzki
* @author Holger Eichelberger
*/ | Class manages a list of configurable elements which we populate in order to show these elements
in the ConfigurableElementsView of the QualiMaster-App.
Using a given configuration we populate this list with machines, specialized Hardware, pipelines.
Moreover this class provides methods to manipulate this list.
Thus it is possible to remove certain elements from the list.
@author Niko Nowatzki
@author Holger Eichelberger | [
"Class",
"manages",
"a",
"list",
"of",
"configurable",
"elements",
"which",
"we",
"populate",
"in",
"order",
"to",
"show",
"these",
"elements",
"in",
"the",
"ConfigurableElementsView",
"of",
"the",
"QualiMaster",
"-",
"App",
".",
"Using",
"a",
"given",
"configuration",
"we",
"populate",
"this",
"list",
"with",
"machines",
"specialized",
"Hardware",
"pipelines",
".",
"Moreover",
"this",
"class",
"provides",
"methods",
"to",
"manipulate",
"this",
"list",
".",
"Thus",
"it",
"is",
"possible",
"to",
"remove",
"certain",
"elements",
"from",
"the",
"list",
".",
"@author",
"Niko",
"Nowatzki",
"@author",
"Holger",
"Eichelberger"
] | public class ConfigurableElement { // unsure whether this shall be a resource
private ElementStatusIndicator status;
private String displayName;
private String editorId;
private IEditorInputCreator input;
private ConfigurableElement parent;
private List<ConfigurableElement> children;
private IModelPart modelPart;
private Image image;
private IMenuContributor menuContributor;
private boolean isFlawed;
/**
* Constructor for a ConfigurableElement with a parent as param.
* @param parent The elements parent.
* @param displayName Name of the element.
* @param editorId The editorID.
* @param input The editor input creator.
* @param modelPart the underlying model part
*/
public ConfigurableElement(ConfigurableElement parent, String displayName,
String editorId, IEditorInputCreator input, IModelPart modelPart) {
this.parent = parent;
this.displayName = displayName;
this.modelPart = modelPart;
this.editorId = editorId;
this.input = input;
this.status = ElementStatusIndicator.NONE;
}
/**
* Constructor for a ConfigurableElement with a parent as param.
* @param parent The elements parent.
* @param displayName Name of the element (may be <b>null</b> in order to ask the <code>input</code> for its name).
* @param editorId The editorID.
* @param input The editor input creator.
*/
public ConfigurableElement(ConfigurableElement parent, String displayName,
String editorId, IEditorInputCreator input) {
this(parent, displayName, editorId, input, parent.getModelPart());
}
/**
* Constructor for a top-level ConfigurableElement.
*
* @param displayName Name of the element.
* @param editorId The editorID.
* @param input The editor input creator.
* @param modelPart the underlying model part
*/
public ConfigurableElement(String displayName, String editorId, IEditorInputCreator input, IModelPart modelPart) {
this(null, displayName, editorId, input, modelPart);
}
/**
* Set the indicator for falwed configurableElements.
* @param newValue new value tre if element is falwed, false if not.
*/
public void setFlawedIndicator(boolean newValue) {
isFlawed = newValue;
}
/**
* Get the information about this element. True if falwed, false if not.
* @return isFlawed true -> Element is falwed, false -> Element is not falwed.
*/
public boolean getFlawedIndicator() {
return isFlawed;
}
/**
* Returns the model part displayed (full or partially) by this configurable element.
*
* @return the model part
*/
public IModelPart getModelPart() {
return modelPart;
}
/**
* Tries to cast the given Object in {@link ConfigurableElement}.
* If this is successful, the method returns the {@link ConfigurableElement}.
* Otherwise the method returns NULL!
* @param object Given object which will be cast to {@link ConfigurableElement}.
* @return result The resulted {@link ConfigurableElement}. Null if object was not instance of
* {@link ConfigurableElement}.
*/
public static ConfigurableElement asConfigurableElement(Object object) {
ConfigurableElement result;
if (object instanceof ConfigurableElement) {
result = (ConfigurableElement) object;
} else {
result = null;
}
return result;
}
/**
* Add a child to this configurable element. The parent of
* <code>child</code> shall be <b>this</b>.
*
* @param child the child to be added
*/
public void addChildAtTop(ConfigurableElement child) {
assert this == child.getParent();
if (null == children) {
children = new ArrayList<ConfigurableElement>();
}
children.add(0, child);
}
/**
* Add a child to this configurable element. The parent of
* <code>child</code> shall be <b>this</b>.
*
* @param child the child to be added
*/
public void addChild(ConfigurableElement child) {
assert this == child.getParent();
if (null == children) {
children = new ArrayList<ConfigurableElement>();
}
children.add(child);
}
/**
* Creates and adds a new child for <code>variable</code> (via {@link IModelPart#getElementFactory()}).
* This method may issue change notification messages.
*
* @param source the event source
* @param variable the variable to create the element for
* @return the created element (may be <b>null</b>)
*/
public ConfigurableElement addChild(Object source, IDecisionVariable variable) {
IVariableEditorInputCreator creator = null;
IDatatype varType = variable.getDeclaration().getType();
// if (null != variable.getParent() && variable.getParent() instanceof SequenceVariable) {
// if ("configuredParameters".equals(variable.getParent().getDeclaration().getName())) {
// addDefaultValues(variable);
// }
// }
if (Compound.TYPE.isAssignableFrom(varType)) {
if (variable.getParent() instanceof ContainerVariable) {
ContainerVariable cVar = (ContainerVariable) variable.getParent();
creator = new ContainerVariableEditorInputCreator(modelPart, cVar.getDeclaration().getName(),
cVar.indexOf(variable));
} else {
creator = new CompoundVariableEditorInputCreator(modelPart,
variable.getDeclaration().getName());
}
} else if (variable.getParent() instanceof ContainerVariable) {
ContainerVariable cont = (ContainerVariable) variable.getParent();
int index = cont.indexOf(variable);
if (index >= 0) {
creator = new ContainerVariableEditorInputCreator(modelPart,
variable.getParent().getDeclaration().getName(), index);
}
}
ConfigurableElement child = null;
if (null != creator) {
child = modelPart.getElementFactory().createElement(this, variable, creator);
if (null != variable.getParent() && variable.getParent() instanceof SequenceVariable) {
if ("configuredParameters".equals(variable.getParent().getDeclaration().getName())) {
addDefaultValues(variable);
IEditorInput input = child.getEditorInputCreator().create();
if (input instanceof DecisionVariableEditorInput) {
DecisionVariableEditorInput decInput = (DecisionVariableEditorInput) input;
addDefaultValues(decInput.getVariable());
}
}
}
addChild(child);
creator.createArtifacts();
ChangeManager.INSTANCE.variableAdded(source, variable);
}
return child;
}
/**
* Adds a default name to the Observable, if not was given yet. This is neccessary for the model to load correctly
* and will lead to crashes and freezes if ignored.
* @param var The variable that needs a default name.
*/
private void addDefaultValues(IDecisionVariable var) {
IDecisionVariable type = var.getNestedElement(SLOT_OBSERVABLE_TYPE);
if (null != type && null == type.getValue()) {
String defaultName = null;
SequenceVariable parent = null;
if (null != var.getParent() && var.getParent() instanceof SequenceVariable) {
parent = (SequenceVariable) var.getParent();
}
if (null != parent) {
defaultName = parent.getDeclaration().getName() + " ["
+ (parent.getNestedElementsCount() - 1) + "]";
}
Value newValue;
try {
newValue = ValueFactory.createValue(
type.getDeclaration().getType(), new Object[]{defaultName});
type.setValue(newValue, AssignmentState.ASSIGNED);
} catch (ValueDoesNotMatchTypeException e) {
e.printStackTrace();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}
/**
* Get the displayName.
* @return displayName The displayName.
*/
public String getDisplayName() {
String result;
if (null == displayName && null != input) {
result = input.getName();
} else {
result = displayName;
}
if (null == result) {
result = "";
}
return result;
}
/**
* Changes the display name.
*
* @param displayName the new display name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* Returns the number of children of this configurable element.
*
* @return the number of children (non-negative)
*/
public int getChildCount() {
return null == children ? 0 : children.size();
}
/**
* Returns the specified child.
*
* @param index the 0-based index of the child
* @return the specified child
* @throws IndexOutOfBoundsException if <code>index < 0 || index >={@link #getChildCount()}</code>
*/
public ConfigurableElement getChild(int index) {
if (null == children) {
throw new IndexOutOfBoundsException();
}
return children.get(index);
}
/**
* Returns the children as an array.
*
* @return the children as an array (new instance)
*/
public ConfigurableElement[] getChildren() {
ConfigurableElement[] result;
if (hasChildren()) {
result = new ConfigurableElement[children.size()];
children.toArray(result);
} else {
result = null;
}
return result;
}
/**
* Check whether there are children.
* @return true if there are children.
* false if there are no children.
*/
public boolean hasChildren() {
return null != children && children.size() > 0;
}
/**
* Returns whether the selected element is a top-level element, thus, represents a model part.
*
* @return <code>true</code> if the selected element is a top-level element, <code>false</code> in case of
* an inner node
*/
public boolean isTopLevel() {
return null == parent; // || parent.input instanceof VarModelEditorInputCreator;
}
/**
* Get the parent.
* @return parent The parent.
*/
public ConfigurableElement getParent() {
return parent;
}
/**
* Return the editor input creator.
*
* @return input The editor input creator.
*/
public IEditorInputCreator getEditorInputCreator() {
return input;
}
/**
* Returns the editor id.
* @return the editor id.
*/
public String getEditorId() {
return editorId;
}
/**
* Returns the display name of the configurable element.
*
* @return the display name of the configurable element.
*/
public String toString() {
return getDisplayName();
}
/**
* Deletes <code>child</code> from the children of this element.
*
* @param child the child to be deleted
* @return <code>true</code> if removed, <code>false</code> else
*/
public boolean deleteFromChildren(ConfigurableElement child) {
boolean done = false;
if (null != children) {
if (!child.isTopLevel()) {
int index = children.indexOf(child);
if (index >= 0) {
ConfigurableElement parent = child.getParent();
String name = parent.getDisplayName();
if (child.input instanceof ContainerVariableEditorInputCreator) {
name = ((ContainerVariableEditorInputCreator) child.input).getVariableName();
}
// String name = child.input.getName();
ContainerVariableEditorInputChangeListener.INSTANCE.notifyDeletetion(name, index);
}
} else {
int index = children.indexOf(child);
if (index >= 0) {
String name = child.getDisplayName();
// String name = child.input.getName();
ContainerVariableEditorInputChangeListener.INSTANCE.notifyDeletetion(name, index);
}
}
done = children.remove(child);
}
return done;
}
/**
* Deletes this element if possible. This method may issue change events.
*
* @param source the source for this call to send change events.
*/
public void delete(Object source) {
input.delete(source, modelPart);
if (null != parent) {
parent.deleteFromChildren(this);
}
}
/**
* Returns the index of the given <code>element</code> in the set of children.
*
* @param element the element to search for
* @return the child index position, <code>-1</code> if not found
*/
public int indexOf(ConfigurableElement element) {
return children.indexOf(element);
}
/**
* Clones this configurable element. This method causes sending
* changed events via {@link ChangeManager}.
*
* @param source the event source (for sending events)
* @param count the number of clones to be created
* @return the created clones (<b>null</b> if none were created)
*/
public List<ConfigurableElement> clone(Object source, int count) {
List<ConfigurableElement> result = null;
if (!isTopLevel() && isCloneable().countAllowed(count)) {
ConfigurableElement parent = getParent();
if (parent.isVirtualSubGroup()) {
parent = parent.getParent();
}
List<IDecisionVariable> clones = input.clone(count);
if (null != clones && !clones.isEmpty()) {
result = new ArrayList<ConfigurableElement>();
for (int i = 0; i < clones.size(); i++) {
ConfigurableElement child = parent.addChild(source, clones.get(i));
if (null != child) {
result.add(child);
}
}
}
}
return result;
}
/**
* Returns whether this element is a virtual sub-group.
*
* @return <code>true</code> for a sub-group, <code>false</code> else
*/
public boolean isVirtualSubGroup() {
return null == getEditorInputCreator() && null != getParent();
}
/**
* Returns whether this element is cloneable.
*
* @return the clone mode
*/
public CloneMode isCloneable() {
return (null != input) ? input.isCloneable() : CloneMode.NONE;
}
/**
* Returns whether this element is (basically) deletable. This method does not
* determine any use of references to the underlying element.
*
* @return <code>true</code> if this element is deletable, <code>false</code> else
*/
public boolean isDeletable() {
// top-level elements are not deletable
return null != getParent() && null != input && input.isDeletable() && !isVirtualSubGroup();
}
/**
* Returns whether this element is (basically) writable.
*
* @return <code>true</code> if this element is writable, <code>false</code> else
*/
public boolean isWritable() {
return (null == getParent() && VariabilityModel.isWritable(modelPart))
|| (null != input && input.isWritable());
}
/**
* Returns whether this element is (basically) readable.
*
* @return <code>true</code> if this element is readable, <code>false</code> else
*/
public boolean isReadable() {
return (null == getParent() && VariabilityModel.isReadable(modelPart)) || isVirtualSubGroup()
|| input.isReadable();
}
/**
* Returns the configurable element holding the given <code>variable</code>.
*
* @param variable the variable to search for
* @return the configurable element holding <code>variable</code> or <b>null</b> if none was found
*/
public ConfigurableElement findElement(IDecisionVariable variable) {
ConfigurableElement result = null;
if (null != input && input.holds(variable)) {
result = this;
}
if (null != children) {
for (int e = 0; null == result && e < children.size(); e++) {
result = children.get(e).findElement(variable);
}
}
return result;
}
/**
* Whether the given configurable element holds the same variable.
*
* @param element the element to check for (may be <b>null</b>)
* @return <code>true</code> if same, <code>false</code> else
*/
public boolean holdsSame(ConfigurableElement element) {
boolean result = false;
if (null != input) {
IDecisionVariable iVar = input.getVariable();
if (null != iVar && null != element && null != element.input) {
IDecisionVariable eVar = element.input.getVariable();
result = eVar.equals(iVar);
}
}
return result;
}
/**
* Returns whether the underlying element is referenced in the given <code>modelPart</code>.
*
* @param modelPart the part to search in
* @return <code>true</code> if the underlying element is referenced in <code>modelPart</code>, <code>false</code>
* else
*/
public boolean isReferencedIn(IModelPart modelPart) {
if (null == modelPart) {
modelPart = this.modelPart;
}
return input.isReferencedIn(modelPart, this.modelPart);
}
/**
* Returns the image of this configurable element.
*
* @return the image (may be <b>null</b>, indicates that the default [platform] image shall be used)
*/
public Image getImage() {
return image;
}
/**
* Defines the image of this configurable element.
*
* @param image the image
* @return <b>this</b> (builder pattern)
*/
public ConfigurableElement setImage(Image image) {
this.image = image;
return this;
}
/**
* Defines the menu contributor.
*
* @param menuContributor the contributor, may be <b>null</b> if disabled
*/
public void setMenuContributor(IMenuContributor menuContributor) {
this.menuContributor = menuContributor;
}
/**
* Asks for contributions to the related popup menu.
*
* @param manager the menu manager
*/
public void contributeToPopup(IMenuManager manager) {
if (null != input) {
IMenuContributor contributor = input.getMenuContributor();
if (null != contributor) {
contributor.contributeTo(manager);
}
}
if (null != menuContributor) {
menuContributor.contributeTo(manager);
}
}
/**
* Get the current dataflow information for this configurable element.
* @return dataflow The current dataflow information for this element.
*/
public ElementStatusIndicator getStatus() {
return status;
}
/**
* Set the dataflow information for this configurable element.
* @param indicator New assigned dataflow information for this element.
*/
public void setStatus(ElementStatusIndicator indicator) {
this.status = indicator;
}
} | [
"public",
"class",
"ConfigurableElement",
"{",
"private",
"ElementStatusIndicator",
"status",
";",
"private",
"String",
"displayName",
";",
"private",
"String",
"editorId",
";",
"private",
"IEditorInputCreator",
"input",
";",
"private",
"ConfigurableElement",
"parent",
";",
"private",
"List",
"<",
"ConfigurableElement",
">",
"children",
";",
"private",
"IModelPart",
"modelPart",
";",
"private",
"Image",
"image",
";",
"private",
"IMenuContributor",
"menuContributor",
";",
"private",
"boolean",
"isFlawed",
";",
"/**\n * Constructor for a ConfigurableElement with a parent as param.\n * @param parent The elements parent.\n * @param displayName Name of the element.\n * @param editorId The editorID.\n * @param input The editor input creator.\n * @param modelPart the underlying model part\n */",
"public",
"ConfigurableElement",
"(",
"ConfigurableElement",
"parent",
",",
"String",
"displayName",
",",
"String",
"editorId",
",",
"IEditorInputCreator",
"input",
",",
"IModelPart",
"modelPart",
")",
"{",
"this",
".",
"parent",
"=",
"parent",
";",
"this",
".",
"displayName",
"=",
"displayName",
";",
"this",
".",
"modelPart",
"=",
"modelPart",
";",
"this",
".",
"editorId",
"=",
"editorId",
";",
"this",
".",
"input",
"=",
"input",
";",
"this",
".",
"status",
"=",
"ElementStatusIndicator",
".",
"NONE",
";",
"}",
"/**\n * Constructor for a ConfigurableElement with a parent as param.\n * @param parent The elements parent.\n * @param displayName Name of the element (may be <b>null</b> in order to ask the <code>input</code> for its name).\n * @param editorId The editorID.\n * @param input The editor input creator.\n */",
"public",
"ConfigurableElement",
"(",
"ConfigurableElement",
"parent",
",",
"String",
"displayName",
",",
"String",
"editorId",
",",
"IEditorInputCreator",
"input",
")",
"{",
"this",
"(",
"parent",
",",
"displayName",
",",
"editorId",
",",
"input",
",",
"parent",
".",
"getModelPart",
"(",
")",
")",
";",
"}",
"/**\n * Constructor for a top-level ConfigurableElement.\n * \n * @param displayName Name of the element.\n * @param editorId The editorID.\n * @param input The editor input creator.\n * @param modelPart the underlying model part\n */",
"public",
"ConfigurableElement",
"(",
"String",
"displayName",
",",
"String",
"editorId",
",",
"IEditorInputCreator",
"input",
",",
"IModelPart",
"modelPart",
")",
"{",
"this",
"(",
"null",
",",
"displayName",
",",
"editorId",
",",
"input",
",",
"modelPart",
")",
";",
"}",
"/**\n * Set the indicator for falwed configurableElements.\n * @param newValue new value tre if element is falwed, false if not.\n */",
"public",
"void",
"setFlawedIndicator",
"(",
"boolean",
"newValue",
")",
"{",
"isFlawed",
"=",
"newValue",
";",
"}",
"/**\n * Get the information about this element. True if falwed, false if not.\n * @return isFlawed true -> Element is falwed, false -> Element is not falwed.\n */",
"public",
"boolean",
"getFlawedIndicator",
"(",
")",
"{",
"return",
"isFlawed",
";",
"}",
"/**\n * Returns the model part displayed (full or partially) by this configurable element.\n * \n * @return the model part\n */",
"public",
"IModelPart",
"getModelPart",
"(",
")",
"{",
"return",
"modelPart",
";",
"}",
"/**\n * Tries to cast the given Object in {@link ConfigurableElement}.\n * If this is successful, the method returns the {@link ConfigurableElement}.\n * Otherwise the method returns NULL!\n * @param object Given object which will be cast to {@link ConfigurableElement}.\n * @return result The resulted {@link ConfigurableElement}. Null if object was not instance of \n * {@link ConfigurableElement}.\n */",
"public",
"static",
"ConfigurableElement",
"asConfigurableElement",
"(",
"Object",
"object",
")",
"{",
"ConfigurableElement",
"result",
";",
"if",
"(",
"object",
"instanceof",
"ConfigurableElement",
")",
"{",
"result",
"=",
"(",
"ConfigurableElement",
")",
"object",
";",
"}",
"else",
"{",
"result",
"=",
"null",
";",
"}",
"return",
"result",
";",
"}",
"/**\n * Add a child to this configurable element. The parent of\n * <code>child</code> shall be <b>this</b>.\n * \n * @param child the child to be added\n */",
"public",
"void",
"addChildAtTop",
"(",
"ConfigurableElement",
"child",
")",
"{",
"assert",
"this",
"==",
"child",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"null",
"==",
"children",
")",
"{",
"children",
"=",
"new",
"ArrayList",
"<",
"ConfigurableElement",
">",
"(",
")",
";",
"}",
"children",
".",
"add",
"(",
"0",
",",
"child",
")",
";",
"}",
"/**\n * Add a child to this configurable element. The parent of\n * <code>child</code> shall be <b>this</b>.\n * \n * @param child the child to be added\n */",
"public",
"void",
"addChild",
"(",
"ConfigurableElement",
"child",
")",
"{",
"assert",
"this",
"==",
"child",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"null",
"==",
"children",
")",
"{",
"children",
"=",
"new",
"ArrayList",
"<",
"ConfigurableElement",
">",
"(",
")",
";",
"}",
"children",
".",
"add",
"(",
"child",
")",
";",
"}",
"/**\n * Creates and adds a new child for <code>variable</code> (via {@link IModelPart#getElementFactory()}).\n * This method may issue change notification messages.\n * \n * @param source the event source\n * @param variable the variable to create the element for\n * @return the created element (may be <b>null</b>)\n */",
"public",
"ConfigurableElement",
"addChild",
"(",
"Object",
"source",
",",
"IDecisionVariable",
"variable",
")",
"{",
"IVariableEditorInputCreator",
"creator",
"=",
"null",
";",
"IDatatype",
"varType",
"=",
"variable",
".",
"getDeclaration",
"(",
")",
".",
"getType",
"(",
")",
";",
"if",
"(",
"Compound",
".",
"TYPE",
".",
"isAssignableFrom",
"(",
"varType",
")",
")",
"{",
"if",
"(",
"variable",
".",
"getParent",
"(",
")",
"instanceof",
"ContainerVariable",
")",
"{",
"ContainerVariable",
"cVar",
"=",
"(",
"ContainerVariable",
")",
"variable",
".",
"getParent",
"(",
")",
";",
"creator",
"=",
"new",
"ContainerVariableEditorInputCreator",
"(",
"modelPart",
",",
"cVar",
".",
"getDeclaration",
"(",
")",
".",
"getName",
"(",
")",
",",
"cVar",
".",
"indexOf",
"(",
"variable",
")",
")",
";",
"}",
"else",
"{",
"creator",
"=",
"new",
"CompoundVariableEditorInputCreator",
"(",
"modelPart",
",",
"variable",
".",
"getDeclaration",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"variable",
".",
"getParent",
"(",
")",
"instanceof",
"ContainerVariable",
")",
"{",
"ContainerVariable",
"cont",
"=",
"(",
"ContainerVariable",
")",
"variable",
".",
"getParent",
"(",
")",
";",
"int",
"index",
"=",
"cont",
".",
"indexOf",
"(",
"variable",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"creator",
"=",
"new",
"ContainerVariableEditorInputCreator",
"(",
"modelPart",
",",
"variable",
".",
"getParent",
"(",
")",
".",
"getDeclaration",
"(",
")",
".",
"getName",
"(",
")",
",",
"index",
")",
";",
"}",
"}",
"ConfigurableElement",
"child",
"=",
"null",
";",
"if",
"(",
"null",
"!=",
"creator",
")",
"{",
"child",
"=",
"modelPart",
".",
"getElementFactory",
"(",
")",
".",
"createElement",
"(",
"this",
",",
"variable",
",",
"creator",
")",
";",
"if",
"(",
"null",
"!=",
"variable",
".",
"getParent",
"(",
")",
"&&",
"variable",
".",
"getParent",
"(",
")",
"instanceof",
"SequenceVariable",
")",
"{",
"if",
"(",
"\"",
"configuredParameters",
"\"",
".",
"equals",
"(",
"variable",
".",
"getParent",
"(",
")",
".",
"getDeclaration",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
"{",
"addDefaultValues",
"(",
"variable",
")",
";",
"IEditorInput",
"input",
"=",
"child",
".",
"getEditorInputCreator",
"(",
")",
".",
"create",
"(",
")",
";",
"if",
"(",
"input",
"instanceof",
"DecisionVariableEditorInput",
")",
"{",
"DecisionVariableEditorInput",
"decInput",
"=",
"(",
"DecisionVariableEditorInput",
")",
"input",
";",
"addDefaultValues",
"(",
"decInput",
".",
"getVariable",
"(",
")",
")",
";",
"}",
"}",
"}",
"addChild",
"(",
"child",
")",
";",
"creator",
".",
"createArtifacts",
"(",
")",
";",
"ChangeManager",
".",
"INSTANCE",
".",
"variableAdded",
"(",
"source",
",",
"variable",
")",
";",
"}",
"return",
"child",
";",
"}",
"/**\n * Adds a default name to the Observable, if not was given yet. This is neccessary for the model to load correctly\n * and will lead to crashes and freezes if ignored.\n * @param var The variable that needs a default name.\n */",
"private",
"void",
"addDefaultValues",
"(",
"IDecisionVariable",
"var",
")",
"{",
"IDecisionVariable",
"type",
"=",
"var",
".",
"getNestedElement",
"(",
"SLOT_OBSERVABLE_TYPE",
")",
";",
"if",
"(",
"null",
"!=",
"type",
"&&",
"null",
"==",
"type",
".",
"getValue",
"(",
")",
")",
"{",
"String",
"defaultName",
"=",
"null",
";",
"SequenceVariable",
"parent",
"=",
"null",
";",
"if",
"(",
"null",
"!=",
"var",
".",
"getParent",
"(",
")",
"&&",
"var",
".",
"getParent",
"(",
")",
"instanceof",
"SequenceVariable",
")",
"{",
"parent",
"=",
"(",
"SequenceVariable",
")",
"var",
".",
"getParent",
"(",
")",
";",
"}",
"if",
"(",
"null",
"!=",
"parent",
")",
"{",
"defaultName",
"=",
"parent",
".",
"getDeclaration",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
" [",
"\"",
"+",
"(",
"parent",
".",
"getNestedElementsCount",
"(",
")",
"-",
"1",
")",
"+",
"\"",
"]",
"\"",
";",
"}",
"Value",
"newValue",
";",
"try",
"{",
"newValue",
"=",
"ValueFactory",
".",
"createValue",
"(",
"type",
".",
"getDeclaration",
"(",
")",
".",
"getType",
"(",
")",
",",
"new",
"Object",
"[",
"]",
"{",
"defaultName",
"}",
")",
";",
"type",
".",
"setValue",
"(",
"newValue",
",",
"AssignmentState",
".",
"ASSIGNED",
")",
";",
"}",
"catch",
"(",
"ValueDoesNotMatchTypeException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"catch",
"(",
"ConfigurationException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
"/**\n * Get the displayName.\n * @return displayName The displayName.\n */",
"public",
"String",
"getDisplayName",
"(",
")",
"{",
"String",
"result",
";",
"if",
"(",
"null",
"==",
"displayName",
"&&",
"null",
"!=",
"input",
")",
"{",
"result",
"=",
"input",
".",
"getName",
"(",
")",
";",
"}",
"else",
"{",
"result",
"=",
"displayName",
";",
"}",
"if",
"(",
"null",
"==",
"result",
")",
"{",
"result",
"=",
"\"",
"\"",
";",
"}",
"return",
"result",
";",
"}",
"/**\n * Changes the display name.\n * \n * @param displayName the new display name\n */",
"public",
"void",
"setDisplayName",
"(",
"String",
"displayName",
")",
"{",
"this",
".",
"displayName",
"=",
"displayName",
";",
"}",
"/**\n * Returns the number of children of this configurable element.\n * \n * @return the number of children (non-negative)\n */",
"public",
"int",
"getChildCount",
"(",
")",
"{",
"return",
"null",
"==",
"children",
"?",
"0",
":",
"children",
".",
"size",
"(",
")",
";",
"}",
"/**\n * Returns the specified child.\n * \n * @param index the 0-based index of the child\n * @return the specified child\n * @throws IndexOutOfBoundsException if <code>index < 0 || index >={@link #getChildCount()}</code>\n */",
"public",
"ConfigurableElement",
"getChild",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"null",
"==",
"children",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"return",
"children",
".",
"get",
"(",
"index",
")",
";",
"}",
"/**\n * Returns the children as an array.\n * \n * @return the children as an array (new instance)\n */",
"public",
"ConfigurableElement",
"[",
"]",
"getChildren",
"(",
")",
"{",
"ConfigurableElement",
"[",
"]",
"result",
";",
"if",
"(",
"hasChildren",
"(",
")",
")",
"{",
"result",
"=",
"new",
"ConfigurableElement",
"[",
"children",
".",
"size",
"(",
")",
"]",
";",
"children",
".",
"toArray",
"(",
"result",
")",
";",
"}",
"else",
"{",
"result",
"=",
"null",
";",
"}",
"return",
"result",
";",
"}",
"/**\n * Check whether there are children.\n * @return true if there are children.\n * false if there are no children.\n */",
"public",
"boolean",
"hasChildren",
"(",
")",
"{",
"return",
"null",
"!=",
"children",
"&&",
"children",
".",
"size",
"(",
")",
">",
"0",
";",
"}",
"/**\n * Returns whether the selected element is a top-level element, thus, represents a model part.\n * \n * @return <code>true</code> if the selected element is a top-level element, <code>false</code> in case of \n * an inner node\n */",
"public",
"boolean",
"isTopLevel",
"(",
")",
"{",
"return",
"null",
"==",
"parent",
";",
"}",
"/**\n * Get the parent.\n * @return parent The parent.\n */",
"public",
"ConfigurableElement",
"getParent",
"(",
")",
"{",
"return",
"parent",
";",
"}",
"/**\n * Return the editor input creator.\n * \n * @return input The editor input creator.\n */",
"public",
"IEditorInputCreator",
"getEditorInputCreator",
"(",
")",
"{",
"return",
"input",
";",
"}",
"/**\n * Returns the editor id.\n * @return the editor id.\n */",
"public",
"String",
"getEditorId",
"(",
")",
"{",
"return",
"editorId",
";",
"}",
"/**\n * Returns the display name of the configurable element.\n * \n * @return the display name of the configurable element.\n */",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"getDisplayName",
"(",
")",
";",
"}",
"/**\n * Deletes <code>child</code> from the children of this element.\n * \n * @param child the child to be deleted\n * @return <code>true</code> if removed, <code>false</code> else\n */",
"public",
"boolean",
"deleteFromChildren",
"(",
"ConfigurableElement",
"child",
")",
"{",
"boolean",
"done",
"=",
"false",
";",
"if",
"(",
"null",
"!=",
"children",
")",
"{",
"if",
"(",
"!",
"child",
".",
"isTopLevel",
"(",
")",
")",
"{",
"int",
"index",
"=",
"children",
".",
"indexOf",
"(",
"child",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"ConfigurableElement",
"parent",
"=",
"child",
".",
"getParent",
"(",
")",
";",
"String",
"name",
"=",
"parent",
".",
"getDisplayName",
"(",
")",
";",
"if",
"(",
"child",
".",
"input",
"instanceof",
"ContainerVariableEditorInputCreator",
")",
"{",
"name",
"=",
"(",
"(",
"ContainerVariableEditorInputCreator",
")",
"child",
".",
"input",
")",
".",
"getVariableName",
"(",
")",
";",
"}",
"ContainerVariableEditorInputChangeListener",
".",
"INSTANCE",
".",
"notifyDeletetion",
"(",
"name",
",",
"index",
")",
";",
"}",
"}",
"else",
"{",
"int",
"index",
"=",
"children",
".",
"indexOf",
"(",
"child",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"String",
"name",
"=",
"child",
".",
"getDisplayName",
"(",
")",
";",
"ContainerVariableEditorInputChangeListener",
".",
"INSTANCE",
".",
"notifyDeletetion",
"(",
"name",
",",
"index",
")",
";",
"}",
"}",
"done",
"=",
"children",
".",
"remove",
"(",
"child",
")",
";",
"}",
"return",
"done",
";",
"}",
"/**\n * Deletes this element if possible. This method may issue change events.\n * \n * @param source the source for this call to send change events.\n */",
"public",
"void",
"delete",
"(",
"Object",
"source",
")",
"{",
"input",
".",
"delete",
"(",
"source",
",",
"modelPart",
")",
";",
"if",
"(",
"null",
"!=",
"parent",
")",
"{",
"parent",
".",
"deleteFromChildren",
"(",
"this",
")",
";",
"}",
"}",
"/**\n * Returns the index of the given <code>element</code> in the set of children.\n * \n * @param element the element to search for\n * @return the child index position, <code>-1</code> if not found\n */",
"public",
"int",
"indexOf",
"(",
"ConfigurableElement",
"element",
")",
"{",
"return",
"children",
".",
"indexOf",
"(",
"element",
")",
";",
"}",
"/**\n * Clones this configurable element. This method causes sending\n * changed events via {@link ChangeManager}.\n * \n * @param source the event source (for sending events)\n * @param count the number of clones to be created\n * @return the created clones (<b>null</b> if none were created)\n */",
"public",
"List",
"<",
"ConfigurableElement",
">",
"clone",
"(",
"Object",
"source",
",",
"int",
"count",
")",
"{",
"List",
"<",
"ConfigurableElement",
">",
"result",
"=",
"null",
";",
"if",
"(",
"!",
"isTopLevel",
"(",
")",
"&&",
"isCloneable",
"(",
")",
".",
"countAllowed",
"(",
"count",
")",
")",
"{",
"ConfigurableElement",
"parent",
"=",
"getParent",
"(",
")",
";",
"if",
"(",
"parent",
".",
"isVirtualSubGroup",
"(",
")",
")",
"{",
"parent",
"=",
"parent",
".",
"getParent",
"(",
")",
";",
"}",
"List",
"<",
"IDecisionVariable",
">",
"clones",
"=",
"input",
".",
"clone",
"(",
"count",
")",
";",
"if",
"(",
"null",
"!=",
"clones",
"&&",
"!",
"clones",
".",
"isEmpty",
"(",
")",
")",
"{",
"result",
"=",
"new",
"ArrayList",
"<",
"ConfigurableElement",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"clones",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"ConfigurableElement",
"child",
"=",
"parent",
".",
"addChild",
"(",
"source",
",",
"clones",
".",
"get",
"(",
"i",
")",
")",
";",
"if",
"(",
"null",
"!=",
"child",
")",
"{",
"result",
".",
"add",
"(",
"child",
")",
";",
"}",
"}",
"}",
"}",
"return",
"result",
";",
"}",
"/**\n * Returns whether this element is a virtual sub-group.\n * \n * @return <code>true</code> for a sub-group, <code>false</code> else\n */",
"public",
"boolean",
"isVirtualSubGroup",
"(",
")",
"{",
"return",
"null",
"==",
"getEditorInputCreator",
"(",
")",
"&&",
"null",
"!=",
"getParent",
"(",
")",
";",
"}",
"/**\n * Returns whether this element is cloneable.\n * \n * @return the clone mode\n */",
"public",
"CloneMode",
"isCloneable",
"(",
")",
"{",
"return",
"(",
"null",
"!=",
"input",
")",
"?",
"input",
".",
"isCloneable",
"(",
")",
":",
"CloneMode",
".",
"NONE",
";",
"}",
"/**\n * Returns whether this element is (basically) deletable. This method does not\n * determine any use of references to the underlying element.\n * \n * @return <code>true</code> if this element is deletable, <code>false</code> else\n */",
"public",
"boolean",
"isDeletable",
"(",
")",
"{",
"return",
"null",
"!=",
"getParent",
"(",
")",
"&&",
"null",
"!=",
"input",
"&&",
"input",
".",
"isDeletable",
"(",
")",
"&&",
"!",
"isVirtualSubGroup",
"(",
")",
";",
"}",
"/**\n * Returns whether this element is (basically) writable.\n * \n * @return <code>true</code> if this element is writable, <code>false</code> else\n */",
"public",
"boolean",
"isWritable",
"(",
")",
"{",
"return",
"(",
"null",
"==",
"getParent",
"(",
")",
"&&",
"VariabilityModel",
".",
"isWritable",
"(",
"modelPart",
")",
")",
"||",
"(",
"null",
"!=",
"input",
"&&",
"input",
".",
"isWritable",
"(",
")",
")",
";",
"}",
"/**\n * Returns whether this element is (basically) readable.\n * \n * @return <code>true</code> if this element is readable, <code>false</code> else\n */",
"public",
"boolean",
"isReadable",
"(",
")",
"{",
"return",
"(",
"null",
"==",
"getParent",
"(",
")",
"&&",
"VariabilityModel",
".",
"isReadable",
"(",
"modelPart",
")",
")",
"||",
"isVirtualSubGroup",
"(",
")",
"||",
"input",
".",
"isReadable",
"(",
")",
";",
"}",
"/**\n * Returns the configurable element holding the given <code>variable</code>.\n * \n * @param variable the variable to search for\n * @return the configurable element holding <code>variable</code> or <b>null</b> if none was found\n */",
"public",
"ConfigurableElement",
"findElement",
"(",
"IDecisionVariable",
"variable",
")",
"{",
"ConfigurableElement",
"result",
"=",
"null",
";",
"if",
"(",
"null",
"!=",
"input",
"&&",
"input",
".",
"holds",
"(",
"variable",
")",
")",
"{",
"result",
"=",
"this",
";",
"}",
"if",
"(",
"null",
"!=",
"children",
")",
"{",
"for",
"(",
"int",
"e",
"=",
"0",
";",
"null",
"==",
"result",
"&&",
"e",
"<",
"children",
".",
"size",
"(",
")",
";",
"e",
"++",
")",
"{",
"result",
"=",
"children",
".",
"get",
"(",
"e",
")",
".",
"findElement",
"(",
"variable",
")",
";",
"}",
"}",
"return",
"result",
";",
"}",
"/**\n * Whether the given configurable element holds the same variable.\n * \n * @param element the element to check for (may be <b>null</b>)\n * @return <code>true</code> if same, <code>false</code> else\n */",
"public",
"boolean",
"holdsSame",
"(",
"ConfigurableElement",
"element",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"if",
"(",
"null",
"!=",
"input",
")",
"{",
"IDecisionVariable",
"iVar",
"=",
"input",
".",
"getVariable",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"iVar",
"&&",
"null",
"!=",
"element",
"&&",
"null",
"!=",
"element",
".",
"input",
")",
"{",
"IDecisionVariable",
"eVar",
"=",
"element",
".",
"input",
".",
"getVariable",
"(",
")",
";",
"result",
"=",
"eVar",
".",
"equals",
"(",
"iVar",
")",
";",
"}",
"}",
"return",
"result",
";",
"}",
"/**\n * Returns whether the underlying element is referenced in the given <code>modelPart</code>.\n * \n * @param modelPart the part to search in\n * @return <code>true</code> if the underlying element is referenced in <code>modelPart</code>, <code>false</code> \n * else\n */",
"public",
"boolean",
"isReferencedIn",
"(",
"IModelPart",
"modelPart",
")",
"{",
"if",
"(",
"null",
"==",
"modelPart",
")",
"{",
"modelPart",
"=",
"this",
".",
"modelPart",
";",
"}",
"return",
"input",
".",
"isReferencedIn",
"(",
"modelPart",
",",
"this",
".",
"modelPart",
")",
";",
"}",
"/**\n * Returns the image of this configurable element.\n * \n * @return the image (may be <b>null</b>, indicates that the default [platform] image shall be used)\n */",
"public",
"Image",
"getImage",
"(",
")",
"{",
"return",
"image",
";",
"}",
"/**\n * Defines the image of this configurable element.\n * \n * @param image the image\n * @return <b>this</b> (builder pattern)\n */",
"public",
"ConfigurableElement",
"setImage",
"(",
"Image",
"image",
")",
"{",
"this",
".",
"image",
"=",
"image",
";",
"return",
"this",
";",
"}",
"/**\n * Defines the menu contributor.\n * \n * @param menuContributor the contributor, may be <b>null</b> if disabled\n */",
"public",
"void",
"setMenuContributor",
"(",
"IMenuContributor",
"menuContributor",
")",
"{",
"this",
".",
"menuContributor",
"=",
"menuContributor",
";",
"}",
"/**\n * Asks for contributions to the related popup menu.\n * \n * @param manager the menu manager\n */",
"public",
"void",
"contributeToPopup",
"(",
"IMenuManager",
"manager",
")",
"{",
"if",
"(",
"null",
"!=",
"input",
")",
"{",
"IMenuContributor",
"contributor",
"=",
"input",
".",
"getMenuContributor",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"contributor",
")",
"{",
"contributor",
".",
"contributeTo",
"(",
"manager",
")",
";",
"}",
"}",
"if",
"(",
"null",
"!=",
"menuContributor",
")",
"{",
"menuContributor",
".",
"contributeTo",
"(",
"manager",
")",
";",
"}",
"}",
"/**\n * Get the current dataflow information for this configurable element.\n * @return dataflow The current dataflow information for this element.\n */",
"public",
"ElementStatusIndicator",
"getStatus",
"(",
")",
"{",
"return",
"status",
";",
"}",
"/**\n * Set the dataflow information for this configurable element.\n * @param indicator New assigned dataflow information for this element.\n */",
"public",
"void",
"setStatus",
"(",
"ElementStatusIndicator",
"indicator",
")",
"{",
"this",
".",
"status",
"=",
"indicator",
";",
"}",
"}"
] | Class manages a list of configurable elements which we populate in order to show these elements
in the {@link ConfigurableElementsView} of the QualiMaster-App. | [
"Class",
"manages",
"a",
"list",
"of",
"configurable",
"elements",
"which",
"we",
"populate",
"in",
"order",
"to",
"show",
"these",
"elements",
"in",
"the",
"{",
"@link",
"ConfigurableElementsView",
"}",
"of",
"the",
"QualiMaster",
"-",
"App",
"."
] | [
"// unsure whether this shall be a resource",
"// if (null != variable.getParent() && variable.getParent() instanceof SequenceVariable) {",
"// if (\"configuredParameters\".equals(variable.getParent().getDeclaration().getName())) {",
"// addDefaultValues(variable);",
"// }",
"// }",
"// || parent.input instanceof VarModelEditorInputCreator;",
"// String name = child.input.getName();",
"// String name = child.input.getName();",
"// top-level elements are not deletable"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd55e188b0fcdd10885470d5ed5dd9411d2fa627 | xhaleera/WhiteShark-for-Java | java/com/xhaleera/whiteshark/exceptions/WhiteSharkException.java | [
"MIT"
] | Java | WhiteSharkException | /**
* Base class for WhiteShark exceptions
*
* @author Christophe SAUVEUR (christophe@xhaleera.com)
* @since 1.0
* @version 1.0
*/ | Base class for WhiteShark exceptions
| [
"Base",
"class",
"for",
"WhiteShark",
"exceptions"
] | public class WhiteSharkException extends Exception {
/** Serialization version UID */
static final long serialVersionUID = 1;
/**
* Default constructor with no message
*/
public WhiteSharkException() {
super();
}
/**
* Constructor with custom message
* @param arg0 Custom message
*/
public WhiteSharkException(String arg0) {
super(arg0);
}
/**
* Constructor with cause Throwable
* @param arg0 Throwable that caused that exception
*/
public WhiteSharkException(Throwable arg0) {
super(arg0);
}
/**
* Constructor with custom message and cause Throwable
* @param arg0 Custom message
* @param arg1 Throwable that caused that exception
*/
public WhiteSharkException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
} | [
"public",
"class",
"WhiteSharkException",
"extends",
"Exception",
"{",
"/** Serialization version UID */",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1",
";",
"/**\n\t * Default constructor with no message\n\t */",
"public",
"WhiteSharkException",
"(",
")",
"{",
"super",
"(",
")",
";",
"}",
"/**\n\t * Constructor with custom message\n\t * @param arg0 Custom message\n\t */",
"public",
"WhiteSharkException",
"(",
"String",
"arg0",
")",
"{",
"super",
"(",
"arg0",
")",
";",
"}",
"/**\n\t * Constructor with cause Throwable\n\t * @param arg0 Throwable that caused that exception\n\t */",
"public",
"WhiteSharkException",
"(",
"Throwable",
"arg0",
")",
"{",
"super",
"(",
"arg0",
")",
";",
"}",
"/**\n\t * Constructor with custom message and cause Throwable\n\t * @param arg0 Custom message\n\t * @param arg1 Throwable that caused that exception\n\t */",
"public",
"WhiteSharkException",
"(",
"String",
"arg0",
",",
"Throwable",
"arg1",
")",
"{",
"super",
"(",
"arg0",
",",
"arg1",
")",
";",
"}",
"}"
] | Base class for WhiteShark exceptions | [
"Base",
"class",
"for",
"WhiteShark",
"exceptions"
] | [] | [
{
"param": "Exception",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Exception",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd56a6b9067ea1033434e0b9e93ed16377c2da2a | schnurlei/jdynameta | jdy/jdy.view.swing/src/main/java/de/jdynameta/metainfoview/attribute/model/PersListenerQueryObjectListModel.java | [
"Apache-2.0"
] | Java | PersListenerQueryObjectListModel | /**
* List Model that reads its objects by a Query
* It listens to the Persistence Manager for the add, remove and update of Object
* Translate a PersistentEvent into ObjectListModelEvent
*
* @author Rainer
*
*/ | List Model that reads its objects by a Query
It listens to the Persistence Manager for the add, remove and update of Object
Translate a PersistentEvent into ObjectListModelEvent
@author Rainer | [
"List",
"Model",
"that",
"reads",
"its",
"objects",
"by",
"a",
"Query",
"It",
"listens",
"to",
"the",
"Persistence",
"Manager",
"for",
"the",
"add",
"remove",
"and",
"update",
"of",
"Object",
"Translate",
"a",
"PersistentEvent",
"into",
"ObjectListModelEvent",
"@author",
"Rainer"
] | @SuppressWarnings("serial")
public class PersListenerQueryObjectListModel<TViewObj extends ValueObject> extends ApplicationQueryObjectListModel<TViewObj>
{
private PersistentObjectReader.PersistentListener<TViewObj> persistentListener;
/**
*
*/
public PersListenerQueryObjectListModel(PersistentObjectReader<TViewObj> aPersistenceReader
, final ClassInfoQuery aQuery) throws JdyPersistentException
{
this(aPersistenceReader, aQuery, true) ;
}
/**
*
*/
protected PersListenerQueryObjectListModel(PersistentObjectReader<TViewObj> aPersistenceReader
, final ClassInfoQuery aQuery, boolean islistenToChanges) throws JdyPersistentException
{
super( aPersistenceReader, aQuery);
this.persistentListener = new PersistentObjectReader.PersistentListener<TViewObj>()
{
public void persistentStateChanged(PersistentObjectReader.PersistentEvent<TViewObj> aEvent)
{
switch (aEvent.getState()) {
case OBJECT_CREATED :
if(getFilter().accept(aEvent.getChangedObject())){
getAllObjects().add( aEvent.getChangedObject());
fireIntervalAdded(PersListenerQueryObjectListModel.this,getAllObjects().size()-1,getAllObjects().size()-1);
}
break;
case OBJECT_DELETED :
int index = getAllObjects().indexOf(aEvent.getChangedObject());
if (index >= 0) {
getAllObjects().remove(aEvent.getChangedObject());
fireIntervalRemoved(PersListenerQueryObjectListModel.this,index,index, Collections.singletonList(aEvent.getChangedObject()));
}
break;
case OBJECT_MODIFIED :
int modIdx = getAllObjects().indexOf(aEvent.getChangedObject());
if (modIdx >= 0) {
fireIntervalUpdated(PersListenerQueryObjectListModel.this,modIdx,modIdx);
}
break;
} aEvent.getState();
}
};
if( islistenToChanges) {
aPersistenceReader.addListener(aQuery.getResultInfo(), persistentListener);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"",
"serial",
"\"",
")",
"public",
"class",
"PersListenerQueryObjectListModel",
"<",
"TViewObj",
"extends",
"ValueObject",
">",
"extends",
"ApplicationQueryObjectListModel",
"<",
"TViewObj",
">",
"{",
"private",
"PersistentObjectReader",
".",
"PersistentListener",
"<",
"TViewObj",
">",
"persistentListener",
";",
"/**\r\n\t * \r\n\t */",
"public",
"PersListenerQueryObjectListModel",
"(",
"PersistentObjectReader",
"<",
"TViewObj",
">",
"aPersistenceReader",
",",
"final",
"ClassInfoQuery",
"aQuery",
")",
"throws",
"JdyPersistentException",
"{",
"this",
"(",
"aPersistenceReader",
",",
"aQuery",
",",
"true",
")",
";",
"}",
"/**\r\n\t * \r\n\t */",
"protected",
"PersListenerQueryObjectListModel",
"(",
"PersistentObjectReader",
"<",
"TViewObj",
">",
"aPersistenceReader",
",",
"final",
"ClassInfoQuery",
"aQuery",
",",
"boolean",
"islistenToChanges",
")",
"throws",
"JdyPersistentException",
"{",
"super",
"(",
"aPersistenceReader",
",",
"aQuery",
")",
";",
"this",
".",
"persistentListener",
"=",
"new",
"PersistentObjectReader",
".",
"PersistentListener",
"<",
"TViewObj",
">",
"(",
")",
"{",
"public",
"void",
"persistentStateChanged",
"(",
"PersistentObjectReader",
".",
"PersistentEvent",
"<",
"TViewObj",
">",
"aEvent",
")",
"{",
"switch",
"(",
"aEvent",
".",
"getState",
"(",
")",
")",
"{",
"case",
"OBJECT_CREATED",
":",
"if",
"(",
"getFilter",
"(",
")",
".",
"accept",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
")",
"{",
"getAllObjects",
"(",
")",
".",
"add",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
";",
"fireIntervalAdded",
"(",
"PersListenerQueryObjectListModel",
".",
"this",
",",
"getAllObjects",
"(",
")",
".",
"size",
"(",
")",
"-",
"1",
",",
"getAllObjects",
"(",
")",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"break",
";",
"case",
"OBJECT_DELETED",
":",
"int",
"index",
"=",
"getAllObjects",
"(",
")",
".",
"indexOf",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"getAllObjects",
"(",
")",
".",
"remove",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
";",
"fireIntervalRemoved",
"(",
"PersListenerQueryObjectListModel",
".",
"this",
",",
"index",
",",
"index",
",",
"Collections",
".",
"singletonList",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
")",
";",
"}",
"break",
";",
"case",
"OBJECT_MODIFIED",
":",
"int",
"modIdx",
"=",
"getAllObjects",
"(",
")",
".",
"indexOf",
"(",
"aEvent",
".",
"getChangedObject",
"(",
")",
")",
";",
"if",
"(",
"modIdx",
">=",
"0",
")",
"{",
"fireIntervalUpdated",
"(",
"PersListenerQueryObjectListModel",
".",
"this",
",",
"modIdx",
",",
"modIdx",
")",
";",
"}",
"break",
";",
"}",
"aEvent",
".",
"getState",
"(",
")",
";",
"}",
"}",
";",
"if",
"(",
"islistenToChanges",
")",
"{",
"aPersistenceReader",
".",
"addListener",
"(",
"aQuery",
".",
"getResultInfo",
"(",
")",
",",
"persistentListener",
")",
";",
"}",
"}",
"}"
] | List Model that reads its objects by a Query
It listens to the Persistence Manager for the add, remove and update of Object
Translate a PersistentEvent into ObjectListModelEvent | [
"List",
"Model",
"that",
"reads",
"its",
"objects",
"by",
"a",
"Query",
"It",
"listens",
"to",
"the",
"Persistence",
"Manager",
"for",
"the",
"add",
"remove",
"and",
"update",
"of",
"Object",
"Translate",
"a",
"PersistentEvent",
"into",
"ObjectListModelEvent"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd5df6f2a47e7f201d44d563d954fa7e56bcb61d | jomrazek/pnc | bpm/src/test/java/org/jboss/pnc/bpm/test/BuildResultRestTest.java | [
"Apache-2.0"
] | Java | BuildResultRestTest | /**
* @author Jakub Bartecek
*/ | @author Jakub Bartecek | [
"@author",
"Jakub",
"Bartecek"
] | public class BuildResultRestTest {
private final String LOG = "LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" +
"GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG";
@Test
public void shouldGetLimitedToStringWithNulls() {
BuildResultRest buildResultRest = new BuildResultRest();
buildResultRest.toString();
}
@Test
public void shouldGetLimitedToStringWithSomeValues() {
BuildResultRest buildResultRest = new BuildResultRest();
buildResultRest.setCompletionStatus(CompletionStatus.SUCCESS);
buildResultRest.setProcessException(null);
buildResultRest.setProcessLog(LOG);
buildResultRest.setBuildExecutionConfiguration(null);
buildResultRest.setBuildDriverResult(null);
buildResultRest.setRepositoryManagerResult(null);
EnvironmentDriverResult environmentDriverResult = new EnvironmentDriverResult(CompletionStatus.SUCCESS, "SUCCESS", Optional.empty());
buildResultRest.setEnvironmentDriverResult(environmentDriverResult);
buildResultRest.setRepourResult(new RepourResult(CompletionStatus.SUCCESS, "Repour Success", "org.jboss", "1.1.0.Final-redhat-1"));
buildResultRest.toString();
}
} | [
"public",
"class",
"BuildResultRestTest",
"{",
"private",
"final",
"String",
"LOG",
"=",
"\"",
"LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"\"",
"+",
"\"",
"GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG",
"\"",
";",
"@",
"Test",
"public",
"void",
"shouldGetLimitedToStringWithNulls",
"(",
")",
"{",
"BuildResultRest",
"buildResultRest",
"=",
"new",
"BuildResultRest",
"(",
")",
";",
"buildResultRest",
".",
"toString",
"(",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"shouldGetLimitedToStringWithSomeValues",
"(",
")",
"{",
"BuildResultRest",
"buildResultRest",
"=",
"new",
"BuildResultRest",
"(",
")",
";",
"buildResultRest",
".",
"setCompletionStatus",
"(",
"CompletionStatus",
".",
"SUCCESS",
")",
";",
"buildResultRest",
".",
"setProcessException",
"(",
"null",
")",
";",
"buildResultRest",
".",
"setProcessLog",
"(",
"LOG",
")",
";",
"buildResultRest",
".",
"setBuildExecutionConfiguration",
"(",
"null",
")",
";",
"buildResultRest",
".",
"setBuildDriverResult",
"(",
"null",
")",
";",
"buildResultRest",
".",
"setRepositoryManagerResult",
"(",
"null",
")",
";",
"EnvironmentDriverResult",
"environmentDriverResult",
"=",
"new",
"EnvironmentDriverResult",
"(",
"CompletionStatus",
".",
"SUCCESS",
",",
"\"",
"SUCCESS",
"\"",
",",
"Optional",
".",
"empty",
"(",
")",
")",
";",
"buildResultRest",
".",
"setEnvironmentDriverResult",
"(",
"environmentDriverResult",
")",
";",
"buildResultRest",
".",
"setRepourResult",
"(",
"new",
"RepourResult",
"(",
"CompletionStatus",
".",
"SUCCESS",
",",
"\"",
"Repour Success",
"\"",
",",
"\"",
"org.jboss",
"\"",
",",
"\"",
"1.1.0.Final-redhat-1",
"\"",
")",
")",
";",
"buildResultRest",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | @author Jakub Bartecek | [
"@author",
"Jakub",
"Bartecek"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd6ba062fb9a13c874bb897a784b67d04c43ece1 | DirectXceriD/gridgain | modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/impl/fs/HadoopFileSystemsUtils.java | [
"Apache-2.0",
"CC0-1.0"
] | Java | HadoopFileSystemsUtils | /**
* Utilities for configuring file systems to support the separate working directory per each thread.
*/ | Utilities for configuring file systems to support the separate working directory per each thread. | [
"Utilities",
"for",
"configuring",
"file",
"systems",
"to",
"support",
"the",
"separate",
"working",
"directory",
"per",
"each",
"thread",
"."
] | public class HadoopFileSystemsUtils {
/** Name of the property for setting working directory on create new local FS instance. */
public static final String LOC_FS_WORK_DIR_PROP = "fs." + FsConstants.LOCAL_FS_URI.getScheme() + ".workDir";
/**
* Setup wrappers of filesystems to support the separate working directory.
*
* @param cfg Config for setup.
*/
public static void setupFileSystems(Configuration cfg) {
cfg.set("fs." + FsConstants.LOCAL_FS_URI.getScheme() + ".impl", HadoopLocalFileSystemV1.class.getName());
cfg.set("fs.AbstractFileSystem." + FsConstants.LOCAL_FS_URI.getScheme() + ".impl",
HadoopLocalFileSystemV2.class.getName());
}
/**
* Gets the property name to disable file system cache.
* @param scheme The file system URI scheme.
* @return The property name. If scheme is null,
* returns "fs.null.impl.disable.cache".
*/
public static String disableFsCachePropertyName(@Nullable String scheme) {
return String.format("fs.%s.impl.disable.cache", scheme);
}
/**
* Clears Hadoop {@link FileSystem} cache.
*
* @throws IOException On error.
*/
public static void clearFileSystemCache() throws IOException {
FileSystem.closeAll();
}
} | [
"public",
"class",
"HadoopFileSystemsUtils",
"{",
"/** Name of the property for setting working directory on create new local FS instance. */",
"public",
"static",
"final",
"String",
"LOC_FS_WORK_DIR_PROP",
"=",
"\"",
"fs.",
"\"",
"+",
"FsConstants",
".",
"LOCAL_FS_URI",
".",
"getScheme",
"(",
")",
"+",
"\"",
".workDir",
"\"",
";",
"/**\n * Setup wrappers of filesystems to support the separate working directory.\n *\n * @param cfg Config for setup.\n */",
"public",
"static",
"void",
"setupFileSystems",
"(",
"Configuration",
"cfg",
")",
"{",
"cfg",
".",
"set",
"(",
"\"",
"fs.",
"\"",
"+",
"FsConstants",
".",
"LOCAL_FS_URI",
".",
"getScheme",
"(",
")",
"+",
"\"",
".impl",
"\"",
",",
"HadoopLocalFileSystemV1",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"cfg",
".",
"set",
"(",
"\"",
"fs.AbstractFileSystem.",
"\"",
"+",
"FsConstants",
".",
"LOCAL_FS_URI",
".",
"getScheme",
"(",
")",
"+",
"\"",
".impl",
"\"",
",",
"HadoopLocalFileSystemV2",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"}",
"/**\n * Gets the property name to disable file system cache.\n * @param scheme The file system URI scheme.\n * @return The property name. If scheme is null,\n * returns \"fs.null.impl.disable.cache\".\n */",
"public",
"static",
"String",
"disableFsCachePropertyName",
"(",
"@",
"Nullable",
"String",
"scheme",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"",
"fs.%s.impl.disable.cache",
"\"",
",",
"scheme",
")",
";",
"}",
"/**\n * Clears Hadoop {@link FileSystem} cache.\n *\n * @throws IOException On error.\n */",
"public",
"static",
"void",
"clearFileSystemCache",
"(",
")",
"throws",
"IOException",
"{",
"FileSystem",
".",
"closeAll",
"(",
")",
";",
"}",
"}"
] | Utilities for configuring file systems to support the separate working directory per each thread. | [
"Utilities",
"for",
"configuring",
"file",
"systems",
"to",
"support",
"the",
"separate",
"working",
"directory",
"per",
"each",
"thread",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd6bb563da1f2d75486aa27da30c15a152384768 | JaniceHe264/adafruit5 | jarboot-core/src/main/java/com/mz/jarboot/core/stream/ResultStreamDistributor.java | [
"Apache-2.0"
] | Java | ResultStreamDistributor | /**
* Use websocket or http to send response data, we need a strategy so that the needed component did not
* care which to use. The server max socket listen buffer is 8k, we must make sure lower it.
* @author majianzheng
*/ | Use websocket or http to send response data, we need a strategy so that the needed component did not
care which to use. The server max socket listen buffer is 8k, we must make sure lower it.
@author majianzheng | [
"Use",
"websocket",
"or",
"http",
"to",
"send",
"response",
"data",
"we",
"need",
"a",
"strategy",
"so",
"that",
"the",
"needed",
"component",
"did",
"not",
"care",
"which",
"to",
"use",
".",
"The",
"server",
"max",
"socket",
"listen",
"buffer",
"is",
"8k",
"we",
"must",
"make",
"sure",
"lower",
"it",
".",
"@author",
"majianzheng"
] | public class ResultStreamDistributor {
private static final Logger logger = LogUtils.getLogger();
private final ResponseStream stream = new ResponseStreamDelegate();
private final ResultViewResolver resultViewResolver = new ResultViewResolver();
public static ResultStreamDistributor getInstance() {
return ResultStreamDistributorHolder.INST;
}
/** instance holder */
private static class ResultStreamDistributorHolder {
static final ResultStreamDistributor INST = new ResultStreamDistributor();
}
/**
* 输出执行结果
* @param model 数据
* @param session 会话
*/
@SuppressWarnings({"unchecked", "java:S3740", "rawtypes"})
public void appendResult(ResultModel model, String session) {
ResultView resultView = ResultStreamDistributorHolder.INST.resultViewResolver.getResultView(model);
if (resultView == null) {
logger.info("获取视图解析失败!{}, {}", model.getName(), model.getClass());
return;
}
String text = resultView.render(model);
NotifyType type = resultView.isJson() ? NotifyType.JSON_RESULT : NotifyType.CONSOLE;
response(true, ResponseType.NOTIFY, type.body(text), session);
}
/**
* 标准输出,退格
* @param num 次数
*/
void stdBackspace(int num) {
if (num > 0) {
response(true, ResponseType.BACKSPACE, String.valueOf(num), StringUtils.EMPTY);
}
}
/**
* 分布式日志记录
* @param text 日志
*/
public void log(String text) {
response(true, ResponseType.LOG_APPENDER, text, StringUtils.EMPTY);
}
public void response(boolean success, ResponseType type, String body, String id) {
NotifyReactor
.getInstance()
.publishEvent(new ResponseEventBuilder()
.success(success)
.type(type)
.body(body)
.session(id)
.build());
}
private void sendToServer(CommandResponse resp) {
if (WsClientFactory.getInstance().isOnline()) {
//根据数据包的大小选择合适的通讯方式
byte[] raw = resp.toRaw();
stream.write(raw);
}
}
private ResultStreamDistributor() {
//命令响应事件
NotifyReactor.getInstance().registerSubscriber(new Subscriber<CommandResponse>() {
@Override
public void onEvent(CommandResponse event) {
sendToServer(event);
}
@Override
public Class<? extends JarbootEvent> subscribeType() {
return CommandResponse.class;
}
});
//std文本输出事件
NotifyReactor.getInstance().registerSubscriber(new Subscriber<StdoutAppendEvent>() {
@Override
public void onEvent(StdoutAppendEvent event) {
sendToServer(new ResponseEventBuilder()
.success(true)
.type(ResponseType.STD_PRINT)
.body(event.getText())
.session(StringUtils.EMPTY)
.build());
}
@Override
public Class<? extends JarbootEvent> subscribeType() {
return StdoutAppendEvent.class;
}
});
}
} | [
"public",
"class",
"ResultStreamDistributor",
"{",
"private",
"static",
"final",
"Logger",
"logger",
"=",
"LogUtils",
".",
"getLogger",
"(",
")",
";",
"private",
"final",
"ResponseStream",
"stream",
"=",
"new",
"ResponseStreamDelegate",
"(",
")",
";",
"private",
"final",
"ResultViewResolver",
"resultViewResolver",
"=",
"new",
"ResultViewResolver",
"(",
")",
";",
"public",
"static",
"ResultStreamDistributor",
"getInstance",
"(",
")",
"{",
"return",
"ResultStreamDistributorHolder",
".",
"INST",
";",
"}",
"/** instance holder */",
"private",
"static",
"class",
"ResultStreamDistributorHolder",
"{",
"static",
"final",
"ResultStreamDistributor",
"INST",
"=",
"new",
"ResultStreamDistributor",
"(",
")",
";",
"}",
"/**\n * 输出执行结果\n * @param model 数据\n * @param session 会话\n */",
"@",
"SuppressWarnings",
"(",
"{",
"\"",
"unchecked",
"\"",
",",
"\"",
"java:S3740",
"\"",
",",
"\"",
"rawtypes",
"\"",
"}",
")",
"public",
"void",
"appendResult",
"(",
"ResultModel",
"model",
",",
"String",
"session",
")",
"{",
"ResultView",
"resultView",
"=",
"ResultStreamDistributorHolder",
".",
"INST",
".",
"resultViewResolver",
".",
"getResultView",
"(",
"model",
")",
";",
"if",
"(",
"resultView",
"==",
"null",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"获取视图解析失败!{}, {}\", model.getName()",
",",
" ",
"odel.",
"g",
"etClass",
"(",
")",
")",
"",
"",
"",
"",
"",
"",
"",
"return",
";",
"}",
"String",
"text",
"=",
"resultView",
".",
"render",
"(",
"model",
")",
";",
"NotifyType",
"type",
"=",
"resultView",
".",
"isJson",
"(",
")",
"?",
"NotifyType",
".",
"JSON_RESULT",
":",
"NotifyType",
".",
"CONSOLE",
";",
"response",
"(",
"true",
",",
"ResponseType",
".",
"NOTIFY",
",",
"type",
".",
"body",
"(",
"text",
")",
",",
"session",
")",
";",
"}",
"/**\n * 标准输出,退格\n * @param num 次数\n */",
"void",
"stdBackspace",
"(",
"int",
"num",
")",
"{",
"if",
"(",
"num",
">",
"0",
")",
"{",
"response",
"(",
"true",
",",
"ResponseType",
".",
"BACKSPACE",
",",
"String",
".",
"valueOf",
"(",
"num",
")",
",",
"StringUtils",
".",
"EMPTY",
")",
";",
"}",
"}",
"/**\n * 分布式日志记录\n * @param text 日志\n */",
"public",
"void",
"log",
"(",
"String",
"text",
")",
"{",
"response",
"(",
"true",
",",
"ResponseType",
".",
"LOG_APPENDER",
",",
"text",
",",
"StringUtils",
".",
"EMPTY",
")",
";",
"}",
"public",
"void",
"response",
"(",
"boolean",
"success",
",",
"ResponseType",
"type",
",",
"String",
"body",
",",
"String",
"id",
")",
"{",
"NotifyReactor",
".",
"getInstance",
"(",
")",
".",
"publishEvent",
"(",
"new",
"ResponseEventBuilder",
"(",
")",
".",
"success",
"(",
"success",
")",
".",
"type",
"(",
"type",
")",
".",
"body",
"(",
"body",
")",
".",
"session",
"(",
"id",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"private",
"void",
"sendToServer",
"(",
"CommandResponse",
"resp",
")",
"{",
"if",
"(",
"WsClientFactory",
".",
"getInstance",
"(",
")",
".",
"isOnline",
"(",
")",
")",
"{",
"byte",
"[",
"]",
"raw",
"=",
"resp",
".",
"toRaw",
"(",
")",
";",
"stream",
".",
"write",
"(",
"raw",
")",
";",
"}",
"}",
"private",
"ResultStreamDistributor",
"(",
")",
"{",
"NotifyReactor",
".",
"getInstance",
"(",
")",
".",
"registerSubscriber",
"(",
"new",
"Subscriber",
"<",
"CommandResponse",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onEvent",
"(",
"CommandResponse",
"event",
")",
"{",
"sendToServer",
"(",
"event",
")",
";",
"}",
"@",
"Override",
"public",
"Class",
"<",
"?",
"extends",
"JarbootEvent",
">",
"subscribeType",
"(",
")",
"{",
"return",
"CommandResponse",
".",
"class",
";",
"}",
"}",
")",
";",
"NotifyReactor",
".",
"getInstance",
"(",
")",
".",
"registerSubscriber",
"(",
"new",
"Subscriber",
"<",
"StdoutAppendEvent",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onEvent",
"(",
"StdoutAppendEvent",
"event",
")",
"{",
"sendToServer",
"(",
"new",
"ResponseEventBuilder",
"(",
")",
".",
"success",
"(",
"true",
")",
".",
"type",
"(",
"ResponseType",
".",
"STD_PRINT",
")",
".",
"body",
"(",
"event",
".",
"getText",
"(",
")",
")",
".",
"session",
"(",
"StringUtils",
".",
"EMPTY",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"Class",
"<",
"?",
"extends",
"JarbootEvent",
">",
"subscribeType",
"(",
")",
"{",
"return",
"StdoutAppendEvent",
".",
"class",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Use websocket or http to send response data, we need a strategy so that the needed component did not
care which to use. | [
"Use",
"websocket",
"or",
"http",
"to",
"send",
"response",
"data",
"we",
"need",
"a",
"strategy",
"so",
"that",
"the",
"needed",
"component",
"did",
"not",
"care",
"which",
"to",
"use",
"."
] | [
"//根据数据包的大小选择合适的通讯方式",
"//命令响应事件",
"//std文本输出事件"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd6c1a99b81c0a66590c76f775ccde7f2b1de5e9 | NianGuu/PlayerEx | src/main/java/com/github/clevernucleus/playerex/api/client/RenderComponent.java | [
"MIT"
] | Java | RenderComponent | /**
*
* Utility wrapper object to allow static creation of lazily loaded text.
* @author CleverNucleus
*
*/ | Utility wrapper object to allow static creation of lazily loaded text. | [
"Utility",
"wrapper",
"object",
"to",
"allow",
"static",
"creation",
"of",
"lazily",
"loaded",
"text",
"."
] | @Environment(EnvType.CLIENT)
public final class RenderComponent {
private final Function<LivingEntity, Text> text;
private final Function<LivingEntity, List<Text>> tooltip;
private final int dx, dy;
private RenderComponent(final Function<LivingEntity, Text> functionIn, final Function<LivingEntity, List<Text>> tooltipIn, final int dx, final int dy) {
this.text = functionIn;
this.tooltip = tooltipIn;
this.dx = dx;
this.dy = dy;
}
/**
*
* @param functionIn display text.
* @param tooltipIn tooltip text.
* @param dx x position
* @param dy y position.
* @return
*/
public static RenderComponent of(final Function<LivingEntity, Text> functionIn, final Function<LivingEntity, List<Text>> tooltipIn, final int dx, final int dy) {
return new RenderComponent(functionIn, tooltipIn, dx, dy);
}
/**
*
* @param attributeIn the text (and therefore tooltip) only display if the player has this attribute and it is not null (i.e. registered to the game).
* @param functionIn display text.
* @param tooltipIn tooltip text.
* @param dx x position
* @param dy y position
* @return
*/
public static RenderComponent of(final Supplier<EntityAttribute> attributeIn, final Function<Float, Text> functionIn, final Function<Float, List<Text>> tooltipIn, final int dx, final int dy) {
return new RenderComponent(livingEntity -> DataAttributesAPI.ifPresent(livingEntity, attributeIn, LiteralText.EMPTY, functionIn), livingEntity -> DataAttributesAPI.ifPresent(livingEntity, attributeIn, new ArrayList<Text>(), tooltipIn), dx, dy);
}
private boolean isMouseOver(float xIn, float yIn, float widthIn, float heightIn, int mouseX, int mouseY) {
return mouseX >= (float)xIn && mouseY >= (float)yIn && mouseX < (float)(xIn + widthIn) && mouseY < (float)(yIn + heightIn);
}
/**
*
* @param livingEntity
* @param matrices
* @param textRenderer
* @param x
* @param y
* @param scaleX
* @param scaleY
*/
public void renderText(LivingEntity livingEntity, MatrixStack matrices, TextRenderer textRenderer, int x, int y, float scaleX, float scaleY) {
textRenderer.draw(matrices, this.text.apply(livingEntity), (x + this.dx) / scaleX, (y + this.dy) / scaleY, 4210752);
}
/**
*
* @param livingEntity
* @param consumer
* @param matrices
* @param textRenderer
* @param x
* @param y
* @param mouseX
* @param mouseY
* @param scaleX
* @param scaleY
*/
public void renderTooltip(LivingEntity livingEntity, RenderTooltip consumer, MatrixStack matrices, TextRenderer textRenderer, int x, int y, int mouseX, int mouseY, float scaleX, float scaleY) {
if(this.isMouseOver(x + this.dx, y + this.dy, textRenderer.getWidth(this.text.apply(livingEntity)) * scaleX, 7, mouseX, mouseY)) {
consumer.renderTooltip(matrices, this.tooltip.apply(livingEntity), mouseX, mouseY);
}
}
@FunctionalInterface
public interface RenderTooltip {
/**
*
* @param matrices
* @param tooltip
* @param mouseX
* @param mouseY
*/
void renderTooltip(MatrixStack matrices, List<Text> tooltip, int mouseX, int mouseY);
}
} | [
"@",
"Environment",
"(",
"EnvType",
".",
"CLIENT",
")",
"public",
"final",
"class",
"RenderComponent",
"{",
"private",
"final",
"Function",
"<",
"LivingEntity",
",",
"Text",
">",
"text",
";",
"private",
"final",
"Function",
"<",
"LivingEntity",
",",
"List",
"<",
"Text",
">",
">",
"tooltip",
";",
"private",
"final",
"int",
"dx",
",",
"dy",
";",
"private",
"RenderComponent",
"(",
"final",
"Function",
"<",
"LivingEntity",
",",
"Text",
">",
"functionIn",
",",
"final",
"Function",
"<",
"LivingEntity",
",",
"List",
"<",
"Text",
">",
">",
"tooltipIn",
",",
"final",
"int",
"dx",
",",
"final",
"int",
"dy",
")",
"{",
"this",
".",
"text",
"=",
"functionIn",
";",
"this",
".",
"tooltip",
"=",
"tooltipIn",
";",
"this",
".",
"dx",
"=",
"dx",
";",
"this",
".",
"dy",
"=",
"dy",
";",
"}",
"/**\n\t * \n\t * @param functionIn display text.\n\t * @param tooltipIn tooltip text.\n\t * @param dx x position\n\t * @param dy y position.\n\t * @return\n\t */",
"public",
"static",
"RenderComponent",
"of",
"(",
"final",
"Function",
"<",
"LivingEntity",
",",
"Text",
">",
"functionIn",
",",
"final",
"Function",
"<",
"LivingEntity",
",",
"List",
"<",
"Text",
">",
">",
"tooltipIn",
",",
"final",
"int",
"dx",
",",
"final",
"int",
"dy",
")",
"{",
"return",
"new",
"RenderComponent",
"(",
"functionIn",
",",
"tooltipIn",
",",
"dx",
",",
"dy",
")",
";",
"}",
"/**\n\t * \n\t * @param attributeIn the text (and therefore tooltip) only display if the player has this attribute and it is not null (i.e. registered to the game).\n\t * @param functionIn display text.\n\t * @param tooltipIn tooltip text.\n\t * @param dx x position\n\t * @param dy y position\n\t * @return\n\t */",
"public",
"static",
"RenderComponent",
"of",
"(",
"final",
"Supplier",
"<",
"EntityAttribute",
">",
"attributeIn",
",",
"final",
"Function",
"<",
"Float",
",",
"Text",
">",
"functionIn",
",",
"final",
"Function",
"<",
"Float",
",",
"List",
"<",
"Text",
">",
">",
"tooltipIn",
",",
"final",
"int",
"dx",
",",
"final",
"int",
"dy",
")",
"{",
"return",
"new",
"RenderComponent",
"(",
"livingEntity",
"->",
"DataAttributesAPI",
".",
"ifPresent",
"(",
"livingEntity",
",",
"attributeIn",
",",
"LiteralText",
".",
"EMPTY",
",",
"functionIn",
")",
",",
"livingEntity",
"->",
"DataAttributesAPI",
".",
"ifPresent",
"(",
"livingEntity",
",",
"attributeIn",
",",
"new",
"ArrayList",
"<",
"Text",
">",
"(",
")",
",",
"tooltipIn",
")",
",",
"dx",
",",
"dy",
")",
";",
"}",
"private",
"boolean",
"isMouseOver",
"(",
"float",
"xIn",
",",
"float",
"yIn",
",",
"float",
"widthIn",
",",
"float",
"heightIn",
",",
"int",
"mouseX",
",",
"int",
"mouseY",
")",
"{",
"return",
"mouseX",
">=",
"(",
"float",
")",
"xIn",
"&&",
"mouseY",
">=",
"(",
"float",
")",
"yIn",
"&&",
"mouseX",
"<",
"(",
"float",
")",
"(",
"xIn",
"+",
"widthIn",
")",
"&&",
"mouseY",
"<",
"(",
"float",
")",
"(",
"yIn",
"+",
"heightIn",
")",
";",
"}",
"/**\n\t * \n\t * @param livingEntity\n\t * @param matrices\n\t * @param textRenderer\n\t * @param x\n\t * @param y\n\t * @param scaleX\n\t * @param scaleY\n\t */",
"public",
"void",
"renderText",
"(",
"LivingEntity",
"livingEntity",
",",
"MatrixStack",
"matrices",
",",
"TextRenderer",
"textRenderer",
",",
"int",
"x",
",",
"int",
"y",
",",
"float",
"scaleX",
",",
"float",
"scaleY",
")",
"{",
"textRenderer",
".",
"draw",
"(",
"matrices",
",",
"this",
".",
"text",
".",
"apply",
"(",
"livingEntity",
")",
",",
"(",
"x",
"+",
"this",
".",
"dx",
")",
"/",
"scaleX",
",",
"(",
"y",
"+",
"this",
".",
"dy",
")",
"/",
"scaleY",
",",
"4210752",
")",
";",
"}",
"/**\n\t * \n\t * @param livingEntity\n\t * @param consumer\n\t * @param matrices\n\t * @param textRenderer\n\t * @param x\n\t * @param y\n\t * @param mouseX\n\t * @param mouseY\n\t * @param scaleX\n\t * @param scaleY\n\t */",
"public",
"void",
"renderTooltip",
"(",
"LivingEntity",
"livingEntity",
",",
"RenderTooltip",
"consumer",
",",
"MatrixStack",
"matrices",
",",
"TextRenderer",
"textRenderer",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"mouseX",
",",
"int",
"mouseY",
",",
"float",
"scaleX",
",",
"float",
"scaleY",
")",
"{",
"if",
"(",
"this",
".",
"isMouseOver",
"(",
"x",
"+",
"this",
".",
"dx",
",",
"y",
"+",
"this",
".",
"dy",
",",
"textRenderer",
".",
"getWidth",
"(",
"this",
".",
"text",
".",
"apply",
"(",
"livingEntity",
")",
")",
"*",
"scaleX",
",",
"7",
",",
"mouseX",
",",
"mouseY",
")",
")",
"{",
"consumer",
".",
"renderTooltip",
"(",
"matrices",
",",
"this",
".",
"tooltip",
".",
"apply",
"(",
"livingEntity",
")",
",",
"mouseX",
",",
"mouseY",
")",
";",
"}",
"}",
"@",
"FunctionalInterface",
"public",
"interface",
"RenderTooltip",
"{",
"/**\n\t\t * \n\t\t * @param matrices\n\t\t * @param tooltip\n\t\t * @param mouseX\n\t\t * @param mouseY\n\t\t */",
"void",
"renderTooltip",
"(",
"MatrixStack",
"matrices",
",",
"List",
"<",
"Text",
">",
"tooltip",
",",
"int",
"mouseX",
",",
"int",
"mouseY",
")",
";",
"}",
"}"
] | Utility wrapper object to allow static creation of lazily loaded text. | [
"Utility",
"wrapper",
"object",
"to",
"allow",
"static",
"creation",
"of",
"lazily",
"loaded",
"text",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd6fb8a1208f799f62fba67664bceafe93ad6757 | robinroos/ikasan | ikasaneip/test/src/test/java/org/ikasan/testharness/flow/expectation/service/UnorderedExpectationTest.java | [
"BSD-3-Clause"
] | Java | UnorderedExpectationTest | /**
* Tests for the <code>UnorderedExpectation</code> class.
*
* @author Ikasan Development Team
*/ | Tests for the UnorderedExpectation class.
@author Ikasan Development Team | [
"Tests",
"for",
"the",
"UnorderedExpectation",
"class",
".",
"@author",
"Ikasan",
"Development",
"Team"
] | public class UnorderedExpectationTest
{
private Mockery mockery = new Mockery()
{
{
setImposteriser(ClassImposteriser.INSTANCE);
setThreadingPolicy(new Synchroniser());
}
};
/**
* mocked capture
*/
private final Capture<?> capture = mockery.mock(Capture.class, "capture");
private final Capture<?> capture2 = mockery.mock(Capture.class, "capture2");
/**
* mocked flowElement
*/
private final FlowElement flowElement = mockery.mock(FlowElement.class, "flowElement");
private final FlowElement flowElement2 = mockery.mock(FlowElement.class, "flowElement2");
/**
* mocked comparatorService
*/
@SuppressWarnings("unchecked") private final ComparatorService comparatorService = mockery
.mock(ComparatorService.class, "ComparatorService");
/**
* mocked expectationComparator
**/
@SuppressWarnings("unchecked") private final ExpectationComparator expectationComparator = mockery
.mock(ExpectationComparator.class, "expectationComparator");
/**
* mocked expectation
*/
private final Object expectation = mockery.mock(Object.class, "ExpectationObject");
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation to be matched using the default description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleExpectationDefaultDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
// expected name
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"));
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with two
* expectations to be matched using the default description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithTwoExpectationsStandardOrdering()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
exactly(1).of(capture2).getActual();
will(returnValue(flowElement2));
// expected name
exactly(1).of(flowElement2).getComponentName();
will(returnValue("two"));
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new TestTranslator()));
// expected implementation class
exactly(2).of(flowElement2).getFlowComponent();
will(returnValue(new TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "one");
flowExpectation.expectation(new TranslatorComponent("two"), "two");
// test expectations satisfied
flowExpectation.allSatisfied(asList(capture, capture2));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with two
* expectations to be matched using the default description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithTwoExpectationsReversedOrdering()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
exactly(1).of(capture2).getActual();
will(returnValue(flowElement2));
// expected name
exactly(1).of(flowElement2).getComponentName();
will(returnValue("two"));
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new TestTranslator()));
// expected implementation class
exactly(2).of(flowElement2).getFlowComponent();
will(returnValue(new TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "one");
flowExpectation.expectation(new TranslatorComponent("two"), "two");
// test expectations satisfied
flowExpectation.allSatisfied(asList(capture, capture2));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation to be matched with a user defined description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleExpectationUserDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
// expected name
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "my test expectation description");
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation to be ignored with default description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleIgnoreExpectationDefaultDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.ignore(new TranslatorComponent("one"));
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation to be ignored with user description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleIgnoreExpectationUserDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.ignore(new TranslatorComponent("one"), "another description");
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation and a user specified comparator passed explicitly for that
* expectation. Use default expectation description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleExpectationAndUserComparatorDefaultDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue("one"));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation("one", new TestComparator());
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation and a user specified comparator passed explicitly for that
* expectation. Use User description.
*/
@Test
public void test_successfulDefaultUnorderedExpectationWithSingleExpectationAndUserComparatorUserDescription()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue("one"));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation("one", new TestComparator(), "another expectation description");
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Sanity test of an UnorderedExpectation instance with an alternate ComparatorService.
*/
@Test
public void test_successfulUnorderedExpectationWithAlternateComparatorService()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue("one"));
exactly(1).of(comparatorService).getComparator(with(any(Object.class)));
will(returnValue(expectationComparator));
exactly(1).of(expectationComparator).compare(with(any(Object.class)), with(any(Object.class)));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation(comparatorService);
flowExpectation.expectation(expectation);
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
@Test
public void test_successWhenNoCapturesOrExpectations()
{
FlowExpectation flowExpectation = new UnorderedExpectation();
// test expectations satisfied
flowExpectation.allSatisfied(emptyList());
mockery.assertIsSatisfied();
}
@Test(expected = AssertionError.class)
public void test_failWhenNoExpectationsButCaptures()
{
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
@Test(expected = AssertionError.class)
public void test_failsWhenNoCapturesButExpectations()
{
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.ignore(new TranslatorComponent("one"), "another description");
// test expectations satisfied
flowExpectation.allSatisfied(emptyList());
mockery.assertIsSatisfied();
}
@Test(expected = AssertionError.class)
public void test_failWhenMissingInvocation()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(1).of(capture).getActual();
will(returnValue(flowElement));
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new UnorderedExpectationTest.TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "one");
flowExpectation.expectation(new TranslatorComponent("two"), "two");
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
@Test(expected = AssertionError.class)
public void test_failWhenMissingExpectation()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(2).of(capture).getActual();
will(returnValue(flowElement));
exactly(3).of(capture2).getActual();
will(returnValue(flowElement2));
// expected name
exactly(2).of(flowElement2).getComponentName();
will(returnValue("two"));
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new UnorderedExpectationTest.TestTranslator()));
// expected implementation class
exactly(2).of(flowElement2).getFlowComponent();
will(returnValue(new UnorderedExpectationTest.TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "one");
// test expectations satisfied
flowExpectation.allSatisfied(asList(capture, capture2));
mockery.assertIsSatisfied();
}
@Test(expected = AssertionError.class)
public void test_failWhenMissingExpectationAndInvocation()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(2).of(capture).getActual();
will(returnValue(flowElement));
exactly(3).of(capture2).getActual();
will(returnValue(flowElement2));
// expected name
exactly(2).of(flowElement2).getComponentName();
will(returnValue("two"));
exactly(1).of(flowElement).getComponentName();
will(returnValue("one"));
// expected implementation class
exactly(2).of(flowElement).getFlowComponent();
will(returnValue(new UnorderedExpectationTest.TestTranslator()));
// expected implementation class
exactly(2).of(flowElement2).getFlowComponent();
will(returnValue(new UnorderedExpectationTest.TestTranslator()));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), "one");
flowExpectation.expectation(new TranslatorComponent("three"), "three");
// test expectations satisfied
flowExpectation.allSatisfied(asList(capture, capture2));
mockery.assertIsSatisfied();
}
/**
* Sanity test of a default UnorderedExpectation instance with a single
* expectation and a user specified comparator, but based on an incorrect
* class comparator parameter type resulting in a ClassCastException.
*/
@Test(expected = RuntimeException.class)
public void test_failedDefaultUnorderedExpectationWithClassCastException()
{
// expectations
mockery.checking(new Expectations()
{
{
// get the mocked actual flow element
exactly(3).of(capture).getActual();
will(returnValue(flowElement));
}
});
FlowExpectation flowExpectation = new UnorderedExpectation();
flowExpectation.expectation(new TranslatorComponent("one"), new TestComparator());
// test expectations satisfied
flowExpectation.allSatisfied(singletonList(capture));
mockery.assertIsSatisfied();
}
/**
* Simple implementation of a Transformer component for testing.
*
* @author Ikasan Development Team
*/
private class TestTranslator implements Translator<StringBuilder>
{
public void translate(StringBuilder payload) throws TransformationException
{
// do nothing
}
}
/**
* Simple implementation of a TestComparator for testing.
*
* @author Ikasan Development Team
*/
private class TestComparator implements ExpectationComparator<String, String>
{
public void compare(String expected, String actual)
{
Assert.assertEquals(expected, actual);
}
}
} | [
"public",
"class",
"UnorderedExpectationTest",
"{",
"private",
"Mockery",
"mockery",
"=",
"new",
"Mockery",
"(",
")",
"{",
"{",
"setImposteriser",
"(",
"ClassImposteriser",
".",
"INSTANCE",
")",
";",
"setThreadingPolicy",
"(",
"new",
"Synchroniser",
"(",
")",
")",
";",
"}",
"}",
";",
"/**\n * mocked capture\n */",
"private",
"final",
"Capture",
"<",
"?",
">",
"capture",
"=",
"mockery",
".",
"mock",
"(",
"Capture",
".",
"class",
",",
"\"",
"capture",
"\"",
")",
";",
"private",
"final",
"Capture",
"<",
"?",
">",
"capture2",
"=",
"mockery",
".",
"mock",
"(",
"Capture",
".",
"class",
",",
"\"",
"capture2",
"\"",
")",
";",
"/**\n * mocked flowElement\n */",
"private",
"final",
"FlowElement",
"flowElement",
"=",
"mockery",
".",
"mock",
"(",
"FlowElement",
".",
"class",
",",
"\"",
"flowElement",
"\"",
")",
";",
"private",
"final",
"FlowElement",
"flowElement2",
"=",
"mockery",
".",
"mock",
"(",
"FlowElement",
".",
"class",
",",
"\"",
"flowElement2",
"\"",
")",
";",
"/**\n * mocked comparatorService\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"private",
"final",
"ComparatorService",
"comparatorService",
"=",
"mockery",
".",
"mock",
"(",
"ComparatorService",
".",
"class",
",",
"\"",
"ComparatorService",
"\"",
")",
";",
"/**\n * mocked expectationComparator\n **/",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"private",
"final",
"ExpectationComparator",
"expectationComparator",
"=",
"mockery",
".",
"mock",
"(",
"ExpectationComparator",
".",
"class",
",",
"\"",
"expectationComparator",
"\"",
")",
";",
"/**\n * mocked expectation\n */",
"private",
"final",
"Object",
"expectation",
"=",
"mockery",
".",
"mock",
"(",
"Object",
".",
"class",
",",
"\"",
"ExpectationObject",
"\"",
")",
";",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation to be matched using the default description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleExpectationDefaultDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with two\n * expectations to be matched using the default description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithTwoExpectationsStandardOrdering",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture2",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement2",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"two",
"\"",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"one",
"\"",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"two",
"\"",
")",
",",
"\"",
"two",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"asList",
"(",
"capture",
",",
"capture2",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with two\n * expectations to be matched using the default description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithTwoExpectationsReversedOrdering",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture2",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement2",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"two",
"\"",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"one",
"\"",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"two",
"\"",
")",
",",
"\"",
"two",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"asList",
"(",
"capture",
",",
"capture2",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation to be matched with a user defined description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleExpectationUserDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"my test expectation description",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation to be ignored with default description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleIgnoreExpectationDefaultDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"ignore",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation to be ignored with user description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleIgnoreExpectationUserDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"ignore",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"another description",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation and a user specified comparator passed explicitly for that\n * expectation. Use default expectation description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleExpectationAndUserComparatorDefaultDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"\"",
"one",
"\"",
",",
"new",
"TestComparator",
"(",
")",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation and a user specified comparator passed explicitly for that\n * expectation. Use User description.\n */",
"@",
"Test",
"public",
"void",
"test_successfulDefaultUnorderedExpectationWithSingleExpectationAndUserComparatorUserDescription",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"\"",
"one",
"\"",
",",
"new",
"TestComparator",
"(",
")",
",",
"\"",
"another expectation description",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of an UnorderedExpectation instance with an alternate ComparatorService.\n */",
"@",
"Test",
"public",
"void",
"test_successfulUnorderedExpectationWithAlternateComparatorService",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"comparatorService",
")",
".",
"getComparator",
"(",
"with",
"(",
"any",
"(",
"Object",
".",
"class",
")",
")",
")",
";",
"will",
"(",
"returnValue",
"(",
"expectationComparator",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"expectationComparator",
")",
".",
"compare",
"(",
"with",
"(",
"any",
"(",
"Object",
".",
"class",
")",
")",
",",
"with",
"(",
"any",
"(",
"Object",
".",
"class",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
"comparatorService",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"expectation",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"test_successWhenNoCapturesOrExpectations",
"(",
")",
"{",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"emptyList",
"(",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"AssertionError",
".",
"class",
")",
"public",
"void",
"test_failWhenNoExpectationsButCaptures",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"AssertionError",
".",
"class",
")",
"public",
"void",
"test_failsWhenNoCapturesButExpectations",
"(",
")",
"{",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"ignore",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"another description",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"emptyList",
"(",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"AssertionError",
".",
"class",
")",
"public",
"void",
"test_failWhenMissingInvocation",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"UnorderedExpectationTest",
".",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"one",
"\"",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"two",
"\"",
")",
",",
"\"",
"two",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"AssertionError",
".",
"class",
")",
"public",
"void",
"test_failWhenMissingExpectation",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"3",
")",
".",
"of",
"(",
"capture2",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement2",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"two",
"\"",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"UnorderedExpectationTest",
".",
"TestTranslator",
"(",
")",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"UnorderedExpectationTest",
".",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"one",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"asList",
"(",
"capture",
",",
"capture2",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"AssertionError",
".",
"class",
")",
"public",
"void",
"test_failWhenMissingExpectationAndInvocation",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"exactly",
"(",
"3",
")",
".",
"of",
"(",
"capture2",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement2",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"two",
"\"",
")",
")",
";",
"exactly",
"(",
"1",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getComponentName",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"\"",
"one",
"\"",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"UnorderedExpectationTest",
".",
"TestTranslator",
"(",
")",
")",
")",
";",
"exactly",
"(",
"2",
")",
".",
"of",
"(",
"flowElement2",
")",
".",
"getFlowComponent",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"new",
"UnorderedExpectationTest",
".",
"TestTranslator",
"(",
")",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"\"",
"one",
"\"",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"three",
"\"",
")",
",",
"\"",
"three",
"\"",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"asList",
"(",
"capture",
",",
"capture2",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Sanity test of a default UnorderedExpectation instance with a single\n * expectation and a user specified comparator, but based on an incorrect\n * class comparator parameter type resulting in a ClassCastException.\n */",
"@",
"Test",
"(",
"expected",
"=",
"RuntimeException",
".",
"class",
")",
"public",
"void",
"test_failedDefaultUnorderedExpectationWithClassCastException",
"(",
")",
"{",
"mockery",
".",
"checking",
"(",
"new",
"Expectations",
"(",
")",
"{",
"{",
"exactly",
"(",
"3",
")",
".",
"of",
"(",
"capture",
")",
".",
"getActual",
"(",
")",
";",
"will",
"(",
"returnValue",
"(",
"flowElement",
")",
")",
";",
"}",
"}",
")",
";",
"FlowExpectation",
"flowExpectation",
"=",
"new",
"UnorderedExpectation",
"(",
")",
";",
"flowExpectation",
".",
"expectation",
"(",
"new",
"TranslatorComponent",
"(",
"\"",
"one",
"\"",
")",
",",
"new",
"TestComparator",
"(",
")",
")",
";",
"flowExpectation",
".",
"allSatisfied",
"(",
"singletonList",
"(",
"capture",
")",
")",
";",
"mockery",
".",
"assertIsSatisfied",
"(",
")",
";",
"}",
"/**\n * Simple implementation of a Transformer component for testing.\n *\n * @author Ikasan Development Team\n */",
"private",
"class",
"TestTranslator",
"implements",
"Translator",
"<",
"StringBuilder",
">",
"{",
"public",
"void",
"translate",
"(",
"StringBuilder",
"payload",
")",
"throws",
"TransformationException",
"{",
"}",
"}",
"/**\n * Simple implementation of a TestComparator for testing.\n *\n * @author Ikasan Development Team\n */",
"private",
"class",
"TestComparator",
"implements",
"ExpectationComparator",
"<",
"String",
",",
"String",
">",
"{",
"public",
"void",
"compare",
"(",
"String",
"expected",
",",
"String",
"actual",
")",
"{",
"Assert",
".",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"}",
"}"
] | Tests for the <code>UnorderedExpectation</code> class. | [
"Tests",
"for",
"the",
"<code",
">",
"UnorderedExpectation<",
"/",
"code",
">",
"class",
"."
] | [
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// test expectations satisfied",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// expected name",
"// expected implementation class",
"// expected implementation class",
"// test expectations satisfied",
"// expectations",
"// get the mocked actual flow element",
"// test expectations satisfied",
"// do nothing"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
cd6fb8a1208f799f62fba67664bceafe93ad6757 | robinroos/ikasan | ikasaneip/test/src/test/java/org/ikasan/testharness/flow/expectation/service/UnorderedExpectationTest.java | [
"BSD-3-Clause"
] | Java | TestTranslator | /**
* Simple implementation of a Transformer component for testing.
*
* @author Ikasan Development Team
*/ | Simple implementation of a Transformer component for testing.
@author Ikasan Development Team | [
"Simple",
"implementation",
"of",
"a",
"Transformer",
"component",
"for",
"testing",
".",
"@author",
"Ikasan",
"Development",
"Team"
] | private class TestTranslator implements Translator<StringBuilder>
{
public void translate(StringBuilder payload) throws TransformationException
{
// do nothing
}
} | [
"private",
"class",
"TestTranslator",
"implements",
"Translator",
"<",
"StringBuilder",
">",
"{",
"public",
"void",
"translate",
"(",
"StringBuilder",
"payload",
")",
"throws",
"TransformationException",
"{",
"}",
"}"
] | Simple implementation of a Transformer component for testing. | [
"Simple",
"implementation",
"of",
"a",
"Transformer",
"component",
"for",
"testing",
"."
] | [
"// do nothing"
] | [
{
"param": "Translator<StringBuilder>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Translator<StringBuilder>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cd6fb8a1208f799f62fba67664bceafe93ad6757 | robinroos/ikasan | ikasaneip/test/src/test/java/org/ikasan/testharness/flow/expectation/service/UnorderedExpectationTest.java | [
"BSD-3-Clause"
] | Java | TestComparator | /**
* Simple implementation of a TestComparator for testing.
*
* @author Ikasan Development Team
*/ | Simple implementation of a TestComparator for testing.
@author Ikasan Development Team | [
"Simple",
"implementation",
"of",
"a",
"TestComparator",
"for",
"testing",
".",
"@author",
"Ikasan",
"Development",
"Team"
] | private class TestComparator implements ExpectationComparator<String, String>
{
public void compare(String expected, String actual)
{
Assert.assertEquals(expected, actual);
}
} | [
"private",
"class",
"TestComparator",
"implements",
"ExpectationComparator",
"<",
"String",
",",
"String",
">",
"{",
"public",
"void",
"compare",
"(",
"String",
"expected",
",",
"String",
"actual",
")",
"{",
"Assert",
".",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"}"
] | Simple implementation of a TestComparator for testing. | [
"Simple",
"implementation",
"of",
"a",
"TestComparator",
"for",
"testing",
"."
] | [] | [
{
"param": "ExpectationComparator<String, String>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ExpectationComparator<String, String>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
332fcf596e7c02057b23366aba4411682d2d45b0 | lyj729047457/Rust_node_test_harness | TestHarness/src/org/aion/harness/result/Result.java | [
"MIT"
] | Java | Result | /**
* A basic result that is either successful or unsuccessful.
*
* If unsuccessful, then this result will hold a String with an error message.
*
* If successful, then the error string is meaningless and possibly null.
*
* There is not a concept of equality defined for a result.
*
* A result is immutable.
*/ | A basic result that is either successful or unsuccessful.
If unsuccessful, then this result will hold a String with an error message.
If successful, then the error string is meaningless and possibly null.
There is not a concept of equality defined for a result.
A result is immutable. | [
"A",
"basic",
"result",
"that",
"is",
"either",
"successful",
"or",
"unsuccessful",
".",
"If",
"unsuccessful",
"then",
"this",
"result",
"will",
"hold",
"a",
"String",
"with",
"an",
"error",
"message",
".",
"If",
"successful",
"then",
"the",
"error",
"string",
"is",
"meaningless",
"and",
"possibly",
"null",
".",
"There",
"is",
"not",
"a",
"concept",
"of",
"equality",
"defined",
"for",
"a",
"result",
".",
"A",
"result",
"is",
"immutable",
"."
] | public final class Result {
private final boolean success;
private final String error;
private Result(boolean success, String error) {
this.success = success;
this.error = error;
}
public static Result successful() {
return new Result(true, null);
}
public static Result unsuccessfulDueTo(String error) {
if (error == null) {
throw new NullPointerException("Cannot create result with null error.");
}
return new Result(false, error);
}
/**
* Returns {@code true} only if the event represented by this result was successful.
*
* @return whether or not the event was successful or not.
*/
public boolean isSuccess() {
return this.success;
}
/**
* Returns the error if one exists.
*
* @return The error.
*/
public String getError() {
return this.error;
}
@Override
public String toString() {
if (this.success) {
return "Result { successful }";
} else {
return "Result { unsuccessful due to: " + this.error + " }";
}
}
} | [
"public",
"final",
"class",
"Result",
"{",
"private",
"final",
"boolean",
"success",
";",
"private",
"final",
"String",
"error",
";",
"private",
"Result",
"(",
"boolean",
"success",
",",
"String",
"error",
")",
"{",
"this",
".",
"success",
"=",
"success",
";",
"this",
".",
"error",
"=",
"error",
";",
"}",
"public",
"static",
"Result",
"successful",
"(",
")",
"{",
"return",
"new",
"Result",
"(",
"true",
",",
"null",
")",
";",
"}",
"public",
"static",
"Result",
"unsuccessfulDueTo",
"(",
"String",
"error",
")",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"",
"Cannot create result with null error.",
"\"",
")",
";",
"}",
"return",
"new",
"Result",
"(",
"false",
",",
"error",
")",
";",
"}",
"/**\n * Returns {@code true} only if the event represented by this result was successful.\n *\n * @return whether or not the event was successful or not.\n */",
"public",
"boolean",
"isSuccess",
"(",
")",
"{",
"return",
"this",
".",
"success",
";",
"}",
"/**\n * Returns the error if one exists.\n *\n * @return The error.\n */",
"public",
"String",
"getError",
"(",
")",
"{",
"return",
"this",
".",
"error",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"if",
"(",
"this",
".",
"success",
")",
"{",
"return",
"\"",
"Result { successful }",
"\"",
";",
"}",
"else",
"{",
"return",
"\"",
"Result { unsuccessful due to: ",
"\"",
"+",
"this",
".",
"error",
"+",
"\"",
" }",
"\"",
";",
"}",
"}",
"}"
] | A basic result that is either successful or unsuccessful. | [
"A",
"basic",
"result",
"that",
"is",
"either",
"successful",
"or",
"unsuccessful",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
33303b8bc1db0ea2215a2920cb06b01a551dee24 | PhongNgo/OptimalVerifiedFT | benchmarks/JaConTeBe/versions.alt/log4j2/orig/com/a/AnObject.java | [
"BSD-3-Clause"
] | Java | AnObject | /**
*
* @author Marcelo S. Miashiro (marc_sm2003@yahoo.com.br)
*/ | @author Marcelo S. | [
"@author",
"Marcelo",
"S",
"."
] | public class AnObject {
private static final Logger LOGGER = Logger.getLogger(AnObject.class);
private final String name;
public AnObject(String name) {
this.name = name;
}
@Override
public String toString() {
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
LOGGER.info("Logging DEBUG in AnObject [" + name + "]");
return name;
}
} | [
"public",
"class",
"AnObject",
"{",
"private",
"static",
"final",
"Logger",
"LOGGER",
"=",
"Logger",
".",
"getLogger",
"(",
"AnObject",
".",
"class",
")",
";",
"private",
"final",
"String",
"name",
";",
"public",
"AnObject",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"4000",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ex",
")",
"{",
"ex",
".",
"printStackTrace",
"(",
")",
";",
"}",
"LOGGER",
".",
"info",
"(",
"\"",
"Logging DEBUG in AnObject [",
"\"",
"+",
"name",
"+",
"\"",
"]",
"\"",
")",
";",
"return",
"name",
";",
"}",
"}"
] | @author Marcelo S. Miashiro (marc_sm2003@yahoo.com.br) | [
"@author",
"Marcelo",
"S",
".",
"Miashiro",
"(",
"marc_sm2003@yahoo",
".",
"com",
".",
"br",
")"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
33322c5d2db975b0584156d50240d4a84ef610b3 | jestevez/portfolio-trusts-funds | gpff-commons/src/main/java/ve/com/sios/gpff/message/WCREPAIAMessage.java | [
"Apache-2.0"
] | Java | WCREPAIAMessage | /**
* Class generated by AS/400 CRTCLASS command from WCREPAIA physical file definition.
*
* File level identifier is 1130103155649.
*
* Mantenimiento de Codigos de Paises
*
* Record format level identifier is 3CF59CECD6122.
*/ | Class generated by AS/400 CRTCLASS command from WCREPAIA physical file definition.
Mantenimiento de Codigos de Paises
Record format level identifier is 3CF59CECD6122. | [
"Class",
"generated",
"by",
"AS",
"/",
"400",
"CRTCLASS",
"command",
"from",
"WCREPAIA",
"physical",
"file",
"definition",
".",
"Mantenimiento",
"de",
"Codigos",
"de",
"Paises",
"Record",
"format",
"level",
"identifier",
"is",
"3CF59CECD6122",
"."
] | public class WCREPAIAMessage extends MessageRecord
{
/*
HPGM CHAR 10 10 1 Ambos PROG. A EJEC.
HDAT PACKED 6 0 4 11 Ambos FECHA DE EJEC.
HTIM PACKED 6 0 4 15 Ambos HORA DE EJEC.
HUSR CHAR 10 10 19 Ambos USUARIO EJEC.
HENV CHAR 1 1 29 Ambos ENVIOS
HPRO CHAR 4 4 30 Ambos COD. PROCESO
HRIN PACKED 5 0 3 34 Ambos REG. INICIAL
HNRE PACKED 3 0 2 37 Ambos NUM. REG A ENVIAR
HRRL PACKED 8 0 5 39 Ambos REG. RELATIVO
HTOT PACKED 7 0 4 44 Ambos TOT. REGISTRO
HFLI CHAR 1 1 48 Ambos FLAG INICIAL
HAREA CHAR 4 4 49 Ambos CODIGO DE AREA
EFLG0 CHAR 1 1 53 Ambos FLAG DE ERROR
EDSC0 CHAR 500 500 54 Ambos ERRORES
PAICLA ZONED 15 0 15 554 Ambos CLAVE DE GRUPO
PAINOM CHAR 40 40 569 Ambos DESCRIPCION
PAICTR ZONED 2 0 2 609 Ambos CLAVE DE FESTIVO
*/
final static String fldnames[] = {
"HPGM",
"HDAT",
"HTIM",
"HUSR",
"HENV",
"HPRO",
"HRIN",
"HNRE",
"HRRL",
"HTOT",
"HFLI",
"HAREA",
"EFLG0",
"EDSC0",
"PAICLA",
"PAINOM",
"PAICTR"
};
final static String tnames[] = {
"HPGM",
"HDAT",
"HTIM",
"HUSR",
"HENV",
"HPRO",
"HRIN",
"HNRE",
"HRRL",
"HTOT",
"HFLI",
"HAREA",
"EFLG0",
"EDSC0",
"PAICLA",
"PAINOM",
"PAICTR"
};
final static String fid = "1130103155649";
final static String rid = "3CF59CECD6122";
final static String fmtname = "WCREPAIA";
final int FIELDCOUNT = 17;
private static Hashtable tlookup = new Hashtable();
private CharacterField fieldHPGM = null;
private DecimalField fieldHDAT = null;
private DecimalField fieldHTIM = null;
private CharacterField fieldHUSR = null;
private CharacterField fieldHENV = null;
private CharacterField fieldHPRO = null;
private DecimalField fieldHRIN = null;
private DecimalField fieldHNRE = null;
private DecimalField fieldHRRL = null;
private DecimalField fieldHTOT = null;
private CharacterField fieldHFLI = null;
private CharacterField fieldHAREA = null;
private CharacterField fieldEFLG0 = null;
private CharacterField fieldEDSC0 = null;
private DecimalField fieldPAICLA = null;
private CharacterField fieldPAINOM = null;
private DecimalField fieldPAICTR = null;
/**
* Constructor for WCREPAIAMessage.
*/
public WCREPAIAMessage()
{
createFields();
initialize();
}
/**
* Create fields for this message.
* This method implements the abstract method in the MessageRecord superclass.
*/
protected void createFields()
{
recordsize = 631;
fileid = fid;
recordid = rid;
message = new byte[getByteLength()];
formatname = fmtname;
fieldnames = fldnames;
tagnames = tnames;
fields = new MessageField[FIELDCOUNT];
fields[0] = fieldHPGM =
new CharacterField(message, HEADERSIZE + 0, 10, "HPGM");
fields[1] = fieldHDAT =
new DecimalField(message, HEADERSIZE + 10, 7, 0, "HDAT");
fields[2] = fieldHTIM =
new DecimalField(message, HEADERSIZE + 17, 7, 0, "HTIM");
fields[3] = fieldHUSR =
new CharacterField(message, HEADERSIZE + 24, 10, "HUSR");
fields[4] = fieldHENV =
new CharacterField(message, HEADERSIZE + 34, 1, "HENV");
fields[5] = fieldHPRO =
new CharacterField(message, HEADERSIZE + 35, 4, "HPRO");
fields[6] = fieldHRIN =
new DecimalField(message, HEADERSIZE + 39, 6, 0, "HRIN");
fields[7] = fieldHNRE =
new DecimalField(message, HEADERSIZE + 45, 4, 0, "HNRE");
fields[8] = fieldHRRL =
new DecimalField(message, HEADERSIZE + 49, 9, 0, "HRRL");
fields[9] = fieldHTOT =
new DecimalField(message, HEADERSIZE + 58, 8, 0, "HTOT");
fields[10] = fieldHFLI =
new CharacterField(message, HEADERSIZE + 66, 1, "HFLI");
fields[11] = fieldHAREA =
new CharacterField(message, HEADERSIZE + 67, 4, "HAREA");
fields[12] = fieldEFLG0 =
new CharacterField(message, HEADERSIZE + 71, 1, "EFLG0");
fields[13] = fieldEDSC0 =
new CharacterField(message, HEADERSIZE + 72, 500, "EDSC0");
fields[14] = fieldPAICLA =
new DecimalField(message, HEADERSIZE + 572, 16, 0, "PAICLA");
fields[15] = fieldPAINOM =
new CharacterField(message, HEADERSIZE + 588, 40, "PAINOM");
fields[16] = fieldPAICTR =
new DecimalField(message, HEADERSIZE + 628, 3, 0, "PAICTR");
synchronized (tlookup)
{
if (tlookup.isEmpty())
{
for (int i = 0; i < tnames.length; i++)
tlookup.put(tnames[i], new Integer(i));
}
}
taglookup = tlookup;
}
/**
* Set field HPGM using a String value.
*/
public void setHPGM(String newvalue)
{
fieldHPGM.setString(newvalue);
}
/**
* Get value of field HPGM as a String.
*/
public String getHPGM()
{
return fieldHPGM.getString();
}
/**
* Set field HDAT using a String value.
*/
public void setHDAT(String newvalue)
{
fieldHDAT.setString(newvalue);
}
/**
* Get value of field HDAT as a String.
*/
public String getHDAT()
{
return fieldHDAT.getString();
}
/**
* Set numeric field HDAT using a BigDecimal value.
*/
public void setHDAT(BigDecimal newvalue)
{
fieldHDAT.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HDAT as a BigDecimal.
*/
public BigDecimal getBigDecimalHDAT()
{
return fieldHDAT.getBigDecimal();
}
/**
* Set field HTIM using a String value.
*/
public void setHTIM(String newvalue)
{
fieldHTIM.setString(newvalue);
}
/**
* Get value of field HTIM as a String.
*/
public String getHTIM()
{
return fieldHTIM.getString();
}
/**
* Set numeric field HTIM using a BigDecimal value.
*/
public void setHTIM(BigDecimal newvalue)
{
fieldHTIM.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HTIM as a BigDecimal.
*/
public BigDecimal getBigDecimalHTIM()
{
return fieldHTIM.getBigDecimal();
}
/**
* Set field HUSR using a String value.
*/
public void setHUSR(String newvalue)
{
fieldHUSR.setString(newvalue);
}
/**
* Get value of field HUSR as a String.
*/
public String getHUSR()
{
return fieldHUSR.getString();
}
/**
* Set field HENV using a String value.
*/
public void setHENV(String newvalue)
{
fieldHENV.setString(newvalue);
}
/**
* Get value of field HENV as a String.
*/
public String getHENV()
{
return fieldHENV.getString();
}
/**
* Set field HPRO using a String value.
*/
public void setHPRO(String newvalue)
{
fieldHPRO.setString(newvalue);
}
/**
* Get value of field HPRO as a String.
*/
public String getHPRO()
{
return fieldHPRO.getString();
}
/**
* Set field HRIN using a String value.
*/
public void setHRIN(String newvalue)
{
fieldHRIN.setString(newvalue);
}
/**
* Get value of field HRIN as a String.
*/
public String getHRIN()
{
return fieldHRIN.getString();
}
/**
* Set numeric field HRIN using a BigDecimal value.
*/
public void setHRIN(BigDecimal newvalue)
{
fieldHRIN.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HRIN as a BigDecimal.
*/
public BigDecimal getBigDecimalHRIN()
{
return fieldHRIN.getBigDecimal();
}
/**
* Set field HNRE using a String value.
*/
public void setHNRE(String newvalue)
{
fieldHNRE.setString(newvalue);
}
/**
* Get value of field HNRE as a String.
*/
public String getHNRE()
{
return fieldHNRE.getString();
}
/**
* Set numeric field HNRE using a BigDecimal value.
*/
public void setHNRE(BigDecimal newvalue)
{
fieldHNRE.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HNRE as a BigDecimal.
*/
public BigDecimal getBigDecimalHNRE()
{
return fieldHNRE.getBigDecimal();
}
/**
* Set field HRRL using a String value.
*/
public void setHRRL(String newvalue)
{
fieldHRRL.setString(newvalue);
}
/**
* Get value of field HRRL as a String.
*/
public String getHRRL()
{
return fieldHRRL.getString();
}
/**
* Set numeric field HRRL using a BigDecimal value.
*/
public void setHRRL(BigDecimal newvalue)
{
fieldHRRL.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HRRL as a BigDecimal.
*/
public BigDecimal getBigDecimalHRRL()
{
return fieldHRRL.getBigDecimal();
}
/**
* Set field HTOT using a String value.
*/
public void setHTOT(String newvalue)
{
fieldHTOT.setString(newvalue);
}
/**
* Get value of field HTOT as a String.
*/
public String getHTOT()
{
return fieldHTOT.getString();
}
/**
* Set numeric field HTOT using a BigDecimal value.
*/
public void setHTOT(BigDecimal newvalue)
{
fieldHTOT.setBigDecimal(newvalue);
}
/**
* Return value of numeric field HTOT as a BigDecimal.
*/
public BigDecimal getBigDecimalHTOT()
{
return fieldHTOT.getBigDecimal();
}
/**
* Set field HFLI using a String value.
*/
public void setHFLI(String newvalue)
{
fieldHFLI.setString(newvalue);
}
/**
* Get value of field HFLI as a String.
*/
public String getHFLI()
{
return fieldHFLI.getString();
}
/**
* Set field HAREA using a String value.
*/
public void setHAREA(String newvalue)
{
fieldHAREA.setString(newvalue);
}
/**
* Get value of field HAREA as a String.
*/
public String getHAREA()
{
return fieldHAREA.getString();
}
/**
* Set field EFLG0 using a String value.
*/
public void setEFLG0(String newvalue)
{
fieldEFLG0.setString(newvalue);
}
/**
* Get value of field EFLG0 as a String.
*/
public String getEFLG0()
{
return fieldEFLG0.getString();
}
/**
* Set field EDSC0 using a String value.
*/
public void setEDSC0(String newvalue)
{
fieldEDSC0.setString(newvalue);
}
/**
* Get value of field EDSC0 as a String.
*/
public String getEDSC0()
{
return fieldEDSC0.getString();
}
/**
* Set field PAICLA using a String value.
*/
public void setPAICLA(String newvalue)
{
fieldPAICLA.setString(newvalue);
}
/**
* Get value of field PAICLA as a String.
*/
public String getPAICLA()
{
return fieldPAICLA.getString();
}
/**
* Set numeric field PAICLA using a BigDecimal value.
*/
public void setPAICLA(BigDecimal newvalue)
{
fieldPAICLA.setBigDecimal(newvalue);
}
/**
* Return value of numeric field PAICLA as a BigDecimal.
*/
public BigDecimal getBigDecimalPAICLA()
{
return fieldPAICLA.getBigDecimal();
}
/**
* Set field PAINOM using a String value.
*/
public void setPAINOM(String newvalue)
{
fieldPAINOM.setString(newvalue);
}
/**
* Get value of field PAINOM as a String.
*/
public String getPAINOM()
{
return fieldPAINOM.getString();
}
/**
* Set field PAICTR using a String value.
*/
public void setPAICTR(String newvalue)
{
fieldPAICTR.setString(newvalue);
}
/**
* Get value of field PAICTR as a String.
*/
public String getPAICTR()
{
return fieldPAICTR.getString();
}
/**
* Set numeric field PAICTR using a BigDecimal value.
*/
public void setPAICTR(BigDecimal newvalue)
{
fieldPAICTR.setBigDecimal(newvalue);
}
/**
* Return value of numeric field PAICTR as a BigDecimal.
*/
public BigDecimal getBigDecimalPAICTR()
{
return fieldPAICTR.getBigDecimal();
}
} | [
"public",
"class",
"WCREPAIAMessage",
"extends",
"MessageRecord",
"{",
"/*\nHPGM CHAR 10 10 1 Ambos PROG. A EJEC.\nHDAT PACKED 6 0 4 11 Ambos FECHA DE EJEC.\nHTIM PACKED 6 0 4 15 Ambos HORA DE EJEC.\nHUSR CHAR 10 10 19 Ambos USUARIO EJEC.\nHENV CHAR 1 1 29 Ambos ENVIOS\nHPRO CHAR 4 4 30 Ambos COD. PROCESO\nHRIN PACKED 5 0 3 34 Ambos REG. INICIAL \nHNRE PACKED 3 0 2 37 Ambos NUM. REG A ENVIAR\nHRRL PACKED 8 0 5 39 Ambos REG. RELATIVO\nHTOT PACKED 7 0 4 44 Ambos TOT. REGISTRO\nHFLI CHAR 1 1 48 Ambos FLAG INICIAL\nHAREA CHAR 4 4 49 Ambos CODIGO DE AREA\nEFLG0 CHAR 1 1 53 Ambos FLAG DE ERROR\nEDSC0 CHAR 500 500 54 Ambos ERRORES\nPAICLA ZONED 15 0 15 554 Ambos CLAVE DE GRUPO\nPAINOM CHAR 40 40 569 Ambos DESCRIPCION\nPAICTR ZONED 2 0 2 609 Ambos CLAVE DE FESTIVO\n*/",
"final",
"static",
"String",
"fldnames",
"[",
"]",
"=",
"{",
"\"",
"HPGM",
"\"",
",",
"\"",
"HDAT",
"\"",
",",
"\"",
"HTIM",
"\"",
",",
"\"",
"HUSR",
"\"",
",",
"\"",
"HENV",
"\"",
",",
"\"",
"HPRO",
"\"",
",",
"\"",
"HRIN",
"\"",
",",
"\"",
"HNRE",
"\"",
",",
"\"",
"HRRL",
"\"",
",",
"\"",
"HTOT",
"\"",
",",
"\"",
"HFLI",
"\"",
",",
"\"",
"HAREA",
"\"",
",",
"\"",
"EFLG0",
"\"",
",",
"\"",
"EDSC0",
"\"",
",",
"\"",
"PAICLA",
"\"",
",",
"\"",
"PAINOM",
"\"",
",",
"\"",
"PAICTR",
"\"",
"}",
";",
"final",
"static",
"String",
"tnames",
"[",
"]",
"=",
"{",
"\"",
"HPGM",
"\"",
",",
"\"",
"HDAT",
"\"",
",",
"\"",
"HTIM",
"\"",
",",
"\"",
"HUSR",
"\"",
",",
"\"",
"HENV",
"\"",
",",
"\"",
"HPRO",
"\"",
",",
"\"",
"HRIN",
"\"",
",",
"\"",
"HNRE",
"\"",
",",
"\"",
"HRRL",
"\"",
",",
"\"",
"HTOT",
"\"",
",",
"\"",
"HFLI",
"\"",
",",
"\"",
"HAREA",
"\"",
",",
"\"",
"EFLG0",
"\"",
",",
"\"",
"EDSC0",
"\"",
",",
"\"",
"PAICLA",
"\"",
",",
"\"",
"PAINOM",
"\"",
",",
"\"",
"PAICTR",
"\"",
"}",
";",
"final",
"static",
"String",
"fid",
"=",
"\"",
"1130103155649",
"\"",
";",
"final",
"static",
"String",
"rid",
"=",
"\"",
"3CF59CECD6122",
"\"",
";",
"final",
"static",
"String",
"fmtname",
"=",
"\"",
"WCREPAIA",
"\"",
";",
"final",
"int",
"FIELDCOUNT",
"=",
"17",
";",
"private",
"static",
"Hashtable",
"tlookup",
"=",
"new",
"Hashtable",
"(",
")",
";",
"private",
"CharacterField",
"fieldHPGM",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHDAT",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHTIM",
"=",
"null",
";",
"private",
"CharacterField",
"fieldHUSR",
"=",
"null",
";",
"private",
"CharacterField",
"fieldHENV",
"=",
"null",
";",
"private",
"CharacterField",
"fieldHPRO",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHRIN",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHNRE",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHRRL",
"=",
"null",
";",
"private",
"DecimalField",
"fieldHTOT",
"=",
"null",
";",
"private",
"CharacterField",
"fieldHFLI",
"=",
"null",
";",
"private",
"CharacterField",
"fieldHAREA",
"=",
"null",
";",
"private",
"CharacterField",
"fieldEFLG0",
"=",
"null",
";",
"private",
"CharacterField",
"fieldEDSC0",
"=",
"null",
";",
"private",
"DecimalField",
"fieldPAICLA",
"=",
"null",
";",
"private",
"CharacterField",
"fieldPAINOM",
"=",
"null",
";",
"private",
"DecimalField",
"fieldPAICTR",
"=",
"null",
";",
"/**\n * Constructor for WCREPAIAMessage.\n */",
"public",
"WCREPAIAMessage",
"(",
")",
"{",
"createFields",
"(",
")",
";",
"initialize",
"(",
")",
";",
"}",
"/**\n * Create fields for this message.\n * This method implements the abstract method in the MessageRecord superclass.\n */",
"protected",
"void",
"createFields",
"(",
")",
"{",
"recordsize",
"=",
"631",
";",
"fileid",
"=",
"fid",
";",
"recordid",
"=",
"rid",
";",
"message",
"=",
"new",
"byte",
"[",
"getByteLength",
"(",
")",
"]",
";",
"formatname",
"=",
"fmtname",
";",
"fieldnames",
"=",
"fldnames",
";",
"tagnames",
"=",
"tnames",
";",
"fields",
"=",
"new",
"MessageField",
"[",
"FIELDCOUNT",
"]",
";",
"fields",
"[",
"0",
"]",
"=",
"fieldHPGM",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"0",
",",
"10",
",",
"\"",
"HPGM",
"\"",
")",
";",
"fields",
"[",
"1",
"]",
"=",
"fieldHDAT",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"10",
",",
"7",
",",
"0",
",",
"\"",
"HDAT",
"\"",
")",
";",
"fields",
"[",
"2",
"]",
"=",
"fieldHTIM",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"17",
",",
"7",
",",
"0",
",",
"\"",
"HTIM",
"\"",
")",
";",
"fields",
"[",
"3",
"]",
"=",
"fieldHUSR",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"24",
",",
"10",
",",
"\"",
"HUSR",
"\"",
")",
";",
"fields",
"[",
"4",
"]",
"=",
"fieldHENV",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"34",
",",
"1",
",",
"\"",
"HENV",
"\"",
")",
";",
"fields",
"[",
"5",
"]",
"=",
"fieldHPRO",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"35",
",",
"4",
",",
"\"",
"HPRO",
"\"",
")",
";",
"fields",
"[",
"6",
"]",
"=",
"fieldHRIN",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"39",
",",
"6",
",",
"0",
",",
"\"",
"HRIN",
"\"",
")",
";",
"fields",
"[",
"7",
"]",
"=",
"fieldHNRE",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"45",
",",
"4",
",",
"0",
",",
"\"",
"HNRE",
"\"",
")",
";",
"fields",
"[",
"8",
"]",
"=",
"fieldHRRL",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"49",
",",
"9",
",",
"0",
",",
"\"",
"HRRL",
"\"",
")",
";",
"fields",
"[",
"9",
"]",
"=",
"fieldHTOT",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"58",
",",
"8",
",",
"0",
",",
"\"",
"HTOT",
"\"",
")",
";",
"fields",
"[",
"10",
"]",
"=",
"fieldHFLI",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"66",
",",
"1",
",",
"\"",
"HFLI",
"\"",
")",
";",
"fields",
"[",
"11",
"]",
"=",
"fieldHAREA",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"67",
",",
"4",
",",
"\"",
"HAREA",
"\"",
")",
";",
"fields",
"[",
"12",
"]",
"=",
"fieldEFLG0",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"71",
",",
"1",
",",
"\"",
"EFLG0",
"\"",
")",
";",
"fields",
"[",
"13",
"]",
"=",
"fieldEDSC0",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"72",
",",
"500",
",",
"\"",
"EDSC0",
"\"",
")",
";",
"fields",
"[",
"14",
"]",
"=",
"fieldPAICLA",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"572",
",",
"16",
",",
"0",
",",
"\"",
"PAICLA",
"\"",
")",
";",
"fields",
"[",
"15",
"]",
"=",
"fieldPAINOM",
"=",
"new",
"CharacterField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"588",
",",
"40",
",",
"\"",
"PAINOM",
"\"",
")",
";",
"fields",
"[",
"16",
"]",
"=",
"fieldPAICTR",
"=",
"new",
"DecimalField",
"(",
"message",
",",
"HEADERSIZE",
"+",
"628",
",",
"3",
",",
"0",
",",
"\"",
"PAICTR",
"\"",
")",
";",
"synchronized",
"(",
"tlookup",
")",
"{",
"if",
"(",
"tlookup",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"tnames",
".",
"length",
";",
"i",
"++",
")",
"tlookup",
".",
"put",
"(",
"tnames",
"[",
"i",
"]",
",",
"new",
"Integer",
"(",
"i",
")",
")",
";",
"}",
"}",
"taglookup",
"=",
"tlookup",
";",
"}",
"/**\n * Set field HPGM using a String value.\n */",
"public",
"void",
"setHPGM",
"(",
"String",
"newvalue",
")",
"{",
"fieldHPGM",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HPGM as a String.\n */",
"public",
"String",
"getHPGM",
"(",
")",
"{",
"return",
"fieldHPGM",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field HDAT using a String value.\n */",
"public",
"void",
"setHDAT",
"(",
"String",
"newvalue",
")",
"{",
"fieldHDAT",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HDAT as a String.\n */",
"public",
"String",
"getHDAT",
"(",
")",
"{",
"return",
"fieldHDAT",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HDAT using a BigDecimal value.\n */",
"public",
"void",
"setHDAT",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHDAT",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HDAT as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHDAT",
"(",
")",
"{",
"return",
"fieldHDAT",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HTIM using a String value.\n */",
"public",
"void",
"setHTIM",
"(",
"String",
"newvalue",
")",
"{",
"fieldHTIM",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HTIM as a String.\n */",
"public",
"String",
"getHTIM",
"(",
")",
"{",
"return",
"fieldHTIM",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HTIM using a BigDecimal value.\n */",
"public",
"void",
"setHTIM",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHTIM",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HTIM as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHTIM",
"(",
")",
"{",
"return",
"fieldHTIM",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HUSR using a String value.\n */",
"public",
"void",
"setHUSR",
"(",
"String",
"newvalue",
")",
"{",
"fieldHUSR",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HUSR as a String.\n */",
"public",
"String",
"getHUSR",
"(",
")",
"{",
"return",
"fieldHUSR",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field HENV using a String value.\n */",
"public",
"void",
"setHENV",
"(",
"String",
"newvalue",
")",
"{",
"fieldHENV",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HENV as a String.\n */",
"public",
"String",
"getHENV",
"(",
")",
"{",
"return",
"fieldHENV",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field HPRO using a String value.\n */",
"public",
"void",
"setHPRO",
"(",
"String",
"newvalue",
")",
"{",
"fieldHPRO",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HPRO as a String.\n */",
"public",
"String",
"getHPRO",
"(",
")",
"{",
"return",
"fieldHPRO",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field HRIN using a String value.\n */",
"public",
"void",
"setHRIN",
"(",
"String",
"newvalue",
")",
"{",
"fieldHRIN",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HRIN as a String.\n */",
"public",
"String",
"getHRIN",
"(",
")",
"{",
"return",
"fieldHRIN",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HRIN using a BigDecimal value.\n */",
"public",
"void",
"setHRIN",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHRIN",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HRIN as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHRIN",
"(",
")",
"{",
"return",
"fieldHRIN",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HNRE using a String value.\n */",
"public",
"void",
"setHNRE",
"(",
"String",
"newvalue",
")",
"{",
"fieldHNRE",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HNRE as a String.\n */",
"public",
"String",
"getHNRE",
"(",
")",
"{",
"return",
"fieldHNRE",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HNRE using a BigDecimal value.\n */",
"public",
"void",
"setHNRE",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHNRE",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HNRE as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHNRE",
"(",
")",
"{",
"return",
"fieldHNRE",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HRRL using a String value.\n */",
"public",
"void",
"setHRRL",
"(",
"String",
"newvalue",
")",
"{",
"fieldHRRL",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HRRL as a String.\n */",
"public",
"String",
"getHRRL",
"(",
")",
"{",
"return",
"fieldHRRL",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HRRL using a BigDecimal value.\n */",
"public",
"void",
"setHRRL",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHRRL",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HRRL as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHRRL",
"(",
")",
"{",
"return",
"fieldHRRL",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HTOT using a String value.\n */",
"public",
"void",
"setHTOT",
"(",
"String",
"newvalue",
")",
"{",
"fieldHTOT",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HTOT as a String.\n */",
"public",
"String",
"getHTOT",
"(",
")",
"{",
"return",
"fieldHTOT",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field HTOT using a BigDecimal value.\n */",
"public",
"void",
"setHTOT",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldHTOT",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field HTOT as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalHTOT",
"(",
")",
"{",
"return",
"fieldHTOT",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field HFLI using a String value.\n */",
"public",
"void",
"setHFLI",
"(",
"String",
"newvalue",
")",
"{",
"fieldHFLI",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HFLI as a String.\n */",
"public",
"String",
"getHFLI",
"(",
")",
"{",
"return",
"fieldHFLI",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field HAREA using a String value.\n */",
"public",
"void",
"setHAREA",
"(",
"String",
"newvalue",
")",
"{",
"fieldHAREA",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field HAREA as a String.\n */",
"public",
"String",
"getHAREA",
"(",
")",
"{",
"return",
"fieldHAREA",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field EFLG0 using a String value.\n */",
"public",
"void",
"setEFLG0",
"(",
"String",
"newvalue",
")",
"{",
"fieldEFLG0",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field EFLG0 as a String.\n */",
"public",
"String",
"getEFLG0",
"(",
")",
"{",
"return",
"fieldEFLG0",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field EDSC0 using a String value.\n */",
"public",
"void",
"setEDSC0",
"(",
"String",
"newvalue",
")",
"{",
"fieldEDSC0",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field EDSC0 as a String.\n */",
"public",
"String",
"getEDSC0",
"(",
")",
"{",
"return",
"fieldEDSC0",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field PAICLA using a String value.\n */",
"public",
"void",
"setPAICLA",
"(",
"String",
"newvalue",
")",
"{",
"fieldPAICLA",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field PAICLA as a String.\n */",
"public",
"String",
"getPAICLA",
"(",
")",
"{",
"return",
"fieldPAICLA",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field PAICLA using a BigDecimal value.\n */",
"public",
"void",
"setPAICLA",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldPAICLA",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field PAICLA as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalPAICLA",
"(",
")",
"{",
"return",
"fieldPAICLA",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"/**\n * Set field PAINOM using a String value.\n */",
"public",
"void",
"setPAINOM",
"(",
"String",
"newvalue",
")",
"{",
"fieldPAINOM",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field PAINOM as a String.\n */",
"public",
"String",
"getPAINOM",
"(",
")",
"{",
"return",
"fieldPAINOM",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set field PAICTR using a String value.\n */",
"public",
"void",
"setPAICTR",
"(",
"String",
"newvalue",
")",
"{",
"fieldPAICTR",
".",
"setString",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Get value of field PAICTR as a String.\n */",
"public",
"String",
"getPAICTR",
"(",
")",
"{",
"return",
"fieldPAICTR",
".",
"getString",
"(",
")",
";",
"}",
"/**\n * Set numeric field PAICTR using a BigDecimal value.\n */",
"public",
"void",
"setPAICTR",
"(",
"BigDecimal",
"newvalue",
")",
"{",
"fieldPAICTR",
".",
"setBigDecimal",
"(",
"newvalue",
")",
";",
"}",
"/**\n * Return value of numeric field PAICTR as a BigDecimal.\n */",
"public",
"BigDecimal",
"getBigDecimalPAICTR",
"(",
")",
"{",
"return",
"fieldPAICTR",
".",
"getBigDecimal",
"(",
")",
";",
"}",
"}"
] | Class generated by AS/400 CRTCLASS command from WCREPAIA physical file definition. | [
"Class",
"generated",
"by",
"AS",
"/",
"400",
"CRTCLASS",
"command",
"from",
"WCREPAIA",
"physical",
"file",
"definition",
"."
] | [] | [
{
"param": "MessageRecord",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "MessageRecord",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
3332de1f786d9b8b1af2719cbd7743129b7bc734 | Spronghi/Sei | Kiu/app/src/main/java/com/spronghi/kiu/json/PlaceJSONParser.java | [
"MIT"
] | Java | PlaceJSONParser | /**
* Created by MatteoSemolaArena on 16/09/2016.
*/ | Created by MatteoSemolaArena on 16/09/2016. | [
"Created",
"by",
"MatteoSemolaArena",
"on",
"16",
"/",
"09",
"/",
"2016",
"."
] | public class PlaceJSONParser extends JSONParser<Place> {
@Override
public Place parse(String jsonString){
try {
return parse(new JSONObject(jsonString));
} catch (JSONException e) {
Log.d("JSON", e.getLocalizedMessage());
}
return null;
}
@Override
public Place parse(JSONObject obj) {
try {
Place place = new Place();
place.setId(obj.getInt("id"));
place.setCity(obj.getString("city"));
place.setAddress(obj.getString("address"));
place.setLocation(obj.getString("location"));
return place;
} catch (JSONException e) {
Log.d("JSON", e.getLocalizedMessage());
}
return null; }
@Override
public JSONObject getJSONObj(Place place){
JSONObject obj = new JSONObject();
try {
obj.put("id", place.getId());
obj.put("city", place.getCity());
obj.put("address", place.getAddress());
obj.put("location", place.getLocation());
} catch (JSONException e) {
Log.d("JSON", e.getLocalizedMessage());
}
return obj;
}
} | [
"public",
"class",
"PlaceJSONParser",
"extends",
"JSONParser",
"<",
"Place",
">",
"{",
"@",
"Override",
"public",
"Place",
"parse",
"(",
"String",
"jsonString",
")",
"{",
"try",
"{",
"return",
"parse",
"(",
"new",
"JSONObject",
"(",
"jsonString",
")",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"Log",
".",
"d",
"(",
"\"",
"JSON",
"\"",
",",
"e",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"}",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"Place",
"parse",
"(",
"JSONObject",
"obj",
")",
"{",
"try",
"{",
"Place",
"place",
"=",
"new",
"Place",
"(",
")",
";",
"place",
".",
"setId",
"(",
"obj",
".",
"getInt",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"place",
".",
"setCity",
"(",
"obj",
".",
"getString",
"(",
"\"",
"city",
"\"",
")",
")",
";",
"place",
".",
"setAddress",
"(",
"obj",
".",
"getString",
"(",
"\"",
"address",
"\"",
")",
")",
";",
"place",
".",
"setLocation",
"(",
"obj",
".",
"getString",
"(",
"\"",
"location",
"\"",
")",
")",
";",
"return",
"place",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"Log",
".",
"d",
"(",
"\"",
"JSON",
"\"",
",",
"e",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"}",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"JSONObject",
"getJSONObj",
"(",
"Place",
"place",
")",
"{",
"JSONObject",
"obj",
"=",
"new",
"JSONObject",
"(",
")",
";",
"try",
"{",
"obj",
".",
"put",
"(",
"\"",
"id",
"\"",
",",
"place",
".",
"getId",
"(",
")",
")",
";",
"obj",
".",
"put",
"(",
"\"",
"city",
"\"",
",",
"place",
".",
"getCity",
"(",
")",
")",
";",
"obj",
".",
"put",
"(",
"\"",
"address",
"\"",
",",
"place",
".",
"getAddress",
"(",
")",
")",
";",
"obj",
".",
"put",
"(",
"\"",
"location",
"\"",
",",
"place",
".",
"getLocation",
"(",
")",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"Log",
".",
"d",
"(",
"\"",
"JSON",
"\"",
",",
"e",
".",
"getLocalizedMessage",
"(",
")",
")",
";",
"}",
"return",
"obj",
";",
"}",
"}"
] | Created by MatteoSemolaArena on 16/09/2016. | [
"Created",
"by",
"MatteoSemolaArena",
"on",
"16",
"/",
"09",
"/",
"2016",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
333785a7ead74ca454bd739ccd9a617ef2d0c729 | cocoatomo/asakusafw | mapreduce/compiler/core/src/main/java/com/asakusafw/compiler/flow/stage/ShuffleEmiterUtil.java | [
"Apache-2.0"
] | Java | ShuffleEmiterUtil | /**
* Utilities for emitters about shuffle operations.
*/ | Utilities for emitters about shuffle operations. | [
"Utilities",
"for",
"emitters",
"about",
"shuffle",
"operations",
"."
] | final class ShuffleEmiterUtil {
/**
* The method name of comparing {@code int} values.
*/
public static final String COMPARE_INT = "compareInt"; //$NON-NLS-1$
/**
* The method name of extracting element ID from its port ID.
*/
public static final String PORT_TO_ELEMENT = "portIdToElementId"; //$NON-NLS-1$
public static List<List<Segment>> groupByElement(ShuffleModel model) {
List<List<Segment>> results = new ArrayList<>();
List<Segment> lastSegment = Collections.emptyList();
int lastElementId = -1;
for (Segment segment : model.getSegments()) {
if (lastElementId != segment.getElementId()) {
lastElementId = segment.getElementId();
if (lastSegment.isEmpty() == false) {
results.add(lastSegment);
}
lastSegment = new ArrayList<>();
}
lastSegment.add(segment);
}
if (lastSegment.isEmpty() == false) {
results.add(lastSegment);
}
return results;
}
public static String getPropertyName(Segment segment, Term term) {
assert segment != null;
assert term != null;
String name;
if (term.getArrangement() == Arrangement.GROUPING) {
name = Naming.getShuffleKeyGroupProperty(
segment.getElementId(),
term.getTermId());
} else {
name = Naming.getShuffleKeySortProperty(
segment.getPortId(),
term.getTermId());
}
return name;
}
public static MethodDeclaration createCompareInts(
ModelFactory factory) {
SimpleName a = factory.newSimpleName("a"); //$NON-NLS-1$
SimpleName b = factory.newSimpleName("b"); //$NON-NLS-1$
Statement statement = factory.newIfStatement(
new ExpressionBuilder(factory, a)
.apply(InfixOperator.EQUALS, b)
.toExpression(),
new ExpressionBuilder(factory, Models.toLiteral(factory, 0))
.toReturnStatement(),
factory.newIfStatement(
new ExpressionBuilder(factory, a)
.apply(InfixOperator.LESS, b)
.toExpression(),
new ExpressionBuilder(factory, Models.toLiteral(factory, -1))
.toReturnStatement(),
new ExpressionBuilder(factory, Models.toLiteral(factory, +1))
.toReturnStatement()));
return factory.newMethodDeclaration(
null,
new AttributeBuilder(factory)
.Private()
.toAttributes(),
factory.newBasicType(BasicTypeKind.INT),
factory.newSimpleName(COMPARE_INT),
Arrays.asList(new FormalParameterDeclaration[] {
factory.newFormalParameterDeclaration(
factory.newBasicType(BasicTypeKind.INT),
a),
factory.newFormalParameterDeclaration(
factory.newBasicType(BasicTypeKind.INT),
b),
}),
Collections.singletonList(statement));
}
public static MethodDeclaration createPortToElement(
ModelFactory factory,
ShuffleModel model) {
List<Statement> cases = new ArrayList<>();
for (List<Segment> segments : groupByElement(model)) {
for (Segment segment : segments) {
cases.add(factory.newSwitchCaseLabel(
Models.toLiteral(factory, segment.getPortId())));
}
cases.add(factory.newReturnStatement(
Models.toLiteral(factory, segments.get(0).getElementId())));
}
cases.add(factory.newSwitchDefaultLabel());
cases.add(factory.newReturnStatement(Models.toLiteral(factory, -1)));
SimpleName pid = factory.newSimpleName("pid"); //$NON-NLS-1$
Statement statement = factory.newSwitchStatement(pid, cases);
return factory.newMethodDeclaration(
null,
new AttributeBuilder(factory)
.Private()
.toAttributes(),
factory.newBasicType(BasicTypeKind.INT),
factory.newSimpleName(PORT_TO_ELEMENT),
Collections.singletonList(factory.newFormalParameterDeclaration(
factory.newBasicType(BasicTypeKind.INT),
pid)),
Collections.singletonList(statement));
}
private ShuffleEmiterUtil() {
return;
}
} | [
"final",
"class",
"ShuffleEmiterUtil",
"{",
"/**\n * The method name of comparing {@code int} values.\n */",
"public",
"static",
"final",
"String",
"COMPARE_INT",
"=",
"\"",
"compareInt",
"\"",
";",
"/**\n * The method name of extracting element ID from its port ID.\n */",
"public",
"static",
"final",
"String",
"PORT_TO_ELEMENT",
"=",
"\"",
"portIdToElementId",
"\"",
";",
"public",
"static",
"List",
"<",
"List",
"<",
"Segment",
">",
">",
"groupByElement",
"(",
"ShuffleModel",
"model",
")",
"{",
"List",
"<",
"List",
"<",
"Segment",
">",
">",
"results",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"List",
"<",
"Segment",
">",
"lastSegment",
"=",
"Collections",
".",
"emptyList",
"(",
")",
";",
"int",
"lastElementId",
"=",
"-",
"1",
";",
"for",
"(",
"Segment",
"segment",
":",
"model",
".",
"getSegments",
"(",
")",
")",
"{",
"if",
"(",
"lastElementId",
"!=",
"segment",
".",
"getElementId",
"(",
")",
")",
"{",
"lastElementId",
"=",
"segment",
".",
"getElementId",
"(",
")",
";",
"if",
"(",
"lastSegment",
".",
"isEmpty",
"(",
")",
"==",
"false",
")",
"{",
"results",
".",
"add",
"(",
"lastSegment",
")",
";",
"}",
"lastSegment",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"}",
"lastSegment",
".",
"add",
"(",
"segment",
")",
";",
"}",
"if",
"(",
"lastSegment",
".",
"isEmpty",
"(",
")",
"==",
"false",
")",
"{",
"results",
".",
"add",
"(",
"lastSegment",
")",
";",
"}",
"return",
"results",
";",
"}",
"public",
"static",
"String",
"getPropertyName",
"(",
"Segment",
"segment",
",",
"Term",
"term",
")",
"{",
"assert",
"segment",
"!=",
"null",
";",
"assert",
"term",
"!=",
"null",
";",
"String",
"name",
";",
"if",
"(",
"term",
".",
"getArrangement",
"(",
")",
"==",
"Arrangement",
".",
"GROUPING",
")",
"{",
"name",
"=",
"Naming",
".",
"getShuffleKeyGroupProperty",
"(",
"segment",
".",
"getElementId",
"(",
")",
",",
"term",
".",
"getTermId",
"(",
")",
")",
";",
"}",
"else",
"{",
"name",
"=",
"Naming",
".",
"getShuffleKeySortProperty",
"(",
"segment",
".",
"getPortId",
"(",
")",
",",
"term",
".",
"getTermId",
"(",
")",
")",
";",
"}",
"return",
"name",
";",
"}",
"public",
"static",
"MethodDeclaration",
"createCompareInts",
"(",
"ModelFactory",
"factory",
")",
"{",
"SimpleName",
"a",
"=",
"factory",
".",
"newSimpleName",
"(",
"\"",
"a",
"\"",
")",
";",
"SimpleName",
"b",
"=",
"factory",
".",
"newSimpleName",
"(",
"\"",
"b",
"\"",
")",
";",
"Statement",
"statement",
"=",
"factory",
".",
"newIfStatement",
"(",
"new",
"ExpressionBuilder",
"(",
"factory",
",",
"a",
")",
".",
"apply",
"(",
"InfixOperator",
".",
"EQUALS",
",",
"b",
")",
".",
"toExpression",
"(",
")",
",",
"new",
"ExpressionBuilder",
"(",
"factory",
",",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"0",
")",
")",
".",
"toReturnStatement",
"(",
")",
",",
"factory",
".",
"newIfStatement",
"(",
"new",
"ExpressionBuilder",
"(",
"factory",
",",
"a",
")",
".",
"apply",
"(",
"InfixOperator",
".",
"LESS",
",",
"b",
")",
".",
"toExpression",
"(",
")",
",",
"new",
"ExpressionBuilder",
"(",
"factory",
",",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"-",
"1",
")",
")",
".",
"toReturnStatement",
"(",
")",
",",
"new",
"ExpressionBuilder",
"(",
"factory",
",",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"+",
"1",
")",
")",
".",
"toReturnStatement",
"(",
")",
")",
")",
";",
"return",
"factory",
".",
"newMethodDeclaration",
"(",
"null",
",",
"new",
"AttributeBuilder",
"(",
"factory",
")",
".",
"Private",
"(",
")",
".",
"toAttributes",
"(",
")",
",",
"factory",
".",
"newBasicType",
"(",
"BasicTypeKind",
".",
"INT",
")",
",",
"factory",
".",
"newSimpleName",
"(",
"COMPARE_INT",
")",
",",
"Arrays",
".",
"asList",
"(",
"new",
"FormalParameterDeclaration",
"[",
"]",
"{",
"factory",
".",
"newFormalParameterDeclaration",
"(",
"factory",
".",
"newBasicType",
"(",
"BasicTypeKind",
".",
"INT",
")",
",",
"a",
")",
",",
"factory",
".",
"newFormalParameterDeclaration",
"(",
"factory",
".",
"newBasicType",
"(",
"BasicTypeKind",
".",
"INT",
")",
",",
"b",
")",
",",
"}",
")",
",",
"Collections",
".",
"singletonList",
"(",
"statement",
")",
")",
";",
"}",
"public",
"static",
"MethodDeclaration",
"createPortToElement",
"(",
"ModelFactory",
"factory",
",",
"ShuffleModel",
"model",
")",
"{",
"List",
"<",
"Statement",
">",
"cases",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"for",
"(",
"List",
"<",
"Segment",
">",
"segments",
":",
"groupByElement",
"(",
"model",
")",
")",
"{",
"for",
"(",
"Segment",
"segment",
":",
"segments",
")",
"{",
"cases",
".",
"add",
"(",
"factory",
".",
"newSwitchCaseLabel",
"(",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"segment",
".",
"getPortId",
"(",
")",
")",
")",
")",
";",
"}",
"cases",
".",
"add",
"(",
"factory",
".",
"newReturnStatement",
"(",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"segments",
".",
"get",
"(",
"0",
")",
".",
"getElementId",
"(",
")",
")",
")",
")",
";",
"}",
"cases",
".",
"add",
"(",
"factory",
".",
"newSwitchDefaultLabel",
"(",
")",
")",
";",
"cases",
".",
"add",
"(",
"factory",
".",
"newReturnStatement",
"(",
"Models",
".",
"toLiteral",
"(",
"factory",
",",
"-",
"1",
")",
")",
")",
";",
"SimpleName",
"pid",
"=",
"factory",
".",
"newSimpleName",
"(",
"\"",
"pid",
"\"",
")",
";",
"Statement",
"statement",
"=",
"factory",
".",
"newSwitchStatement",
"(",
"pid",
",",
"cases",
")",
";",
"return",
"factory",
".",
"newMethodDeclaration",
"(",
"null",
",",
"new",
"AttributeBuilder",
"(",
"factory",
")",
".",
"Private",
"(",
")",
".",
"toAttributes",
"(",
")",
",",
"factory",
".",
"newBasicType",
"(",
"BasicTypeKind",
".",
"INT",
")",
",",
"factory",
".",
"newSimpleName",
"(",
"PORT_TO_ELEMENT",
")",
",",
"Collections",
".",
"singletonList",
"(",
"factory",
".",
"newFormalParameterDeclaration",
"(",
"factory",
".",
"newBasicType",
"(",
"BasicTypeKind",
".",
"INT",
")",
",",
"pid",
")",
")",
",",
"Collections",
".",
"singletonList",
"(",
"statement",
")",
")",
";",
"}",
"private",
"ShuffleEmiterUtil",
"(",
")",
"{",
"return",
";",
"}",
"}"
] | Utilities for emitters about shuffle operations. | [
"Utilities",
"for",
"emitters",
"about",
"shuffle",
"operations",
"."
] | [
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
3337f0c6629e6d1d2261f8447b85f3be1e3b5bbd | VirtueDev/synced_repo | src/java/com/threerings/msoy/admin/server/DepotQueriesStatCollector.java | [
"BSD-3-Clause"
] | Java | DepotQueriesStatCollector | /**
* Collects stats on Depot query performance.
*/ | Collects stats on Depot query performance. | [
"Collects",
"stats",
"on",
"Depot",
"query",
"performance",
"."
] | public class DepotQueriesStatCollector extends StatCollector
{
public DepotQueriesStatCollector (PersistenceContext perCtx)
{
_perCtx = perCtx;
}
@Override // from StatCollector
public Object compileStats ()
{
// Stats.Snapshot stats = _perCtx.getStats();
return null; // TODO
}
@Override // from StatCollector
public Merger createMerger () {
return new Merger() {
protected void mergeStats (String nodeName, Object stats) {
// TODO
}
protected StatsModel finalizeModel () {
// TODO
return _model;
}
protected StatsModel _model = StatsModel.newRowModel(
"stat", "ops", "con. wait", "avg wait",
"q. cached", "q. uncached", "q. explicit", // "q. %",
"r. cached", "r. uncached", // "r. %",
"reads", "read time", "avg read", "writes", "write time", "avg write");
};
}
protected PersistenceContext _perCtx;
} | [
"public",
"class",
"DepotQueriesStatCollector",
"extends",
"StatCollector",
"{",
"public",
"DepotQueriesStatCollector",
"(",
"PersistenceContext",
"perCtx",
")",
"{",
"_perCtx",
"=",
"perCtx",
";",
"}",
"@",
"Override",
"public",
"Object",
"compileStats",
"(",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"Merger",
"createMerger",
"(",
")",
"{",
"return",
"new",
"Merger",
"(",
")",
"{",
"protected",
"void",
"mergeStats",
"(",
"String",
"nodeName",
",",
"Object",
"stats",
")",
"{",
"}",
"protected",
"StatsModel",
"finalizeModel",
"(",
")",
"{",
"return",
"_model",
";",
"}",
"protected",
"StatsModel",
"_model",
"=",
"StatsModel",
".",
"newRowModel",
"(",
"\"",
"stat",
"\"",
",",
"\"",
"ops",
"\"",
",",
"\"",
"con. wait",
"\"",
",",
"\"",
"avg wait",
"\"",
",",
"\"",
"q. cached",
"\"",
",",
"\"",
"q. uncached",
"\"",
",",
"\"",
"q. explicit",
"\"",
",",
"\"",
"r. cached",
"\"",
",",
"\"",
"r. uncached",
"\"",
",",
"\"",
"reads",
"\"",
",",
"\"",
"read time",
"\"",
",",
"\"",
"avg read",
"\"",
",",
"\"",
"writes",
"\"",
",",
"\"",
"write time",
"\"",
",",
"\"",
"avg write",
"\"",
")",
";",
"}",
";",
"}",
"protected",
"PersistenceContext",
"_perCtx",
";",
"}"
] | Collects stats on Depot query performance. | [
"Collects",
"stats",
"on",
"Depot",
"query",
"performance",
"."
] | [
"// from StatCollector",
"// Stats.Snapshot stats = _perCtx.getStats();",
"// TODO",
"// from StatCollector",
"// TODO",
"// TODO",
"// \"q. %\",",
"// \"r. %\","
] | [
{
"param": "StatCollector",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "StatCollector",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |