lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
47c174658098ae0328a88b045236b6d5ff837b7c
0
rndme/intraHTML
// intraHTML: a better innerHTML (partial/non-destructive updates) for faster and simpler view rendering. (c)2015:dandavis, [CCBY4/MIT] // usage: intraHTML(element, strNewInnerHTMLContent); // includes a slightly modified copy of the odiff JS library by Billy Tetrud, under a modified MIT license per "Free to use for any purpose" from https://github.com/Tixit/odiff/blob/master/odiff.js (function defineIntraHTML (global, factory) { if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') { module.exports=factory(); // CommonJS } else if (typeof define === 'function' && define.amd) { define(['exports'], factory()); // AMD } else { global.intraHTML = factory(global); // script, jq plugin, wsh, asp } }(this, function intraHTMLFactory (pub) { if(!Number.isNaN) Number.isNaN = function(value) { return typeof value === "number" && isNaN(value);}; if (!Array.isArray) Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]';}; // 2015-10-22 :: https://github.com/Tixit/odiff - changes: compare direct first, perf tweaks var odiff=function(z,A){function u(b,a,c,d,g,l,m){for(var e=d-l,h=g-m,k=Math.max(e,h),f=1;f<=k;f++){var n=a[d-f],v=c[g-f];if(f<=h&&f<=e&&b(n,v))return{a:d-f,b:g-f};for(var q=0;q<f;q++){var B=a[d-q],p=c[g-q];if(f<=h&&b(B,v))return{a:d-q,b:g-f};if(f<=e&&b(n,p))return{a:d-f,b:g-q}}}return{a:l-1,b:m-1}}function w(b,a){if(b===a)return!0;if(Array.isArray(b)){if(!Array.isArray(a))return!1;for(var c=b.length/15,d=Math.abs(b.length-a.length),g=0,l=b.length;g<l;g++)if(p(b[g],a[g])){if(2<=d&&d>c||d===b.length)return!1;d++}return!0}if("object"==typeof b){if("object"!=typeof a)return!1;var g=x(r(Object.keys(b)),r(Object.keys(a))),l=Object.keys(g).length,c=l/15,d=0,m;for(m in g)if(!p(b[m],a[m])){if(2<=d&&d>c||d+1===l)return!1;d++}return!0}return Number.isNaN(b)&&Number.isNaN(a)}function p(b,a){if(b===a)return!0;if(Array.isArray(b)){if(Array.isArray(a)&&b.length===a.length&&b[0]===a[0]&&String(b)===String(a)){for(var c=0,d=b.length;c<d;c++)if(!p(b[c],a[c]))return!1;return!0}return!1}if("object"==typeof b){if("object"!=typeof a)return!1;var g=Object.keys(b),c=Object.keys(a);if(g.length!==c.length||String(g)!==String(c))return!1;c=0;for(d=g.length;c<d;c++)if(!p(b[g[c]],a[g[c]]))return!1;return!0}return Number.isNaN(b)&&Number.isNaN(a)}function r(b){var a=0,c=b.length,d={};for(a;a<c;a++)d[b[a]]=!0;return d}function x(b,a){for(var c in a)b[c]=a[c];return b}var t=function(b,a,c,d){function g(a,b,c){a.push({type:"set",path:b,val:c})}function l(a,b,c,d,e){a.push({type:"rm",path:b,index:c,num:d,mode:e})}function m(a,b,c,d){a.push({type:"add",path:b,index:c,vals:d})}if(!(b===a||Number.isNaN(b)&&Number.isNaN(a)))if(Array.isArray(b)&&Array.isArray(a)){for(var e=b.length-1,h=a.length-1;0<=e&&0<=h;)if(p(b[e],a[h]))e--,h--;else{for(var k=u(p,b,a,e,h,0,0),f=e;f>k.a&&h>k.b;)if(w(b[f],a[h]))t(b[f],a[h],c,d.concat([f])),f--,h--;else{var e=u(w,b,a,f,h,k.a+1,k.b+1),f=f-e.a,n=h-e.b;1===f&&1===n?g(c,d.concat(e.a+1),a[e.b+1]):1===f&&2===n?(m(c,d,e.a+2,a.slice(e.b+2,h+1)),g(c,d.concat(e.a+1),a[e.b+1])):2===f&&1===n?(l(c,d,e.a+2,1,"I"),g(c,d.concat(e.a+1),a[e.b+1])):2===f&&2===n?(g(c,d.concat(e.a+2),a[e.b+2]),g(c,d.concat(e.a+1),a[e.b+1])):(0<f&&l(c,d,e.a+1,f,"X"),0<n&&m(c,d,e.a+1,a.slice(e.b+1,h+1))),f=e.a,h=e.b}f>k.a?l(c,d,f,f-k.a,"Z"):h>k.b&&m(c,d,f+1,a.slice(k.b+1,h+1)),e=k.a,h=k.b}0<=e?l(c,d,0,e+1):0<=h&&m(c,d,0,a.slice(0,h+1))}else if("object"==typeof b&&"object"==typeof a)for(h in k=x(r(Object.keys(b)),r(Object.keys(a))),k)t(b[h],a[h],c,d.concat([h]));else g(c,d,a)},y=[];return t(z,A,y,[]),y}; //need to pull from master, rewire these two in, plus the for-loop on apply changes function forEach(r,f,v){ "use strict"; if(arguments.length<2) return; var m=r.length, i=0; for (; i<m; i++) f(r[i],i,r); } function filter(r, f) { "use strict"; var m=r.length, o=[], i=0; for(; i<m; i++) if(f(r[i],i,r)) o.push(r[i]); return o; } // given a string of html, returns a document fragment of that content: fragmentFromString.temp = document.createElement('template'); function fragmentFromString(strHTML) { var temp = fragmentFromString.temp; temp.innerHTML = strHTML; return temp.content; } var elementFromString = function elementFromString(strHTML, containerTagName) { var temp = document.createElement(containerTagName || "div"); temp.innerHTML = strHTML; return temp; }; // given a string of html, returns a document fragment of that content: fragmentFromString.temp = document.createElement('template'); if("content" in fragmentFromString.temp) elementFromString = fragmentFromString; // given an html element or html string, returns a vdom of that markpup: function fromHTML(source, containerTagName) { function scan(ob) { var bag = [], i = 0, v, tag, mx = ob.childNodes.length; for(i; i < mx; i++) { v = ob.childNodes[i]; if(v.tagName) { // recurse sub-tags if any tag = { $: v.tagName.toLowerCase() }; for(var i2 = 0, va = v.attributes, attr, mx2 = va.length; i2 < mx2; i2++) { attr = va[i2]; tag[attr.name] = attr.value; } tag._=scan(v); bag.push(tag); } else { //if sub tags? no: bag.push(v.nodeValue); } } return bag; } // end scan() if(typeof source === "string") { return parseHT(source); } else { return scan({ tagName: containerTagName||"div", attributes: [], childNodes: [source] })[0]; } } //end fromHTML var entities={'&quot;':'"', '&amp;':"&", '&lt;':'<', '&gt;': '>', '&apos;': "'"}; ("nbsp,iexcl,cent,pound,curren,yen,brvbar,sect,uml,copy,ordf,laquo,not,shy,reg,macr,deg,plusmn,sup2,sup3,acute,micro,para,middot,cedil,sup1,ordm,raquo,"+ "frac14,frac12,frac34,iquest,Agrave,Aacute,Acirc,Atilde,Auml,Aring,AElig,Ccedil,Egrave,Eacute,Ecirc,Euml,Igrave,Iacute,Icirc,Iuml,ETH,Ntilde,Ograve,Oacute,"+ "Ocirc,Otilde,Ouml,times,Oslash,Ugrave,Uacute,Ucirc,Uuml,Yacute,THORN,szlig,agrave,aacute,acirc,atilde,auml,aring,aelig,ccedil,egrave,eacute,ecirc,euml,"+ "igrave,iacute,icirc,iuml,eth,ntilde,ograve,oacute,ocirc,otilde,ouml,divide,oslash,ugrave,uacute,ucirc,uuml,yacute,thorn,yuml").split(",").forEach(function(a,b,c){ this["&"+a+";"]= String.fromCharCode(160+b); }, entities); function parseHT(html) { "use strict"; html=String(html).replace(/<\!\-\-[\s\S]+?\-\->/g,""); var out = { $: "ROOT", _: [] }, parent = out, out2 = out, rxQuoteOpen = /^['"]/, rxQuoteClose = /['"]$/, rxWhite = /\s+/, rxTagNameEnd = /[\s>]/, tag = out, heap = html.split(/([<>])/), last = "", hint, token, index = 0, mx2 = heap.length, name, r, b = 1, mx, a, n, strAttribs, cap, val, key, attrValue, parents = [out], overlap, rxBooleanAttrib =/([\w\-]+)()/g , rxAttrVal = /([\w\-]+)=([^\s>\/]+)/g, rxAttribValQ = /([\w\-]+)="([^"]*)"/g, rxAttribValA = /([\w\-]+)='([^']*)'/g, rxs=[rxAttribValQ, rxAttribValA, rxAttrVal, rxBooleanAttrib]; function fnReppr(j, k, v, x, y){ tag[k]=v || ""; return ""; } // loop through all tag opening and closing tags in a flattened array: for(; index < mx2; index++) { token = heap[index]; hint = token.slice(0, 1); if(last === "<"){ if(hint === "/") { // handle closing tags: (return to parent, clear buffer); tag = parents.pop(); out = tag; last = ""; continue; } // handle opening tags by making new tag object and adding attribs and kids n=token.search(rxTagNameEnd); if(n===-1) n = 20; name=token.slice(0, n); strAttribs= token.slice(n); // save old tag to parent children collection: parents.push(out); // create a new tag object: out._.push(tag = { $: name, _: [] }); // add attribs: if(strAttribs) for(b=0; b<4; b++) strAttribs=strAttribs.replace(rxs[b], fnReppr ); if(singleTags[name]){ last=token; tag = parents.pop(); out = tag; continue; } // move "cursor" to this new tag: if(out !== tag) parent = out; out = tag; last = token; continue; }// end if tag opening? //if not tag open or close, must be content, add to cursor tag: if(token && !(token === "<" || token === ">") ) tag._.push( token.indexOf("&") === -1 ? token : token.replace(/(&\w+;)/g, function(j, a){ return entities[a] || a; })); // memorize current value for parser peek-behind to find closing tags: last = token; } return out2._[0]; }//end parseHT() function resolvePath(path, base) { var last = [], i=0, mx =path.length, out=base, u, k; for(i; i<mx; i++){ k = path[i]; if(k==="_") k="childNodes"; last.push(out); out = out[k]; if(out===u) break ; }; return { node: out, parents: last }; } function resolveAll(path, base) { var last = [], i=0, mx =path.length, out=base, u; for(i; i<mx; i++){ last.push(out); out = out[path[i]]; if(out===u) break ; }; return { node: out, parents: last }; } var singleTags={area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1}; function toHT(obj) { var attribs = "", r = [], tn, kids, u, a, i, o, mx, own = r.hasOwnProperty; if(obj === u) return ""; tn=obj.$; // build attribs from values and functions: for(a in obj) if( a !== "$" && a !== "_" && own.call(obj, a) ) attribs += (" " + a) + ((obj[a] === "") ? "" : ("=" + JSON.stringify(obj[a]))); if(singleTags[tn]) return "<" + tn + attribs + " />"; kids = obj._ || []; if(kids && !Array.isArray(kids)) kids = [kids]; for(i = 0, o, mx = kids.length; i < mx; i++) { o = kids[i]; // || ""; r[i] = typeof o === "object" ? toHT(o) : o; } return "<" + tn + attribs + ">" + r.join("") + "</" + tn + ">"; } //given a change array, applies the changes to the element that's rendering the vdom: function applyChanges(change, INDEX, ALLS, that) { var time = that.timing, startTime = time ? performance.now() : 0, bug = that.debug, path = filter(change.path.concat(change.index || change.key), function _pathFilterer(a, b, c) { return a != b.xsdgdfg; }), slice = path.slice, lastChange = ALLS[INDEX - 1] || "", key = filter(path, function _keyFilterer(a, b, c) { return a != b.xsdgdfg; }).slice(-1)[0], elm = resolvePath(path, that.dest), parents = resolveAll(path, that.vdom), elmPar = filter(elm.parents, Boolean), ochange = { type: change.type, index: INDEX, path: path, key: key, elm: elm.node || elm.parents.slice(-1)[0], elmParents: elmPar, elmParent: elmPar.slice(-1)[0], dest: that.dest, parents: parents, parent: parents.parents.slice(-1)[0], isAttrib: !(key - 0.1) && key != "_" && key != "$", change: change }, attrs, a, mx, i, it, kids, temp, content, ext, cp, cc, vals, val, old; if(typeof ochange.elm == "function") ochange.elm = ochange.elmParent; if(bug) console.info("CHANGE: " + INDEX, ochange); function _setStrParFinder(a, b, c) {return a.textContent !== a.fsdhjklghdklg;} switch(change.type) { case "set": if(!ochange.isAttrib && (typeof change.val === "string" || Array.isArray(change.val))) { cp = ochange.elm; if(!ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent[ochange.key]; if(!ochange.elm) ochange.elm = ochange.elmParent; vals = change.val; if(!Array.isArray(vals)) vals = [vals]; for(var valIndex = 0, maxIndex = vals.length; valIndex < maxIndex; valIndex++) { val = vals[valIndex]; if(typeof val === "string") { //add text nodes: if(ochange.elm instanceof NodeList) ochange.elm = filter(ochange.elmParents, _setStrParFinder ).pop(); if(ochange.elm.childNodes) { if(bug) console.log("set: non attrib, string, elm: ", ochange.key, [val], ochange.elm.outerHTML); content = document.createTextNode(val); if(ochange.key === "_") { ochange.elm.textContent = val; } else { if(ochange.key === "$") { temp = document.createElement(change.val); if(bug) console.warn("changing tag name!", change); ochange.elm.parentNode.insertBefore(temp, ochange.elm); attrs = ochange.elm.attributes; for(i = 0, mx = attrs.length; i < mx; i++) { a = attrs[i]; temp.setAttribute(a.name, a.value); } kids = ochange.elm.childNodes; for(i = 0, mx = kids.length; i < mx; i++) temp.appendChild(kids[0]); ochange.elm.parentNode.removeChild(ochange.elm); } else { ochange.elm.parentNode.insertBefore(content, ochange.elm); ochange.elm.parentNode.removeChild(ochange.elm); } } change.elm = content; } else { if(bug) console.log("set: non attrib, string, not elm", val); ochange.elm.textContent = val; //update element change.elm = ochange.elm; } } else { //add elms: content = typeof val === "string" ? document.createTextNode(val) : elementFromString(toHT(val), ochange.elmParent[0] && ochange.elmParent[0].parentNode.tagName).firstChild; if(!ochange.elm.parentNode) ochange.elm = ochange.elmParent; old = ochange.elm.childNodes[+key + valIndex]; if(old) { if(bug) console.log("set: non attrib, not string, has old", val); ochange.elm.insertBefore(content, old); ochange.elm.removeChild(ochange.elm); } else { if(bug) console.log("set: non attrib, not string, no old, appending", [val, content, content.outerHTML || content.textContent]); ochange.elm.appendChild(content); } } if(key == "_") { key = 0; if(!ochange.parent.length) ochange.parent = (ochange.parent._ || (ochange.parent._ = [])); } if(bug) console.info("attempting key change", + key + valIndex, !! (1.1 - key), key, valIndex, val, ochange.parent[+key + valIndex], [ochange.parent]); } break; } if(ochange.isAttrib) { if(key == "$" && String(path) == key) throw new TypeError("You cannot change the root element of an update-bound element: " + ochange.elm.outerHTML); if(key == "$") { temp = document.createElement(change.val); if(bug) console.warn("changing tag name!", change); ochange.elm.parentNode.insertBefore(temp, ochange.elm); attrs = ochange.elm.attributes; for(i = 0, mx = attrs.length; i < mx; i++) { a = attrs[i]; temp.setAttribute(a.name, a.value); } kids = ochange.elm.childNodes; for(i = 0, mx = kids.length; i < mx; i++) temp.appendChild(kids[0]); change.elm = temp; ochange.elm.parentNode.removeChild(ochange.elm); } else { if(!ochange.elm.setAttribute && ochange.elm.parentNode && ochange.elm.parentNode.setAttribute) { ochange.elm = ochange.elm.parentNode; } if(!ochange.elm.setAttribute && (cc = filter(ochange.elmParents, function _setParFinderCC(a, b, c) { return a.setAttribute; }).slice(-1)[0]).setAttribute) { ochange.elm = cc; } if(change.val === change.dgfjkdfl34534fd) { ochange.elm.removeAttribute(key); //update element } else { ochange.elm.setAttribute(key, change.val); //update element } change.elm = ochange.elm; } break; } if(ochange.elm.length && change.val === change.sdgfdf) { for(var i6 = 0, mx6 = ochange.elm.length; i6 < mx6; i6++) ochange.elm[0].parentNode.removeChild(ochange.elm[0]); } else { if(ochange.elm instanceof NodeList) ochange.elm = filter(ochange.elmParents, function _setParFinder(a, b, c) { return a.textContent !== a.fsdhjklghdklg; }).pop(); temp = elementFromString(toHT(change.val), ochange.parent.$).firstChild; if(bug) console.log("element replacing", [ochange.elm.outerHTML || ochange.elm.textContent], " with ", [temp.outerHTML]); change.elm = temp; ochange.elm.parentNode.insertBefore(temp, ochange.elm); ochange.elm.parentNode.removeChild(ochange.elm); } break; case "add": if(!ochange.isAttrib) { if(ochange.key == "_") { ochange.elm = ochange.elm[change.index]; ochange.key = change.index; ochange.parent = ochange.parent._; ochange.elmParent = ochange.elmParent.childNodes; } forEach(change.vals, function _valUpdater(val, i, arrWhole) { if(!ochange.elmParent.length) ochange.elmParent = ochange.elmParents.slice(-1)[0].childNodes; if(!ochange.elmParent) ochange.elmParent = ochange.elmParents.slice(-2)[0].childNodes; content = typeof val === "string" ? document.createTextNode(val) : elementFromString(toHT(val), ochange.elmParent[0] && ochange.elmParent[0].parentNode.tagName).firstChild; ext = ochange.elmParent[ochange.key + i]; change.elm = content; if(ext) { ext.parentNode.insertBefore(content, ext); ochange.parent.splice(ochange.key + i, 0, val); } else { if(ochange.elmParent[ochange.key + i]) { ochange.elmParent[ochange.key + i] = content; } else { it = ochange.elmParents.slice(-1)[0]; if(it[0]) it = it[it.length - 1]; if(ochange.elm && ochange.elm.length >= ochange.key) it = ochange.elm[0].parentNode; if(it instanceof NodeList) it = filter(ochange.elmParents, function _addParFinder(a, b, c) { return a.textContent !== a.fsdhjklghdklg; }).pop(); if(it !== content) { if(it.nodeType != 3) { it.appendChild(content); } else { it.parentNode.insertBefore(content, it); it.parentNode.insertBefore(it, content); } } } } }); } break; case "rm": if(ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent.childNodes; if(ochange.elmParent.length === 0) ochange.elmParent = ochange.elmParents.slice(-3)[0]; if(ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent.childNodes; if(ochange.parent._) ochange.parent = ochange.parent._; // list out what to remove: var min = change.index - change.num, max = change.index, toRemove = slice.call(ochange.elmParent, min + 1, max + 1); if(change.index === 0) { // it starts at zero, the odiff range goes positive instead of couring backwards from 0: if(bug) console.log("removing many from zero", slice.call(ochange.parent), ochange.elmParent, "|||", ochange.parent[0], change.index, change.num); for(i = change.index, mx = i + change.num; i < mx; i++) { ochange.elmParent[change.index].remove(); } change.elm = ochange.elmParent; } else { if(change.index - change.num > -1) { if(change.num === 1) { toRemove = [ochange.elmParent[change.index]]; if(bug) console.log("removing one", ochange.elmParent, toRemove[0].outerHTML, change.index, slice.call(ochange.elmParent).map(function _removeOneConsoleMapper(a) { return a.outerHTML || a.nodeValue; }), ochange.parent); } else { if(change.index + change.num < ochange.elmParent.length + 1) { var ind = change.index; if(ind > 1 && change.mode === "Z") ind = ind - (change.num - 1); if(bug) console.log("removing many up", change.mode, ochange.elmParent, ind, ind + change.num); toRemove = slice.call(ochange.elmParent, ind, ind + change.num); } else { //count backwards: if(bug) console.log("removing many down", slice.call(ochange.elmParent), change.index - change.num, change.index); toRemove = slice.call(ochange.elmParent, (change.index - change.num) + 1, (change.index) + 1); } } } else { if(bug) console.log("removing many negative", ochange.elmParent, change.index, change.index + change.num); toRemove = slice.call(ochange.elmParent, change.index, change.index + change.num); } if(toRemove.length) change.elm = toRemove[0].parentNode; if(bug) console.log("removing:", toRemove, change, ochange.parent.slice((change.index - change.num) + 1, (change.index) + 1)); forEach(toRemove, function _toRemover(a, b, c) { a.parentNode.removeChild(a); }); } break; } if(time) change.runtime = performance.now() - startTime; } //end applyChanges() function getRenderer(dest, vdom, hint) { if(typeof dest === "string") dest = document.querySelector(dest); var it= intraHTML.timing ? performance.now() : 0, tag=dest.tagName.toLowerCase(), head="<"+tag+">", ht, st, state; if(!dest.childNodes.length) dest.innerHTML = " "; if(!vdom) vdom = dest; if(vdom instanceof Element){ ht=vdom.innerHTML; if(hint === ht) return {update: Boolean}; vdom = fromHTML(head + ht + "</" + tag + ">", tag); // actually faster using outerHTML than feeding it a dom node (dest, which works). confirm that widely... } if(typeof vdom === "string" ) vdom = fromHTML(vdom, tag); st= intraHTML.timing ? performance.now() : 0; state = { dest: dest, vdom: vdom, debug: intraHTML.debug, timing : intraHTML.timing, initTime: st-it, update: function(vdom) { var blnTime=intraHTML.timing, st, i=0, mx; if(blnTime) st=performance.now(); if(typeof vdom === "string") vdom = fromHTML(head + vdom + "</" + tag + ">", tag); if(blnTime) state.parseTime= (performance.now() - st); state.vdom2 = vdom; if(blnTime) st=performance.now(); state.changes = odiff(state.vdom, vdom); if(blnTime){ state.diffTime= performance.now() - st; st=performance.now(); } for(mx=state.changes.length;i<mx;i++) applyChanges(state.changes[i], i, state.changes, state); if(blnTime) state.applyTime= performance.now() - st; state.vdom = vdom; return state; } }; return state; } //the return/module value/main routine: function intraHTML(elm, content){ return intraHTML._last=getRenderer(elm, elm, content), intraHTML._last.update(content); } // publish useful internal helper methods: intraHTML.applyChanges = applyChanges; intraHTML.elementFromString=elementFromString; intraHTML.fromHTML = fromHTML; intraHTML.toHTML = toHT; intraHTML.odiff=odiff; intraHTML.parseHTML=parseHT; intraHTML.updater=getRenderer; intraHTML.getRenderer = getRenderer; //publish external options: intraHTML.timing = true; intraHTML.debug = false; intraHTML.entities =entities; // jQuery plugin: if(pub.jQuery) pub.jQuery.fn.intraHTML=function(strContent){ this.each(function jqiht(i,e){ intraHTML(e, strContent);}); return this; }; return intraHTML; }));
intrahtml.js
// intraHTML: a better innerHTML (partial/non-destructive updates) for faster and simpler view rendering. (c)2015:dandavis, [CCBY4/MIT] // usage: intraHTML(element, strNewInnerHTMLContent); // includes a slightly modified copy of the odiff JS library by Billy Tetrud, under a modified MIT license per "Free to use for any purpose" from https://github.com/Tixit/odiff/blob/master/odiff.js (function defineIntraHTML (global, factory) { if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') { module.exports=factory(); // CommonJS } else if (typeof define === 'function' && define.amd) { define(['exports'], factory()); // AMD } else { global.intraHTML = factory(global); // script, jq plugin, wsh, asp } }(this, function intraHTMLFactory (pub) { if(!Number.isNaN) Number.isNaN = function(value) { return typeof value === "number" && isNaN(value);}; if (!Array.isArray) Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]';}; // 2015-10-22 :: https://github.com/Tixit/odiff - changes: compare direct first, perf tweaks var odiff=function(z,A){function u(b,a,c,d,g,l,m){for(var e=d-l,h=g-m,k=Math.max(e,h),f=1;f<=k;f++){var n=a[d-f],v=c[g-f];if(f<=h&&f<=e&&b(n,v))return{a:d-f,b:g-f};for(var q=0;q<f;q++){var B=a[d-q],p=c[g-q];if(f<=h&&b(B,v))return{a:d-q,b:g-f};if(f<=e&&b(n,p))return{a:d-f,b:g-q}}}return{a:l-1,b:m-1}}function w(b,a){if(b===a)return!0;if(Array.isArray(b)){if(!Array.isArray(a))return!1;for(var c=b.length/15,d=Math.abs(b.length-a.length),g=0,l=b.length;g<l;g++)if(p(b[g],a[g])){if(2<=d&&d>c||d===b.length)return!1;d++}return!0}if("object"==typeof b){if("object"!=typeof a)return!1;var g=x(r(Object.keys(b)),r(Object.keys(a))),l=Object.keys(g).length,c=l/15,d=0,m;for(m in g)if(!p(b[m],a[m])){if(2<=d&&d>c||d+1===l)return!1;d++}return!0}return Number.isNaN(b)&&Number.isNaN(a)}function p(b,a){if(b===a)return!0;if(Array.isArray(b)){if(Array.isArray(a)&&b.length===a.length&&b[0]===a[0]&&String(b)===String(a)){for(var c=0,d=b.length;c<d;c++)if(!p(b[c],a[c]))return!1;return!0}return!1}if("object"==typeof b){if("object"!=typeof a)return!1;var g=Object.keys(b),c=Object.keys(a);if(g.length!==c.length||String(g)!==String(c))return!1;c=0;for(d=g.length;c<d;c++)if(!p(b[g[c]],a[g[c]]))return!1;return!0}return Number.isNaN(b)&&Number.isNaN(a)}function r(b){var a=0,c=b.length,d={};for(a;a<c;a++)d[b[a]]=!0;return d}function x(b,a){for(var c in a)b[c]=a[c];return b}var t=function(b,a,c,d){function g(a,b,c){a.push({type:"set",path:b,val:c})}function l(a,b,c,d,e){a.push({type:"rm",path:b,index:c,num:d,mode:e})}function m(a,b,c,d){a.push({type:"add",path:b,index:c,vals:d})}if(!(b===a||Number.isNaN(b)&&Number.isNaN(a)))if(Array.isArray(b)&&Array.isArray(a)){for(var e=b.length-1,h=a.length-1;0<=e&&0<=h;)if(p(b[e],a[h]))e--,h--;else{for(var k=u(p,b,a,e,h,0,0),f=e;f>k.a&&h>k.b;)if(w(b[f],a[h]))t(b[f],a[h],c,d.concat([f])),f--,h--;else{var e=u(w,b,a,f,h,k.a+1,k.b+1),f=f-e.a,n=h-e.b;1===f&&1===n?g(c,d.concat(e.a+1),a[e.b+1]):1===f&&2===n?(m(c,d,e.a+2,a.slice(e.b+2,h+1)),g(c,d.concat(e.a+1),a[e.b+1])):2===f&&1===n?(l(c,d,e.a+2,1,"I"),g(c,d.concat(e.a+1),a[e.b+1])):2===f&&2===n?(g(c,d.concat(e.a+2),a[e.b+2]),g(c,d.concat(e.a+1),a[e.b+1])):(0<f&&l(c,d,e.a+1,f,"X"),0<n&&m(c,d,e.a+1,a.slice(e.b+1,h+1))),f=e.a,h=e.b}f>k.a?l(c,d,f,f-k.a,"Z"):h>k.b&&m(c,d,f+1,a.slice(k.b+1,h+1)),e=k.a,h=k.b}0<=e?l(c,d,0,e+1):0<=h&&m(c,d,0,a.slice(0,h+1))}else if("object"==typeof b&&"object"==typeof a)for(h in k=x(r(Object.keys(b)),r(Object.keys(a))),k)t(b[h],a[h],c,d.concat([h]));else g(c,d,a)},y=[];return t(z,A,y,[]),y}; //need to pull from master, rewire these two in, plus the for-loop on apply changes function forEach(r,f,v){ "use strict"; if(arguments.length<2) return; var m=r.length, i=0; for (; i<m; i++) f(r[i],i,r); } function filter(r, f) { "use strict"; var m=r.length, o=[], i=0; for(; i<m; i++) if(f(r[i],i,r)) o.push(r[i]); return o; } // given a string of html, returns a document fragment of that content: fragmentFromString.temp = document.createElement('template'); function fragmentFromString(strHTML) { var temp = fragmentFromString.temp; temp.innerHTML = strHTML; return temp.content; } var elementFromString = function elementFromString(strHTML, containerTagName) { var temp = document.createElement(containerTagName || "div"); temp.innerHTML = strHTML; return temp; }; // given a string of html, returns a document fragment of that content: fragmentFromString.temp = document.createElement('template'); if("content" in fragmentFromString.temp) elementFromString = fragmentFromString; // given an html element or html string, returns a vdom of that markpup: function fromHTML(source, containerTagName) { function scan(ob) { var bag = [], i = 0, v, tag, mx = ob.childNodes.length; for(i; i < mx; i++) { v = ob.childNodes[i]; if(v.tagName) { // recurse sub-tags if any tag = { $: v.tagName.toLowerCase() }; for(var i2 = 0, va = v.attributes, attr, mx2 = va.length; i2 < mx2; i2++) { attr = va[i2]; tag[attr.name] = attr.value; } tag._=scan(v); bag.push(tag); } else { //if sub tags? no: bag.push(v.nodeValue); } } return bag; } // end scan() if(typeof source === "string") { return parseHT(source); } else { return scan({ tagName: containerTagName||"div", attributes: [], childNodes: [source] })[0]; } } //end fromHTML var entities={'&quot;':'"', '&amp;':"&", '&lt;':'<', '&gt;': '>', '&apos;': "'"}; ("nbsp,iexcl,cent,pound,curren,yen,brvbar,sect,uml,copy,ordf,laquo,not,shy,reg,macr,deg,plusmn,sup2,sup3,acute,micro,para,middot,cedil,sup1,ordm,raquo,"+ "frac14,frac12,frac34,iquest,Agrave,Aacute,Acirc,Atilde,Auml,Aring,AElig,Ccedil,Egrave,Eacute,Ecirc,Euml,Igrave,Iacute,Icirc,Iuml,ETH,Ntilde,Ograve,Oacute,"+ "Ocirc,Otilde,Ouml,times,Oslash,Ugrave,Uacute,Ucirc,Uuml,Yacute,THORN,szlig,agrave,aacute,acirc,atilde,auml,aring,aelig,ccedil,egrave,eacute,ecirc,euml,"+ "igrave,iacute,icirc,iuml,eth,ntilde,ograve,oacute,ocirc,otilde,ouml,divide,oslash,ugrave,uacute,ucirc,uuml,yacute,thorn,yuml").split(",").forEach(function(a,b,c){ this["&"+a+";"]= String.fromCharCode(160+b); }, entities); function parseHT(html) { "use strict"; var out = { $: "ROOT", _: [] }, parent = out, out2 = out, rxQuoteOpen = /^['"]/, rxQuoteClose = /['"]$/, rxWhite = /\s+/, rxTagNameEnd = /[\s>]/, tag = out, heap = html.split(/([<>])/), last = "", hint, token, index = 0, mx2 = heap.length, name, r, b = 1, mx, a, n, strAttribs, cap, val, key, attrValue, parents = [out], overlap, rxBooleanAttrib =/([\w\-]+)()/g , rxAttrVal = /([\w\-]+)=([^\s>\/]+)/g, rxAttribValQ = /([\w\-]+)="([^"]*)"/g, rxAttribValA = /([\w\-]+)='([^']*)'/g, rxs=[rxAttribValQ, rxAttribValA, rxAttrVal, rxBooleanAttrib]; function fnReppr(j, k, v, x, y){ tag[k]=v || ""; return ""; } // loop through all tag opening and closing tags in a flattened array: for(; index < mx2; index++) { token = heap[index]; hint = token.slice(0, 1); if(last === "<"){ if(hint === "/") { // handle closing tags: (return to parent, clear buffer); tag = parents.pop(); out = tag; last = ""; continue; } // handle opening tags by making new tag object and adding attribs and kids n=token.search(rxTagNameEnd); if(n===-1) n = 20; name=token.slice(0, n); strAttribs= token.slice(n); // save old tag to parent children collection: parents.push(out); // create a new tag object: out._.push(tag = { $: name, _: [] }); // add attribs: if(strAttribs) for(b=0; b<4; b++) strAttribs=strAttribs.replace(rxs[b], fnReppr ); if(singleTags[name]){ last=token; tag = parents.pop(); out = tag; continue; } // move "cursor" to this new tag: if(out !== tag) parent = out; out = tag; last = token; continue; }// end if tag opening? //if not tag open or close, must be content, add to cursor tag: if(token && !(token === "<" || token === ">") ) tag._.push( token.indexOf("&") === -1 ? token : token.replace(/(&\w+;)/g, function(j, a){ return entities[a] || a; })); // memorize current value for parser peek-behind to find closing tags: last = token; } return out2._[0]; }//end parseHT() function resolvePath(path, base) { var last = [], i=0, mx =path.length, out=base, u, k; for(i; i<mx; i++){ k = path[i]; if(k==="_") k="childNodes"; last.push(out); out = out[k]; if(out===u) break ; }; return { node: out, parents: last }; } function resolveAll(path, base) { var last = [], i=0, mx =path.length, out=base, u; for(i; i<mx; i++){ last.push(out); out = out[path[i]]; if(out===u) break ; }; return { node: out, parents: last }; } var singleTags={area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1}; function toHT(obj) { var attribs = "", r = [], tn, kids, u, a, i, o, mx, own = r.hasOwnProperty; if(obj === u) return ""; tn=obj.$; // build attribs from values and functions: for(a in obj) if( a !== "$" && a !== "_" && own.call(obj, a) ) attribs += (" " + a) + ((obj[a] === "") ? "" : ("=" + JSON.stringify(obj[a]))); if(singleTags[tn]) return "<" + tn + attribs + " />"; kids = obj._ || []; if(kids && !Array.isArray(kids)) kids = [kids]; for(i = 0, o, mx = kids.length; i < mx; i++) { o = kids[i]; // || ""; r[i] = typeof o === "object" ? toHT(o) : o; } return "<" + tn + attribs + ">" + r.join("") + "</" + tn + ">"; } //given a change array, applies the changes to the element that's rendering the vdom: function applyChanges(change, INDEX, ALLS, that) { var time = that.timing, startTime = time ? performance.now() : 0, bug = that.debug, path = filter(change.path.concat(change.index || change.key), function _pathFilterer(a, b, c) { return a != b.xsdgdfg; }), slice = path.slice, lastChange = ALLS[INDEX - 1] || "", key = filter(path, function _keyFilterer(a, b, c) { return a != b.xsdgdfg; }).slice(-1)[0], elm = resolvePath(path, that.dest), parents = resolveAll(path, that.vdom), elmPar = filter(elm.parents, Boolean), ochange = { type: change.type, index: INDEX, path: path, key: key, elm: elm.node || elm.parents.slice(-1)[0], elmParents: elmPar, elmParent: elmPar.slice(-1)[0], dest: that.dest, parents: parents, parent: parents.parents.slice(-1)[0], isAttrib: !(key - 0.1) && key != "_" && key != "$", change: change }, attrs, a, mx, i, it, kids, temp, content, ext, cp, cc, vals, val, old; if(typeof ochange.elm == "function") ochange.elm = ochange.elmParent; if(bug) console.info("CHANGE: " + INDEX, ochange); function _setStrParFinder(a, b, c) {return a.textContent !== a.fsdhjklghdklg;} switch(change.type) { case "set": if(!ochange.isAttrib && (typeof change.val === "string" || Array.isArray(change.val))) { cp = ochange.elm; if(!ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent[ochange.key]; if(!ochange.elm) ochange.elm = ochange.elmParent; vals = change.val; if(!Array.isArray(vals)) vals = [vals]; for(var valIndex = 0, maxIndex = vals.length; valIndex < maxIndex; valIndex++) { val = vals[valIndex]; if(typeof val === "string") { //add text nodes: if(ochange.elm instanceof NodeList) ochange.elm = filter(ochange.elmParents, _setStrParFinder ).pop(); if(ochange.elm.childNodes) { if(bug) console.log("set: non attrib, string, elm: ", ochange.key, [val], ochange.elm.outerHTML); content = document.createTextNode(val); if(ochange.key === "_") { ochange.elm.textContent = val; } else { if(ochange.key === "$") { temp = document.createElement(change.val); if(bug) console.warn("changing tag name!", change); ochange.elm.parentNode.insertBefore(temp, ochange.elm); attrs = ochange.elm.attributes; for(i = 0, mx = attrs.length; i < mx; i++) { a = attrs[i]; temp.setAttribute(a.name, a.value); } kids = ochange.elm.childNodes; for(i = 0, mx = kids.length; i < mx; i++) temp.appendChild(kids[0]); ochange.elm.parentNode.removeChild(ochange.elm); } else { ochange.elm.parentNode.insertBefore(content, ochange.elm); ochange.elm.parentNode.removeChild(ochange.elm); } } change.elm = content; } else { if(bug) console.log("set: non attrib, string, not elm", val); ochange.elm.textContent = val; //update element change.elm = ochange.elm; } } else { //add elms: content = typeof val === "string" ? document.createTextNode(val) : elementFromString(toHT(val), ochange.elmParent[0] && ochange.elmParent[0].parentNode.tagName).firstChild; if(!ochange.elm.parentNode) ochange.elm = ochange.elmParent; old = ochange.elm.childNodes[+key + valIndex]; if(old) { if(bug) console.log("set: non attrib, not string, has old", val); ochange.elm.insertBefore(content, old); ochange.elm.removeChild(ochange.elm); } else { if(bug) console.log("set: non attrib, not string, no old, appending", [val, content, content.outerHTML || content.textContent]); ochange.elm.appendChild(content); } } if(key == "_") { key = 0; if(!ochange.parent.length) ochange.parent = (ochange.parent._ || (ochange.parent._ = [])); } if(bug) console.info("attempting key change", + key + valIndex, !! (1.1 - key), key, valIndex, val, ochange.parent[+key + valIndex], [ochange.parent]); } break; } if(ochange.isAttrib) { if(key == "$" && String(path) == key) throw new TypeError("You cannot change the root element of an update-bound element: " + ochange.elm.outerHTML); if(key == "$") { temp = document.createElement(change.val); if(bug) console.warn("changing tag name!", change); ochange.elm.parentNode.insertBefore(temp, ochange.elm); attrs = ochange.elm.attributes; for(i = 0, mx = attrs.length; i < mx; i++) { a = attrs[i]; temp.setAttribute(a.name, a.value); } kids = ochange.elm.childNodes; for(i = 0, mx = kids.length; i < mx; i++) temp.appendChild(kids[0]); change.elm = temp; ochange.elm.parentNode.removeChild(ochange.elm); } else { if(!ochange.elm.setAttribute && ochange.elm.parentNode && ochange.elm.parentNode.setAttribute) { ochange.elm = ochange.elm.parentNode; } if(!ochange.elm.setAttribute && (cc = filter(ochange.elmParents, function _setParFinderCC(a, b, c) { return a.setAttribute; }).slice(-1)[0]).setAttribute) { ochange.elm = cc; } if(change.val === change.dgfjkdfl34534fd) { ochange.elm.removeAttribute(key); //update element } else { ochange.elm.setAttribute(key, change.val); //update element } change.elm = ochange.elm; } break; } if(ochange.elm.length && change.val === change.sdgfdf) { for(var i6 = 0, mx6 = ochange.elm.length; i6 < mx6; i6++) ochange.elm[0].parentNode.removeChild(ochange.elm[0]); } else { if(ochange.elm instanceof NodeList) ochange.elm = filter(ochange.elmParents, function _setParFinder(a, b, c) { return a.textContent !== a.fsdhjklghdklg; }).pop(); temp = elementFromString(toHT(change.val), ochange.parent.$).firstChild; if(bug) console.log("element replacing", [ochange.elm.outerHTML || ochange.elm.textContent], " with ", [temp.outerHTML]); change.elm = temp; ochange.elm.parentNode.insertBefore(temp, ochange.elm); ochange.elm.parentNode.removeChild(ochange.elm); } break; case "add": if(!ochange.isAttrib) { if(ochange.key == "_") { ochange.elm = ochange.elm[change.index]; ochange.key = change.index; ochange.parent = ochange.parent._; ochange.elmParent = ochange.elmParent.childNodes; } forEach(change.vals, function _valUpdater(val, i, arrWhole) { if(!ochange.elmParent.length) ochange.elmParent = ochange.elmParents.slice(-1)[0].childNodes; if(!ochange.elmParent) ochange.elmParent = ochange.elmParents.slice(-2)[0].childNodes; content = typeof val === "string" ? document.createTextNode(val) : elementFromString(toHT(val), ochange.elmParent[0] && ochange.elmParent[0].parentNode.tagName).firstChild; ext = ochange.elmParent[ochange.key + i]; change.elm = content; if(ext) { ext.parentNode.insertBefore(content, ext); ochange.parent.splice(ochange.key + i, 0, val); } else { if(ochange.elmParent[ochange.key + i]) { ochange.elmParent[ochange.key + i] = content; } else { it = ochange.elmParents.slice(-1)[0]; if(it[0]) it = it[it.length - 1]; if(ochange.elm && ochange.elm.length >= ochange.key) it = ochange.elm[0].parentNode; if(it instanceof NodeList) it = filter(ochange.elmParents, function _addParFinder(a, b, c) { return a.textContent !== a.fsdhjklghdklg; }).pop(); if(it !== content) { if(it.nodeType != 3) { it.appendChild(content); } else { it.parentNode.insertBefore(content, it); it.parentNode.insertBefore(it, content); } } } } }); } break; case "rm": if(ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent.childNodes; if(ochange.elmParent.length === 0) ochange.elmParent = ochange.elmParents.slice(-3)[0]; if(ochange.elmParent.childNodes) ochange.elmParent = ochange.elmParent.childNodes; if(ochange.parent._) ochange.parent = ochange.parent._; // list out what to remove: var min = change.index - change.num, max = change.index, toRemove = slice.call(ochange.elmParent, min + 1, max + 1); if(change.index === 0) { // it starts at zero, the odiff range goes positive instead of couring backwards from 0: if(bug) console.log("removing many from zero", slice.call(ochange.parent), ochange.elmParent, "|||", ochange.parent[0], change.index, change.num); for(i = change.index, mx = i + change.num; i < mx; i++) { ochange.elmParent[change.index].remove(); } change.elm = ochange.elmParent; } else { if(change.index - change.num > -1) { if(change.num === 1) { toRemove = [ochange.elmParent[change.index]]; if(bug) console.log("removing one", ochange.elmParent, toRemove[0].outerHTML, change.index, slice.call(ochange.elmParent).map(function _removeOneConsoleMapper(a) { return a.outerHTML || a.nodeValue; }), ochange.parent); } else { if(change.index + change.num < ochange.elmParent.length + 1) { var ind = change.index; if(ind > 1 && change.mode === "Z") ind = ind - (change.num - 1); if(bug) console.log("removing many up", change.mode, ochange.elmParent, ind, ind + change.num); toRemove = slice.call(ochange.elmParent, ind, ind + change.num); } else { //count backwards: if(bug) console.log("removing many down", slice.call(ochange.elmParent), change.index - change.num, change.index); toRemove = slice.call(ochange.elmParent, (change.index - change.num) + 1, (change.index) + 1); } } } else { if(bug) console.log("removing many negative", ochange.elmParent, change.index, change.index + change.num); toRemove = slice.call(ochange.elmParent, change.index, change.index + change.num); } if(toRemove.length) change.elm = toRemove[0].parentNode; if(bug) console.log("removing:", toRemove, change, ochange.parent.slice((change.index - change.num) + 1, (change.index) + 1)); forEach(toRemove, function _toRemover(a, b, c) { a.parentNode.removeChild(a); }); } break; } if(time) change.runtime = performance.now() - startTime; } //end applyChanges() function getRenderer(dest, vdom, hint) { if(typeof dest === "string") dest = document.querySelector(dest); var it= intraHTML.timing ? performance.now() : 0, tag=dest.tagName.toLowerCase(), head="<"+tag+">", ht, st, state; if(!dest.childNodes.length) dest.innerHTML = " "; if(!vdom) vdom = dest; if(vdom instanceof Element){ ht=vdom.innerHTML; if(hint === ht) return {update: Boolean}; vdom = fromHTML(head + ht + "</" + tag + ">", tag); // actually faster using outerHTML than feeding it a dom node (dest, which works). confirm that widely... } if(typeof vdom === "string" ) vdom = fromHTML(vdom, tag); st= intraHTML.timing ? performance.now() : 0; state = { dest: dest, vdom: vdom, debug: intraHTML.debug, timing : intraHTML.timing, initTime: st-it, update: function(vdom) { var blnTime=intraHTML.timing, st, i=0, mx; if(blnTime) st=performance.now(); if(typeof vdom === "string") vdom = fromHTML(head + vdom + "</" + tag + ">", tag); if(blnTime) state.parseTime= (performance.now() - st); state.vdom2 = vdom; if(blnTime) st=performance.now(); state.changes = odiff(state.vdom, vdom); if(blnTime){ state.diffTime= performance.now() - st; st=performance.now(); } for(mx=state.changes.length;i<mx;i++) applyChanges(state.changes[i], i, state.changes, state); if(blnTime) state.applyTime= performance.now() - st; state.vdom = vdom; return state; } }; return state; } //the return/module value/main routine: function intraHTML(elm, content){ return intraHTML._last=getRenderer(elm, elm, content), intraHTML._last.update(content); } // publish useful internal helper methods: intraHTML.applyChanges = applyChanges; intraHTML.elementFromString=elementFromString; intraHTML.fromHTML = fromHTML; intraHTML.toHTML = toHT; intraHTML.odiff=odiff; intraHTML.parseHTML=parseHT; intraHTML.updater=getRenderer; intraHTML.getRenderer = getRenderer; //publish external options: intraHTML.timing = true; intraHTML.debug = false; intraHTML.entities =entities; // jQuery plugin: if(pub.jQuery) pub.jQuery.fn.intraHTML=function(strContent){ this.each(function jqiht(i,e){ intraHTML(e, strContent);}); return this; }; return intraHTML; }));
strip HTML comments from vdom for perf/compat
intrahtml.js
strip HTML comments from vdom for perf/compat
<ide><path>ntrahtml.js <ide> <ide> function parseHT(html) { <ide> "use strict"; <add> <add> html=String(html).replace(/<\!\-\-[\s\S]+?\-\->/g,""); <add> <ide> var out = { <ide> $: "ROOT", <ide> _: []
JavaScript
mit
17db7e90dc1efb4ecc20c48043f5b913fb2d6907
0
LasaulecBV/compoxure,LasaulecBV/compoxure,tes/compoxure,tes/compoxure
var htmlparser = require("htmlparser2"); var fs = require('fs'); var _ = require('lodash'); var Hogan = require('hogan.js'); var utils = require('../utils'); var Stream = require('stream').Stream; var through = require('through'); var getThenCache = require('../getThenCache'); var errorTemplate = "<div style='color: red; font-weight: bold; font-family: monospace;'>Error: <%= err %></div>"; module.exports = HtmlParserProxy; function HtmlParserProxy(config, cache, eventHandler) { if (!(this instanceof HtmlParserProxy)) return new HtmlParserProxy(config, cache, eventHandler); this.config = config; this.cache = cache; this.eventHandler = eventHandler; this.hoganCache = {}; return this; }; HtmlParserProxy.prototype.render = function(text, data) { var self = this; if(!this.hoganCache[text]) { this.hoganCache[text] = Hogan.compile(text); } return this.hoganCache[text].render(data); } HtmlParserProxy.prototype.middleware = function(req, res, next) { var self = this, output = [], outputIndex = 0, fragmentIndex = 0, fragmentOutput = [], nextTextDefault = false, skipClosingTag = false; output[outputIndex] = ""; req.timerStart = Date.now(); res.transformer = { end: function(data) { parser.end(data); } }; var parser = new htmlparser.Parser({ onopentag: function(tagname, attribs) { if(attribs && attribs['cx-url']) { if(attribs['cx-replace-outer']) { skipClosingTag = true; } else { output[outputIndex] += utils.createTag(tagname, attribs); } outputIndex ++; output[outputIndex] = "_processing_"; fragmentOutput[fragmentIndex] = attribs; fragmentOutput[fragmentIndex].outputIndex = outputIndex; fragmentOutput[fragmentIndex].fragmentIndex = fragmentIndex; nextTextDefault = true; getCx(fragmentOutput[fragmentIndex], function(fragment, response) { output[fragment.outputIndex] = response; fragment.done = true; }); outputIndex ++; fragmentIndex ++; output[outputIndex] = ""; } else if(attribs && attribs['cx-test']) { output[outputIndex] += utils.createTag(tagname, attribs); output[outputIndex] += self.render(attribs['cx-test'], req.templateVars); } else { output[outputIndex] += utils.createTag(tagname, attribs); } }, onprocessinginstruction: function(name, data) { output[outputIndex] += "<" + data + ">"; }, ontext:function(data) { if(nextTextDefault) { // Set Default value - provided it hasn't already been set // When using memory cache it could actually retrieve a value // Faster than the ontext event fired from this library nextTextDefault = false; if(output[outputIndex-1] == "_processing_") output[outputIndex-1] = data; } else { output[outputIndex] += data; } }, oncomment: function(data) { output[outputIndex] += "<!-- " + data }, oncommentend: function() { output[outputIndex] += " -->" }, onclosetag: function(tagname){ if(nextTextDefault) nextTextDefault = false; if(skipClosingTag) { skipClosingTag = false; return; } output[outputIndex] += "</" + tagname + ">"; }, onend: function(){ var timeoutStart = Date.now(), timeout = utils.timeToMillis(req.backend.timeout || "5s"); function checkDone() { var done = true, outputHTML = ""; for (var i = 0, len = fragmentOutput.length; i < len; i++) { done = done && fragmentOutput[i].done; } if(done) { for (var i = 0, len = output.length; i < len; i++) { outputHTML += output[i]; } var responseTime = Date.now() - req.timerStart; self.eventHandler.logger('info', "Page composer response completed", {tracer: req.tracer,responseTime: responseTime}); self.eventHandler.stats('timing','responseTime',responseTime); res.end(outputHTML); } else { if((Date.now() - timeoutStart) > timeout) { res.writeHead(500, {"Content-Type": "text/html"}); var errorMsg = 'Compoxure failed to respond in <%= timeout %>ms. Failed to respond: '; for (var i = 0, len = fragmentOutput.length; i < len; i++) { if(!fragmentOutput[i].done) { errorMsg += ' ' + self.render(fragmentOutput[i]['cx-url'], req.templateVars) + '.'; } } res.end(_.template(errorMsg)({timeout:timeout})); } else { setTimeout(checkDone,1); } } } checkDone(); }, recognizeSelfClosing: true }); function getCx(node, next) { var options = {}, start = Date.now(), templateVars = _.clone(req.templateVars); options.unparsedUrl = node['cx-url']; options.url = self.render(node['cx-url'], templateVars); options.timeout = utils.timeToMillis(node['cx-timeout'] || "1s"); options.cacheKey = self.render(node['cx-cache-key'] || node['cx-url'], templateVars); options.cacheTTL = utils.timeToMillis(node['cx-cache-ttl'] || "1m"); options.explicitNoCache = node['cx-no-cache'] ? self.render(node['cx-no-cache'], templateVars) === "true" : false; options.ignore404 = node['cx-ignore-404'] === "true"; options.type = 'fragment'; options.cache = (options.cacheTTL > 0); options.headers = { 'cx-page-url': templateVars['url:href'] }; if (typeof req.headers.cookie !== 'undefined') { options.headers.cookie = req.headers.cookie; } options.tracer = req.tracer; options.statsdKey = 'fragment_' + (node['cx-statsd-key'] || 'unknown'); if (self.config.cdn) { if(self.config.cdn.host) options.headers['x-cdn-host'] = self.config.cdn.host; if(self.config.cdn.url) options.headers['x-cdn-url'] = self.config.cdn.url; } var responseStream = { end: function(data) { next(node, data); } }; getThenCache(options, self.config, self.cache, self.eventHandler, responseStream, onErrorHandler); function onErrorHandler(err, oldContent) { var errorMsg; if (err.statusCode === 404 && !options.ignore404) { res.writeHead(404, {"Content-Type": "text/html"}); errorMsg = _.template('404 Service <%= url %> cache <%= cacheKey %> returned 404.'); self.eventHandler.logger('error', errorMsg({url: options.url, cacheKey: options.cacheKey}), {tracer:req.tracer}); res.end(errorMsg(options)); } else { if(!req.backend.quietFailure) { var msg = _.template(errorTemplate); responseStream.end(msg({ 'err': err.message })); } else { if(oldContent) { responseStream.end(oldContent); errorMsg = _.template('STALE <%= url %> cache <%= cacheKey %> failed but serving stale content.'); self.eventHandler.logger('error', errorMsg(options), {tracer:req.tracer}); } else { responseStream.end(req.backend.leaveContentOnFail ? output[node.outputIndex] : "" ); } } self.eventHandler.stats('increment', options.statsdKey + '.error'); var elapsed = Date.now() - req.timerStart, timing = Date.now() - start; errorMsg = _.template('FAIL <%= url %> did not respond in <%= timing%>, elapsed <%= elapsed %>. Reason: ' + err.message); self.eventHandler.logger('error', errorMsg({url: options.url, timing: timing, elapsed: elapsed}), {tracer:req.tracer}); } } } next(); }
src/middleware/htmlparser.js
var htmlparser = require("htmlparser2"); var fs = require('fs'); var _ = require('lodash'); var Hogan = require('hogan.js'); var utils = require('../utils'); var Stream = require('stream').Stream; var through = require('through'); var getThenCache = require('../getThenCache'); var errorTemplate = "<div style='color: red; font-weight: bold; font-family: monospace;'>Error: <%= err %></div>"; module.exports = HtmlParserProxy; function HtmlParserProxy(config, cache, eventHandler) { if (!(this instanceof HtmlParserProxy)) return new HtmlParserProxy(config, cache, eventHandler); this.config = config; this.cache = cache; this.eventHandler = eventHandler; this.hoganCache = {}; return this; }; HtmlParserProxy.prototype.render = function(text, data) { var self = this; if(!this.hoganCache[text]) { this.hoganCache[text] = Hogan.compile(text); } return this.hoganCache[text].render(data); } HtmlParserProxy.prototype.middleware = function(req, res, next) { var self = this, output = [], outputIndex = 0, fragmentIndex = 0, fragmentOutput = [], nextTextDefault = false, skipClosingTag = false; output[outputIndex] = ""; req.timerStart = Date.now(); res.transformer = { end: function(data) { parser.end(data); } }; var parser = new htmlparser.Parser({ onopentag: function(tagname, attribs) { if(attribs && attribs['cx-url']) { if(attribs['cx-replace-outer']) { skipClosingTag = true; } else { output[outputIndex] += utils.createTag(tagname, attribs); } outputIndex ++; output[outputIndex] = "_processing_"; fragmentOutput[fragmentIndex] = attribs; fragmentOutput[fragmentIndex].outputIndex = outputIndex; fragmentOutput[fragmentIndex].fragmentIndex = fragmentIndex; nextTextDefault = true; getCx(fragmentOutput[fragmentIndex], function(fragment, response) { output[fragment.outputIndex] = response; fragment.done = true; }); outputIndex ++; fragmentIndex ++; output[outputIndex] = ""; } else if(attribs && attribs['cx-test']) { output[outputIndex] += utils.createTag(tagname, attribs); output[outputIndex] += self.render(attribs['cx-test'], req.templateVars); } else { output[outputIndex] += utils.createTag(tagname, attribs); } }, onprocessinginstruction: function(name, data) { output[outputIndex] += "<" + data + ">"; }, ontext:function(data) { if(nextTextDefault) { // Set Default value - provided it hasn't already been set // When using memory cache it could actually retrieve a value // Faster than the ontext event fired from this library nextTextDefault = false; if(output[outputIndex-1] == "_processing_") output[outputIndex-1] = data; } else { output[outputIndex] += data; } }, oncomment: function(data) { output[outputIndex] += "<!-- " + data }, oncommentend: function() { output[outputIndex] += " -->" }, onclosetag: function(tagname){ if(nextTextDefault) nextTextDefault = false; if(skipClosingTag) { skipClosingTag = false; return; } output[outputIndex] += "</" + tagname + ">"; }, onend: function(){ var timeoutStart = Date.now(), timeout = utils.timeToMillis(req.backend.timeout || "5s"); function checkDone() { var done = true, outputHTML = ""; for (var i = 0, len = fragmentOutput.length; i < len; i++) { done = done && fragmentOutput[i].done; } if(done) { for (var i = 0, len = output.length; i < len; i++) { outputHTML += output[i]; } var responseTime = Date.now() - req.timerStart; self.eventHandler.logger('info', "Page composer response completed", {tracer: req.tracer,responseTime: responseTime}); self.eventHandler.stats('timing','responseTime',responseTime); res.end(outputHTML); } else { if((Date.now() - timeoutStart) > timeout) { res.writeHead(500, {"Content-Type": "text/html"}); var errorMsg = 'Compoxure failed to respond in <%= timeout %>ms. Failed to respond: '; for (var i = 0, len = fragmentOutput.length; i < len; i++) { if(!fragmentOutput[i].done) { errorMsg += ' ' + self.render(fragmentOutput[i]['cx-url'], req.templateVars) + '.'; } } res.end(_.template(errorMsg)({timeout:timeout})); } else { setTimeout(checkDone,1); } } } checkDone(); }, recognizeSelfClosing: true }); function getCx(node, next) { var options = {}, start = Date.now(), templateVars = _.clone(req.templateVars); options.unparsedUrl = node['cx-url']; options.url = self.render(node['cx-url'], templateVars); options.timeout = utils.timeToMillis(node['cx-timeout'] || "1s"); options.cacheKey = self.render(node['cx-cache-key'] || node['cx-url'], templateVars); options.cacheTTL = utils.timeToMillis(node['cx-cache-ttl'] || "1m"); options.explicitNoCache = node['cx-no-cache'] ? self.render(node['cx-no-cache'], templateVars) === "true" : false; options.ignore404 = node['cx-ignore-404'] === "true"; options.type = 'fragment'; options.cache = (options.cacheTTL > 0); options.headers = { 'cx-page-url': templateVars['param:pageUrl'] }; options.headers.cookie = req.headers.cookie; options.tracer = req.tracer; options.statsdKey = 'fragment_' + (node['cx-statsd-key'] || 'unknown'); if (self.config.cdn) { if(self.config.cdn.host) options.headers['x-cdn-host'] = self.config.cdn.host; if(self.config.cdn.url) options.headers['x-cdn-url'] = self.config.cdn.url; } var responseStream = { end: function(data) { next(node, data); } }; getThenCache(options, self.config, self.cache, self.eventHandler, responseStream, onErrorHandler); function onErrorHandler(err, oldContent) { var errorMsg; if (err.statusCode === 404 && !options.ignore404) { res.writeHead(404, {"Content-Type": "text/html"}); errorMsg = _.template('404 Service <%= url %> cache <%= cacheKey %> returned 404.'); self.eventHandler.logger('error', errorMsg({url: options.url, cacheKey: options.cacheKey}), {tracer:req.tracer}); res.end(errorMsg(options)); } else { if(!req.backend.quietFailure) { var msg = _.template(errorTemplate); responseStream.end(msg({ 'err': err.message })); } else { if(oldContent) { responseStream.end(oldContent); errorMsg = _.template('STALE <%= url %> cache <%= cacheKey %> failed but serving stale content.'); self.eventHandler.logger('error', errorMsg(options), {tracer:req.tracer}); } else { responseStream.end(req.backend.leaveContentOnFail ? output[node.outputIndex] : "" ); } } self.eventHandler.stats('increment', options.statsdKey + '.error'); var elapsed = Date.now() - req.timerStart, timing = Date.now() - start; errorMsg = _.template('FAIL <%= url %> did not respond in <%= timing%>, elapsed <%= elapsed %>. Reason: ' + err.message); self.eventHandler.logger('error', errorMsg({url: options.url, timing: timing, elapsed: elapsed}), {tracer:req.tracer}); } } } next(); }
Fixed an issue where empty headers were being passed as 'undefined'
src/middleware/htmlparser.js
Fixed an issue where empty headers were being passed as 'undefined'
<ide><path>rc/middleware/htmlparser.js <ide> fragmentIndex ++; <ide> output[outputIndex] = ""; <ide> <del> } else if(attribs && attribs['cx-test']) { <add> } else if(attribs && attribs['cx-test']) { <ide> output[outputIndex] += utils.createTag(tagname, attribs); <ide> output[outputIndex] += self.render(attribs['cx-test'], req.templateVars); <ide> } else { <ide> options.ignore404 = node['cx-ignore-404'] === "true"; <ide> options.type = 'fragment'; <ide> options.cache = (options.cacheTTL > 0); <add> <ide> options.headers = { <del> 'cx-page-url': templateVars['param:pageUrl'] <add> 'cx-page-url': templateVars['url:href'] <ide> }; <del> options.headers.cookie = req.headers.cookie; <add> <add> if (typeof req.headers.cookie !== 'undefined') { <add> options.headers.cookie = req.headers.cookie; <add> } <add> <ide> options.tracer = req.tracer; <ide> options.statsdKey = 'fragment_' + (node['cx-statsd-key'] || 'unknown'); <ide> <ide> if(self.config.cdn.host) options.headers['x-cdn-host'] = self.config.cdn.host; <ide> if(self.config.cdn.url) options.headers['x-cdn-url'] = self.config.cdn.url; <ide> } <del> <add> <ide> var responseStream = { <ide> end: function(data) { <ide> next(node, data);
JavaScript
mit
bbfc51485f50d8fb16db623ad2b4ed0b72cdc3ac
0
andreoliva/dnd.js,andreoliva/dnd.js
/** DND Version 1.0 Developed by: André H. Oliva Copyright 2014 */ window.dnd = (function () { var currentData; var scale = 1; var configs = {}; var dndCount = 0; //----------------------------------------------------------------------------DND library constructor function DND (els) { for(var i = 0; i < els.length; i++ ) { this[i] = els[i]; } this.length = els.length; }; //----------------------------------------------------------------------------Calls callback to all selected elements DND.prototype.map = function (callback) { var results = [], i = 0; for ( ; i < this.length; i++) { results.push(callback.call(this, this[i], i)); } return results; }; DND.prototype.forEach = function(callback) { this.map(callback); return this; }; //----------------------------------------------------------------------------DND methods DND.prototype.initDraggable = function(params) { params = params || {}; return this.map(function(el){ configs[dndCount] = { onStart: (typeof(params.onStart) !== 'undefined') ? params.onStart : null, onDrag: (typeof(params.onDrag) !== 'undefined') ? params.onDrag : null, onDrop: (typeof(params.onDrop) !== 'undefined') ? params.onDrop : null, parent: (typeof(params.parent) !== 'undefined') ? params.parent : document.body, centralize: (typeof(params.centralize) !== 'undefined') ? params.centralize : false, clone: (typeof(params.clone) !== 'undefined') ? params.clone : false, revert: (typeof(params.revert) !== 'undefined') ? params.revert : -1, originalElement: el, originalCoords: { x: el.getBoundingClientRect().left, y: el.getBoundingClientRect().top }, grabPoint: { x: 0, y: 0 }, dragElement: null, dropTarget: null }; if(params.onCreate) params.onCreate(); el.setAttribute('data-drag-id', dndCount); el.addEventListener('mousedown', (params.clone) ? CreateClone : Grab); el.addEventListener('touchstart', (params.clone) ? CreateClone : Grab); el.addEventListener('touchend', Drop); dndCount++; }); }; DND.prototype.removeDraggable = function() { return this.map(function(el){ el.removeEventListener('mousedown', CreateClone); el.removeEventListener('touchstart', CreateClone); el.removeEventListener('mousedown', Grab); el.removeEventListener('touchstart', Grab); el.removeEventListener('touchend', Drop); delete configs[el.getAttribute('data-drag-id')]; el.removeAttribute('data-drag-id'); }); }; DND.prototype.option = function(key, val) { this.map(function(el){ var id = el.getAttribute('data-drag-id'); configs[id][key] = val; }) return this; }; DND.prototype.destroyElement = function() { return this.map(function(el){ var id = el.getAttribute('data-drag-id'); if (id !== null){ var data = configs[id]; delete configs[id]; if (data.dragElement !== data.originalElement && data.dragElement !== null){ if(data.originalElement.parentNode) data.originalElement.parentNode.removeChild(data.originalElement); if(data.dragElement.parentNode) data.dragElement.parentNode.removeChild(data.dragElement); } else { if(data.originalElement.parentNode) data.originalElement.parentNode.removeChild(data.originalElement); } } else { el.parentNode.removeChild(el); } }); } //----------------------------------------------------------------------------Drag'n'drop control functions function CreateClone(e){ e.preventDefault(); if (e.type == 'touchstart') e = e.touches[0]; var evtTarget = (e.target.getAttribute('data-drag-id') == null) ? findDraggableParent(e.target) : e.target; currentData = configs[evtTarget.getAttribute('data-drag-id')]; currentData.originalElement = evtTarget; var pos = (currentData.centralize) ? { top: (e.clientY/scale) - (parseInt(window.getComputedStyle(evtTarget).height)/2), left: (e.clientX/scale) - (parseInt(window.getComputedStyle(evtTarget).width)/2) } : { top: evtTarget.getBoundingClientRect().top, left: evtTarget.getBoundingClientRect().left } ; var clone = evtTarget.cloneNode(true); clone.className += (clone.className) ? " cloned-piece" : "cloned-piece"; clone.style.position = 'absolute'; clone.style.top = pos.top + 'px'; clone.style.left = pos.left + 'px'; clone.style.margin = '0px'; currentData.parent.appendChild(clone); currentData.dragElement = clone; if(currentData.onStart) { currentData.onStart(e); } evtTarget.style.opacity = 0; Grab(e, clone); }; function Grab(e, target){ if (e.type == 'touchstart'){ e.preventDefault(); e = e.touches[0]; } var evtTarget = (e.target.getAttribute('data-drag-id') == null) ? findDraggableParent(e.target) : e.target; currentData = configs[evtTarget.getAttribute('data-drag-id')]; currentData.originalCoords = { x: evtTarget.getBoundingClientRect().left, y: evtTarget.getBoundingClientRect().top }; currentData.dragElement = target || evtTarget; if(!currentData.clone && currentData.onStart) { currentData.onStart(e); } currentData.grabPoint.x = e.clientX / scale; currentData.grabPoint.y = e.clientY / scale; document.addEventListener('mouseup', Drop); document.addEventListener('mousemove', Drag); document.addEventListener('touchmove', Drag); }; function Drag(e){ e.preventDefault(); if (e.type == 'touchmove') e = e.changedTouches[0]; var newX = (e.clientX / scale) - currentData.grabPoint.x; var newY = (e.clientY / scale) - currentData.grabPoint.y; newY += (newY == 0) ? 0.001 : 0; setCSSTransform(currentData.dragElement, 'translate(' + newX + 'px,' + newY + 'px)'); if(currentData.onDrag) { currentData.onDrag(e); } }; function Drop(e){ e.preventDefault(); if (e.type == 'touchend') e = e.changedTouches[0]; document.removeEventListener('mousemove', Drag); document.removeEventListener('touchmove', Drag); document.removeEventListener('mouseup', Drop); currentData.originalElement.removeEventListener('touchend', Drop); currentData.dragElement.style.display = 'none'; currentData.dropTarget = document.elementFromPoint(e.clientX, e.clientY); currentData.dragElement.style.display = 'block'; currentData.grabPoint = { x : 0, y : 0 }; if (currentData.dropTarget == currentData.originalElement) currentData.dropTarget = currentData.originalElement.parentNode; if(currentData.onDrop){ if(currentData.onDrop(e)) return; } if (currentData.revert >= 0) RevertDrag(currentData); else PlaceDrag(currentData); }; //----------------------------------------------------------------------------Revert draggable to initial point function RevertDrag(d, callback){ d.dragElement.style.top = d.originalCoords.y / scale + 'px'; d.dragElement.style.left = d.originalCoords.x / scale + 'px'; if (d.revert > 0){ var str = (d.revert/1000) + "s"; setCSSTransition(d.dragElement, str); setTimeout(function(){setCSSTransform(d.dragElement, 'translate(0px,0px)')}, 1); d.revertCallback = callback; d.dragElement.addEventListener('transitionend', TransitionEnd); d.dragElement.addEventListener('webkitTransitionEnd', TransitionEnd); d.dragElement.addEventListener('oTransitionEnd', TransitionEnd); } else { setCSSTransform(d.dragElement, 'translate(0px,0px)'); TransitionEnd({target: d.dragElement}); } }; function TransitionEnd(e){ e.target.removeEventListener('transitionend', TransitionEnd); e.target.removeEventListener('webkitTransitionEnd', TransitionEnd); e.target.removeEventListener('oTransitionEnd', TransitionEnd); var d = configs[e.target.getAttribute('data-drag-id')]; if (d.clone){ d.originalElement.style.opacity = 1; d.dragElement.parentNode.removeChild(d.dragElement); } else { setCSSTransition(d.dragElement, 'none'); } if(d.revertCallback) d.revertCallback(); d.dragElement = null; }; //-------------------------------------------------------------------------Place draggable at the drop point function PlaceDrag(d, callback){ var newCoords = { x: (d.dragElement.style.transform) ? parseInt(d.dragElement.style.transform.split('(').pop().split(',')[0]) * scale : 0, y: (d.dragElement.style.transform) ? parseInt(d.dragElement.style.transform.split('(').pop().split(',')[1]) * scale : 0 } var st = window.getComputedStyle(d.dropTarget, null); var tScale = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || 1; if(st.getPropertyValue('position') == 'static'){ d.dropTarget.style.position = 'relative'; }; if(tScale == 'none') tScale = 1; else tScale = parseFloat(tScale.split('(')[1].split(',')[0]); setCSSTransform(d.dragElement, 'translate(0px,0px)'); d.dragElement.style.position = 'absolute'; d.dragElement.style.margin = '0'; d.dragElement.style.top = (( (d.originalCoords.y + newCoords.y) - d.dropTarget.getBoundingClientRect().top) / tScale) / scale + 'px'; d.dragElement.style.left = (( (d.originalCoords.x + newCoords.x) - d.dropTarget.getBoundingClientRect().left) / tScale) / scale + 'px'; d.dropTarget.appendChild(d.dragElement); if(d.clone){ d.dragElement.addEventListener('mousedown', CreateClone); d.dragElement.addEventListener('touchstart', CreateClone); d.dragElement.addEventListener('touchend', Drop); d.dragElement.className = d.originalElement.className; d.originalElement.parentNode.removeChild(d.originalElement); } if(callback) callback(); }; //----------------------------------------------------------------------------Finding closest parent who is a valid drggable function findDraggableParent(el) { while (el.getAttribute('data-drag-id') == null){ el = el.parentNode; } return el } //----------------------------------------------------------------------------Style setting helpers function setCSSTransform(el, val) { el.style.transform = val; el.style.webkitTransform = val; el.style.mozTransform = val; el.style.msTransform = val; el.style.oTransform = val; }; function setCSSTransition(el, val) { el.style.transition = val; el.style.webkitTransition = val; el.style.mozTransition = val; el.style.msTransition = val; el.style.oTransition = val; }; //----------------------------------------------------------------------------Library object var dnd = { get: function (selector) { var els; if (typeof selector === 'string') els = document.querySelectorAll(selector); else if (selector.length) els = selector; else els = [selector]; return new DND(els); }, setScale: function(val) { scale = val; }, revertDrag: function(data, cb) { RevertDrag(data, cb); }, placeDrag: function(data, cb) { PlaceDrag(data, cb); }, getParentScale: function(el) { var st = window.getComputedStyle(el.parentNode, null); var tr = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || 'none'; return (tr == 'none') ? 1 : parseFloat(tr.split('(')[1].split(',')[0]); } }; return dnd; }());
dnd.js
/** DND Version 1.0 Developed by: André H. Oliva Copyright 2014 */ window.dnd = (function () { var currentData; var scale = 1; var configs = {}; var dndCount = 0; //----------------------------------------------------------------------------DND library constructor function DND (els) { for(var i = 0; i < els.length; i++ ) { this[i] = els[i]; } this.length = els.length; }; //----------------------------------------------------------------------------Calls callback to all selected elements DND.prototype.map = function (callback) { var results = [], i = 0; for ( ; i < this.length; i++) { results.push(callback.call(this, this[i], i)); } return results; }; DND.prototype.forEach = function(callback) { this.map(callback); return this; }; //----------------------------------------------------------------------------DND methods DND.prototype.initDraggable = function(params) { params = params || {}; return this.map(function(el){ configs[dndCount] = { onStart: (typeof(params.onStart) !== 'undefined') ? params.onStart : null, onDrag: (typeof(params.onDrag) !== 'undefined') ? params.onDrag : null, onDrop: (typeof(params.onDrop) !== 'undefined') ? params.onDrop : null, parent: (typeof(params.parent) !== 'undefined') ? params.parent : document.body, centralize: (typeof(params.centralize) !== 'undefined') ? params.centralize : false, clone: (typeof(params.clone) !== 'undefined') ? params.clone : false, revert: (typeof(params.revert) !== 'undefined') ? params.revert : -1, originalElement: el, originalCoords: { x: el.getBoundingClientRect().left, y: el.getBoundingClientRect().top }, grabPoint: { x: 0, y: 0 }, dragElement: null, dropTarget: null }; if(params.onCreate) params.onCreate(); el.setAttribute('data-drag-id', dndCount); el.addEventListener('mousedown', (params.clone) ? CreateClone : Grab); el.addEventListener('touchstart', (params.clone) ? CreateClone : Grab); el.addEventListener('touchend', Drop); dndCount++; }); }; DND.prototype.removeDraggable = function() { return this.map(function(el){ el.removeEventListener('mousedown', CreateClone); el.removeEventListener('touchstart', CreateClone); el.removeEventListener('mousedown', Grab); el.removeEventListener('touchstart', Grab); el.removeEventListener('touchend', Drop); delete configs[el.getAttribute('data-drag-id')]; el.removeAttribute('data-drag-id'); }); }; DND.prototype.option = function(key, val) { this.map(function(el){ var id = el.getAttribute('data-drag-id'); configs[id][key] = val; }) return this; }; DND.prototype.destroyElement = function() { return this.map(function(el){ var id = el.getAttribute('data-drag-id'); if (id !== null){ var data = configs[id]; delete configs[id]; if (data.dragElement !== data.originalElement && data.dragElement !== null){ if(data.originalElement.parentNode) data.originalElement.parentNode.removeChild(data.originalElement); if(data.dragElement.parentNode) data.dragElement.parentNode.removeChild(data.dragElement); } else { if(data.originalElement.parentNode) data.originalElement.parentNode.removeChild(data.originalElement); } } else { el.parentNode.removeChild(el); } }); } //----------------------------------------------------------------------------Drag'n'drop control functions function CreateClone(e){ e.preventDefault(); if (e.type == 'touchstart') e = e.touches[0]; var evtTarget = (e.target.getAttribute('data-drag-id') == null) ? findDraggableParent(e.target) : e.target; currentData = configs[evtTarget.getAttribute('data-drag-id')]; currentData.originalElement = evtTarget; var pos = (currentData.centralize) ? { top: (e.clientY/scale) - (parseInt(window.getComputedStyle(evtTarget).height)/2), left: (e.clientX/scale) - (parseInt(window.getComputedStyle(evtTarget).width)/2) } : { top: evtTarget.getBoundingClientRect().top, left: evtTarget.getBoundingClientRect().left } ; var clone = evtTarget.cloneNode(true); clone.className += (clone.className) ? " cloned-piece" : "cloned-piece"; clone.style.position = 'absolute'; clone.style.top = pos.top + 'px'; clone.style.left = pos.left + 'px'; clone.style.margin = '0px'; currentData.parent.appendChild(clone); currentData.dragElement = clone; if(currentData.onStart) { currentData.onStart(e); } evtTarget.style.opacity = 0; Grab(e, clone); }; function Grab(e, target){ if (e.type == 'touchstart'){ e.preventDefault(); e = e.touches[0]; } var evtTarget = (e.target.getAttribute('data-drag-id') == null) ? findDraggableParent(e.target) : e.target; currentData = configs[evtTarget.getAttribute('data-drag-id')]; currentData.originalCoords = { x: evtTarget.getBoundingClientRect().left, y: evtTarget.getBoundingClientRect().top }; currentData.dragElement = target || evtTarget; if(!currentData.clone && currentData.onStart) { currentData.onStart(e); } currentData.grabPoint.x = e.clientX / scale; currentData.grabPoint.y = e.clientY / scale; document.addEventListener('mouseup', Drop); document.addEventListener('mousemove', Drag); document.addEventListener('touchmove', Drag); }; function Drag(e){ e.preventDefault(); if (e.type == 'touchmove') e = e.changedTouches[0]; var newX = (e.clientX / scale) - currentData.grabPoint.x; var newY = (e.clientY / scale) - currentData.grabPoint.y; setCSSTransform(currentData.dragElement, 'translate(' + newX + 'px,' + newY + 'px)'); if(currentData.onDrag) { currentData.onDrag(e); } }; function Drop(e){ e.preventDefault(); if (e.type == 'touchend') e = e.changedTouches[0]; document.removeEventListener('mousemove', Drag); document.removeEventListener('touchmove', Drag); document.removeEventListener('mouseup', Drop); currentData.originalElement.removeEventListener('touchend', Drop); currentData.dragElement.style.display = 'none'; currentData.dropTarget = document.elementFromPoint(e.clientX, e.clientY); currentData.dragElement.style.display = 'block'; currentData.grabPoint = { x : 0, y : 0 }; if (currentData.dropTarget == currentData.originalElement) currentData.dropTarget = currentData.originalElement.parentNode; if(currentData.onDrop){ if(currentData.onDrop(e)) return; } if (currentData.revert >= 0) RevertDrag(currentData); else PlaceDrag(currentData); }; //----------------------------------------------------------------------------Revert draggable to initial point function RevertDrag(d, callback){ d.dragElement.style.top = d.originalCoords.y / scale + 'px'; d.dragElement.style.left = d.originalCoords.x / scale + 'px'; if (d.revert > 0){ var str = (d.revert/1000) + "s"; setCSSTransition(d.dragElement, str); setTimeout(function(){setCSSTransform(d.dragElement, 'translate(0px,0px)')}, 1); d.revertCallback = callback; d.dragElement.addEventListener('transitionend', TransitionEnd); d.dragElement.addEventListener('webkitTransitionEnd', TransitionEnd); d.dragElement.addEventListener('oTransitionEnd', TransitionEnd); } else { setCSSTransform(d.dragElement, 'translate(0px,0px)'); TransitionEnd({target: d.dragElement}); } }; function TransitionEnd(e){ e.target.removeEventListener('transitionend', TransitionEnd); e.target.removeEventListener('webkitTransitionEnd', TransitionEnd); e.target.removeEventListener('oTransitionEnd', TransitionEnd); var d = configs[e.target.getAttribute('data-drag-id')]; if (d.clone){ d.originalElement.style.opacity = 1; d.dragElement.parentNode.removeChild(d.dragElement); } else { setCSSTransition(d.dragElement, 'none'); } if(d.revertCallback) d.revertCallback(); d.dragElement = null; }; //-------------------------------------------------------------------------Place draggable at the drop point function PlaceDrag(d, callback){ var newCoords = { x: (d.dragElement.style.transform) ? parseInt(d.dragElement.style.transform.split('(').pop().split(',')[0]) * scale : 0, y: (d.dragElement.style.transform) ? parseInt(d.dragElement.style.transform.split('(').pop().split(',')[1]) * scale : 0 } var st = window.getComputedStyle(d.dropTarget, null); var tScale = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || 1; if(st.getPropertyValue('position') == 'static'){ d.dropTarget.style.position = 'relative'; }; if(tScale == 'none') tScale = 1; else tScale = parseFloat(tScale.split('(')[1].split(',')[0]); setCSSTransform(d.dragElement, 'translate(0px,0px)'); d.dragElement.style.position = 'absolute'; d.dragElement.style.margin = '0'; d.dragElement.style.top = (( (d.originalCoords.y + newCoords.y) - d.dropTarget.getBoundingClientRect().top) / tScale) / scale + 'px'; d.dragElement.style.left = (( (d.originalCoords.x + newCoords.x) - d.dropTarget.getBoundingClientRect().left) / tScale) / scale + 'px'; d.dropTarget.appendChild(d.dragElement); if(d.clone){ d.dragElement.addEventListener('mousedown', CreateClone); d.dragElement.addEventListener('touchstart', CreateClone); d.dragElement.addEventListener('touchend', Drop); d.dragElement.className = d.originalElement.className; d.originalElement.parentNode.removeChild(d.originalElement); } if(callback) callback(); }; //----------------------------------------------------------------------------Finding closest parent who is a valid drggable function findDraggableParent(el) { while (el.getAttribute('data-drag-id') == null){ el = el.parentNode; } return el } //----------------------------------------------------------------------------Style setting helpers function setCSSTransform(el, val) { el.style.transform = val; el.style.webkitTransform = val; el.style.mozTransform = val; el.style.msTransform = val; el.style.oTransform = val; }; function setCSSTransition(el, val) { el.style.transition = val; el.style.webkitTransition = val; el.style.mozTransition = val; el.style.msTransition = val; el.style.oTransition = val; }; //----------------------------------------------------------------------------Library object var dnd = { get: function (selector) { var els; if (typeof selector === 'string') els = document.querySelectorAll(selector); else if (selector.length) els = selector; else els = [selector]; return new DND(els); }, setScale: function(val) { scale = val; }, revertDrag: function(data, cb) { RevertDrag(data, cb); }, placeDrag: function(data, cb) { PlaceDrag(data, cb); }, getParentScale: function(el) { var st = window.getComputedStyle(el.parentNode, null); var tr = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || 'none'; return (tr == 'none') ? 1 : parseFloat(tr.split('(')[1].split(',')[0]); } }; return dnd; }());
now the bug is really fixed
dnd.js
now the bug is really fixed
<ide><path>nd.js <ide> currentData = configs[evtTarget.getAttribute('data-drag-id')]; <ide> currentData.originalCoords = { x: evtTarget.getBoundingClientRect().left, y: evtTarget.getBoundingClientRect().top }; <ide> currentData.dragElement = target || evtTarget; <del> <add> <ide> if(!currentData.clone && currentData.onStart) { <ide> currentData.onStart(e); <ide> } <ide> <ide> var newX = (e.clientX / scale) - currentData.grabPoint.x; <ide> var newY = (e.clientY / scale) - currentData.grabPoint.y; <add> newY += (newY == 0) ? 0.001 : 0; <add> <ide> setCSSTransform(currentData.dragElement, 'translate(' + newX + 'px,' + newY + 'px)'); <ide> <ide> if(currentData.onDrag) {
Java
apache-2.0
c71e0529883d73094e30ce2f9e864f6abb60eb2d
0
jroper/async-http-client,elijah513/async-http-client,junjiemars/async-http-client,nemoyixin/async-http-client,ooon/async-http-client,olksdr/async-http-client,magiccao/async-http-client,drmaas/async-http-client,ALEXGUOQ/async-http-client,wyyl1/async-http-client,bomgar/async-http-client,craigwblake/async-http-client-1,stepancheg/async-http-client,liuyb02/async-http-client,dotta/async-http-client,afelisatti/async-http-client,thinker-fang/async-http-client,fengshao0907/async-http-client,Aulust/async-http-client,Aulust/async-http-client,jxauchengchao/async-http-client,typesafehub/async-http-client,hgl888/async-http-client
/* * Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.util; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Vector; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.AsyncHttpProvider; import com.ning.http.client.ByteArrayPart; import com.ning.http.client.Cookie; import com.ning.http.client.FilePart; import com.ning.http.client.FluentStringsMap; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.Part; import com.ning.http.client.Request; import com.ning.http.client.StringPart; import com.ning.http.multipart.ByteArrayPartSource; import com.ning.http.multipart.MultipartRequestEntity; import com.ning.http.multipart.PartSource; /** * {@link com.ning.http.client.AsyncHttpProvider} common utilities. * <p/> * The cookies's handling code is from the Netty framework. */ public class AsyncHttpProviderUtils { private final static byte[] NO_BYTES = new byte[0]; public final static String DEFAULT_CHARSET = "ISO-8859-1"; private final static String BODY_NOT_COMPUTED = "Response's body hasn't been computed by your AsyncHandler."; protected final static ThreadLocal<SimpleDateFormat[]> simpleDateFormat = new ThreadLocal<SimpleDateFormat[]>() { protected SimpleDateFormat[] initialValue() { return new SimpleDateFormat[] { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), // RFC1123 new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), //RFC1036 new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy", Locale.US), //ASCTIME new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss Z", Locale.US) }; } }; public final static SimpleDateFormat[] get() { return simpleDateFormat.get(); } //space ' ' static final byte SP = 32; //tab ' ' static final byte HT = 9; /** * Carriage return */ static final byte CR = 13; /** * Equals '=' */ static final byte EQUALS = 61; /** * Line feed character */ static final byte LF = 10; /** * carriage return line feed */ static final byte[] CRLF = new byte[]{CR, LF}; /** * Colon ':' */ static final byte COLON = 58; /** * Semicolon ';' */ static final byte SEMICOLON = 59; /** * comma ',' */ static final byte COMMA = 44; static final byte DOUBLE_QUOTE = '"'; static final String PATH = "Path"; static final String EXPIRES = "Expires"; static final String MAX_AGE = "Max-Age"; static final String DOMAIN = "Domain"; static final String SECURE = "Secure"; static final String HTTPONLY = "HTTPOnly"; static final String COMMENT = "Comment"; static final String COMMENTURL = "CommentURL"; static final String DISCARD = "Discard"; static final String PORT = "Port"; static final String VERSION = "Version"; public static final void validateSupportedScheme(URI uri) { final String scheme = uri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https") && !scheme.equalsIgnoreCase("ws") && !scheme.equalsIgnoreCase("wss")) { throw new IllegalArgumentException("The URI scheme, of the URI " + uri + ", must be equal (ignoring case) to 'http', 'https', 'ws', or 'wss'"); } } public final static URI createUri(String u) { URI uri = URI.create(u); validateSupportedScheme(uri); String path = uri.getPath(); if (path == null) { throw new IllegalArgumentException("The URI path, of the URI " + uri + ", must be non-null"); } else if (path.length() > 0 && path.charAt(0) != '/') { throw new IllegalArgumentException("The URI path, of the URI " + uri + ". must start with a '/'"); } else if (path.length() == 0) { return URI.create(u + "/"); } return uri; } public static String getBaseUrl(String url) { return getBaseUrl(createUri(url)); } public final static String getBaseUrl(URI uri) { String url = uri.getScheme() + "://" + uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static String getAuthority(URI uri) { String url = uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static String contentToString(List<HttpResponseBodyPart> bodyParts, String charset) throws UnsupportedEncodingException { return new String(contentToBytes(bodyParts), charset); } public final static byte[] contentToBytes(List<HttpResponseBodyPart> bodyParts) throws UnsupportedEncodingException { final int partCount = bodyParts.size(); if (partCount == 0) { return NO_BYTES; } if (partCount == 1) { return bodyParts.get(0).getBodyPartBytes(); } int size = 0; ArrayList<byte[]> chunks = new ArrayList<byte[]>(partCount); for (HttpResponseBodyPart part : bodyParts) { byte[] chunk = part.getBodyPartBytes(); size += chunk.length; chunks.add(chunk); } byte[] bytes = new byte[size]; int offset = 0; for (byte[] chunk : chunks) { System.arraycopy(chunk, 0, bytes, offset, chunk.length); offset += chunk.length; } return bytes; } public final static byte[] contentToBytes(List<HttpResponseBodyPart> bodyParts, int maxLen) throws UnsupportedEncodingException { final int partCount = bodyParts.size(); if (partCount == 0) { return NO_BYTES; } if (partCount == 1) { byte[] chunk = bodyParts.get(0).getBodyPartBytes(); if (chunk.length <= maxLen) { return chunk; } byte[] result = new byte[maxLen]; System.arraycopy(chunk, 0, result, 0, maxLen); return result; } int size = 0; byte[] result = new byte[maxLen]; for (HttpResponseBodyPart part : bodyParts) { byte[] chunk = part.getBodyPartBytes(); int amount = Math.min(maxLen-size, chunk.length); System.arraycopy(chunk, 0, result, size, amount); size += amount; if (size == maxLen) { return result; } } if (size < maxLen) { byte[] old = result; result = new byte[old.length]; System.arraycopy(old, 0, result, 0, old.length); } return result; } public final static InputStream contentAsStream(List<HttpResponseBodyPart> bodyParts) { switch (bodyParts.size()) { case 0: return new ByteArrayInputStream(NO_BYTES); case 1: return bodyParts.get(0).readBodyPartBytes(); } Vector<InputStream> streams = new Vector<InputStream>(bodyParts.size()); for (HttpResponseBodyPart part : bodyParts) { streams.add(part.readBodyPartBytes()); } return new SequenceInputStream(streams.elements()); } public final static String getHost(URI uri) { String host = uri.getHost(); if (host == null) { host = uri.getAuthority(); } return host; } public final static URI getRedirectUri(URI uri, String location) { if(location == null) throw new IllegalArgumentException("URI " + uri + " was redirected to null location"); URI newUri = uri.resolve(location); String scheme = newUri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https") && !scheme.equals("ws") && !scheme.equals("wss")) { throw new IllegalArgumentException("The URI scheme, of the URI " + newUri + ", must be equal (ignoring case) to 'ws, 'wss', 'http', or 'https'"); } return newUri; } public final static int getPort(URI uri) { int port = uri.getPort(); if (port == -1) port = uri.getScheme().equals("http") || uri.getScheme().equals("ws") ? 80 : 443; return port; } /** * This is quite ugly as our internal names are duplicated, but we build on top of HTTP Client implementation. * * @param params * @param methodParams * @return a MultipartRequestEntity. * @throws java.io.FileNotFoundException */ public final static MultipartRequestEntity createMultipartRequestEntity(List<Part> params, FluentStringsMap methodParams) throws FileNotFoundException { com.ning.http.multipart.Part[] parts = new com.ning.http.multipart.Part[params.size()]; int i = 0; for (Part part : params) { if (part instanceof com.ning.http.multipart.Part) { parts[i] = (com.ning.http.multipart.Part) part; } else if (part instanceof StringPart) { parts[i] = new com.ning.http.multipart.StringPart(part.getName(), ((StringPart) part).getValue(), ((StringPart) part).getCharset()); } else if (part instanceof FilePart) { parts[i] = new com.ning.http.multipart.FilePart(part.getName(), ((FilePart) part).getFile(), ((FilePart) part).getMimeType(), ((FilePart) part).getCharSet()); } else if (part instanceof ByteArrayPart) { PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData()); parts[i] = new com.ning.http.multipart.FilePart(part.getName(), source, ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet()); } else if (part == null) { throw new NullPointerException("Part cannot be null"); } else { throw new IllegalArgumentException(String.format("Unsupported part type for multipart parameter %s", part.getName())); } ++i; } return new MultipartRequestEntity(parts, methodParams); } public final static byte[] readFully(InputStream in, int[] lengthWrapper) throws IOException { // just in case available() returns bogus (or -1), allocate non-trivial chunk byte[] b = new byte[Math.max(512, in.available())]; int offset = 0; while (true) { int left = b.length - offset; int count = in.read(b, offset, left); if (count < 0) { // EOF break; } offset += count; if (count == left) { // full buffer, need to expand b = doubleUp(b); } } // wish Java had Tuple return type... lengthWrapper[0] = offset; return b; } private static byte[] doubleUp(byte[] b) { int len = b.length; byte[] b2 = new byte[len + len]; System.arraycopy(b, 0, b2, 0, len); return b2; } public static String encodeCookies(Collection<Cookie> cookies) { StringBuilder sb = new StringBuilder(); for (Cookie cookie : cookies) { if (cookie.getVersion() >= 1) { add(sb, '$' + VERSION, 1); } add(sb, cookie.getName(), cookie.getValue()); if (cookie.getPath() != null) { add(sb, '$' + PATH, cookie.getPath()); } if (cookie.getDomain() != null) { add(sb, '$' + DOMAIN, cookie.getDomain()); } if (cookie.getVersion() >= 1) { if (!cookie.getPorts().isEmpty()) { sb.append('$'); sb.append(PORT); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); for (int port : cookie.getPorts()) { sb.append(port); sb.append((char) COMMA); } sb.setCharAt(sb.length() - 1, (char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } } } sb.setLength(sb.length() - 1); return sb.toString(); } private static void add(StringBuilder sb, String name, String val) { if (val == null) { addQuoted(sb, name, ""); return; } for (int i = 0; i < val.length(); i++) { char c = val.charAt(i); switch (c) { case '\t': case ' ': case '"': case '(': case ')': case ',': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '{': case '}': addQuoted(sb, name, val); return; } } addUnquoted(sb, name, val); } private static void addUnquoted(StringBuilder sb, String name, String val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } private static void addQuoted(StringBuilder sb, String name, String val) { if (val == null) { val = ""; } sb.append(name); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); sb.append(val.replace("\\", "\\\\").replace("\"", "\\\"")); sb.append((char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } private static void add(StringBuilder sb, String name, int val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } public static String constructUserAgent(Class<? extends AsyncHttpProvider> httpProvider, AsyncHttpClientConfig config) { return new StringBuffer(config.getUserAgent()) .append(' ') .append('(') .append(httpProvider.getSimpleName()) .append(" - ") .append(System.getProperty("os.name")) .append(" - ") .append(System.getProperty("os.version")) .append(" - ") .append(System.getProperty("java.version")) .append(" - ") .append(Runtime.getRuntime().availableProcessors()) .append(" core(s))").toString(); } public static String parseCharset(String contentType) { for (String part : contentType.split(";")) { if (part.trim().startsWith("charset=")) { String[] val = part.split("="); if (val.length > 1) { String charset = val[1].trim(); // Quite a lot of sites have charset="CHARSET", // e.g. charset="utf-8". Note the quotes. This is // not correct, but client should be able to handle // it (all browsers do, Apache HTTP Client and Grizzly // strip it by default) // This is a poor man's trim("\"").trim("'") return charset.replaceAll("\"", "").replaceAll("'", ""); } } } return null; } public static Cookie parseCookie(String value) { String[] fields = value.split(";\\s*"); String[] cookie = fields[0].split("=", 2); String cookieName = cookie[0]; String cookieValue = (cookie.length == 1) ? null : cookie[1]; int maxAge = -1; String path = null; String domain = null; boolean secure = false; boolean maxAgeSet = false; boolean expiresSet = false; for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); if (f.length == 1) continue; // Add protection against null field values // favor 'max-age' field over 'expires' if (!maxAgeSet && "max-age".equalsIgnoreCase(f[0])) { try { maxAge = Math.max(Integer.valueOf(removeQuote(f[1])), 0); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie // invalidate a previously parsed expires-field maxAge = -1; } maxAgeSet = true; } else if (!maxAgeSet && !expiresSet && "expires".equalsIgnoreCase(f[0])) { try { maxAge = Math.max(convertExpireField(f[1]), 0); } catch (Exception e) { // original behavior, is this correct at all (expires field with max-age semantics)? try { maxAge = Math.max(Integer.valueOf(f[1]), 0); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie } } expiresSet = true; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } return new Cookie(domain, cookieName, cookieValue, path, maxAge, secure); } public static int convertExpireField(String timestring) throws Exception { String trimmedTimeString = removeQuote(timestring.trim()); for (SimpleDateFormat sdf : simpleDateFormat.get()) { Date date = sdf.parse(trimmedTimeString, new ParsePosition(0)); if (date != null) { long now = System.currentTimeMillis(); long expire = date.getTime(); return (int) ((expire - now) / 1000); } } throw new IllegalArgumentException("Not a valid expire field " + trimmedTimeString); } private final static String removeQuote(String s) { if (MiscUtil.isNonEmpty(s)) { if (s.charAt(0) == '"') s = s.substring(1); if (s.charAt(s.length() - 1) == '"') s = s.substring(0, s.length() - 1); } return s; } public static void checkBodyParts(int statusCode, Collection<HttpResponseBodyPart> bodyParts) { if (bodyParts == null || bodyParts.size() == 0) { // We allow empty body on 204 if (statusCode == 204) return; throw new IllegalStateException(BODY_NOT_COMPUTED); } } public static String keepAliveHeaderValue(AsyncHttpClientConfig config) { return config.getAllowPoolingConnection() ? "keep-alive" : "close"; } public static int requestTimeout(AsyncHttpClientConfig config, Request request) { return request.getRequestTimeoutInMs() != 0 ? request.getRequestTimeoutInMs() : config.getRequestTimeoutInMs(); } }
api/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java
/* * Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.util; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Vector; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.AsyncHttpProvider; import com.ning.http.client.ByteArrayPart; import com.ning.http.client.Cookie; import com.ning.http.client.FilePart; import com.ning.http.client.FluentStringsMap; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.Part; import com.ning.http.client.Request; import com.ning.http.client.StringPart; import com.ning.http.multipart.ByteArrayPartSource; import com.ning.http.multipart.MultipartRequestEntity; import com.ning.http.multipart.PartSource; /** * {@link com.ning.http.client.AsyncHttpProvider} common utilities. * <p/> * The cookies's handling code is from the Netty framework. */ public class AsyncHttpProviderUtils { private final static byte[] NO_BYTES = new byte[0]; public final static String DEFAULT_CHARSET = "ISO-8859-1"; private final static String BODY_NOT_COMPUTED = "Response's body hasn't been computed by your AsyncHandler."; protected final static ThreadLocal<SimpleDateFormat[]> simpleDateFormat = new ThreadLocal<SimpleDateFormat[]>() { protected SimpleDateFormat[] initialValue() { return new SimpleDateFormat[] { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), // RFC1123 new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), //RFC1036 new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy", Locale.US), //ASCTIME new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss Z", Locale.US) }; } }; public final static SimpleDateFormat[] get() { return simpleDateFormat.get(); } //space ' ' static final byte SP = 32; //tab ' ' static final byte HT = 9; /** * Carriage return */ static final byte CR = 13; /** * Equals '=' */ static final byte EQUALS = 61; /** * Line feed character */ static final byte LF = 10; /** * carriage return line feed */ static final byte[] CRLF = new byte[]{CR, LF}; /** * Colon ':' */ static final byte COLON = 58; /** * Semicolon ';' */ static final byte SEMICOLON = 59; /** * comma ',' */ static final byte COMMA = 44; static final byte DOUBLE_QUOTE = '"'; static final String PATH = "Path"; static final String EXPIRES = "Expires"; static final String MAX_AGE = "Max-Age"; static final String DOMAIN = "Domain"; static final String SECURE = "Secure"; static final String HTTPONLY = "HTTPOnly"; static final String COMMENT = "Comment"; static final String COMMENTURL = "CommentURL"; static final String DISCARD = "Discard"; static final String PORT = "Port"; static final String VERSION = "Version"; public static final void validateSupportedScheme(URI uri) { final String scheme = uri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https") && !scheme.equalsIgnoreCase("ws") && !scheme.equalsIgnoreCase("wss")) { throw new IllegalArgumentException("The URI scheme, of the URI " + uri + ", must be equal (ignoring case) to 'http', 'https', 'ws', or 'wss'"); } } public final static URI createUri(String u) { URI uri = URI.create(u); validateSupportedScheme(uri); String path = uri.getPath(); if (path == null) { throw new IllegalArgumentException("The URI path, of the URI " + uri + ", must be non-null"); } else if (path.length() > 0 && path.charAt(0) != '/') { throw new IllegalArgumentException("The URI path, of the URI " + uri + ". must start with a '/'"); } else if (path.length() == 0) { return URI.create(u + "/"); } return uri; } public static String getBaseUrl(String url) { return getBaseUrl(createUri(url)); } public final static String getBaseUrl(URI uri) { String url = uri.getScheme() + "://" + uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static String getAuthority(URI uri) { String url = uri.getAuthority(); int port = uri.getPort(); if (port == -1) { port = getPort(uri); url += ":" + port; } return url; } public final static String contentToString(List<HttpResponseBodyPart> bodyParts, String charset) throws UnsupportedEncodingException { return new String(contentToBytes(bodyParts), charset); } public final static byte[] contentToBytes(List<HttpResponseBodyPart> bodyParts) throws UnsupportedEncodingException { final int partCount = bodyParts.size(); if (partCount == 0) { return NO_BYTES; } if (partCount == 1) { return bodyParts.get(0).getBodyPartBytes(); } int size = 0; ArrayList<byte[]> chunks = new ArrayList<byte[]>(partCount); for (HttpResponseBodyPart part : bodyParts) { byte[] chunk = part.getBodyPartBytes(); size += chunk.length; chunks.add(chunk); } byte[] bytes = new byte[size]; int offset = 0; for (byte[] chunk : chunks) { System.arraycopy(chunk, 0, bytes, offset, chunk.length); offset += chunk.length; } return bytes; } public final static byte[] contentToBytes(List<HttpResponseBodyPart> bodyParts, int maxLen) throws UnsupportedEncodingException { final int partCount = bodyParts.size(); if (partCount == 0) { return NO_BYTES; } if (partCount == 1) { byte[] chunk = bodyParts.get(0).getBodyPartBytes(); if (chunk.length <= maxLen) { return chunk; } byte[] result = new byte[maxLen]; System.arraycopy(chunk, 0, result, 0, maxLen); return result; } int size = 0; byte[] result = new byte[maxLen]; for (HttpResponseBodyPart part : bodyParts) { byte[] chunk = part.getBodyPartBytes(); int amount = Math.min(maxLen-size, chunk.length); System.arraycopy(chunk, 0, result, size, amount); size += amount; if (size == maxLen) { return result; } } if (size < maxLen) { byte[] old = result; result = new byte[old.length]; System.arraycopy(old, 0, result, 0, old.length); } return result; } public final static InputStream contentAsStream(List<HttpResponseBodyPart> bodyParts) { switch (bodyParts.size()) { case 0: return new ByteArrayInputStream(NO_BYTES); case 1: return bodyParts.get(0).readBodyPartBytes(); } Vector<InputStream> streams = new Vector<InputStream>(bodyParts.size()); for (HttpResponseBodyPart part : bodyParts) { streams.add(part.readBodyPartBytes()); } return new SequenceInputStream(streams.elements()); } public final static String getHost(URI uri) { String host = uri.getHost(); if (host == null) { host = uri.getAuthority(); } return host; } public final static URI getRedirectUri(URI uri, String location) { if(location == null) throw new IllegalArgumentException("URI " + uri + " was redirected to null location"); URI newUri = uri.resolve(location); String scheme = newUri.getScheme(); if (scheme == null || !scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https") && !scheme.equals("ws") && !scheme.equals("wss")) { throw new IllegalArgumentException("The URI scheme, of the URI " + newUri + ", must be equal (ignoring case) to 'ws, 'wss', 'http', or 'https'"); } return newUri; } public final static int getPort(URI uri) { int port = uri.getPort(); if (port == -1) port = uri.getScheme().equals("http") || uri.getScheme().equals("ws") ? 80 : 443; return port; } /** * This is quite ugly as our internal names are duplicated, but we build on top of HTTP Client implementation. * * @param params * @param methodParams * @return a MultipartRequestEntity. * @throws java.io.FileNotFoundException */ public final static MultipartRequestEntity createMultipartRequestEntity(List<Part> params, FluentStringsMap methodParams) throws FileNotFoundException { com.ning.http.multipart.Part[] parts = new com.ning.http.multipart.Part[params.size()]; int i = 0; for (Part part : params) { if (part instanceof com.ning.http.multipart.Part) { parts[i] = (com.ning.http.multipart.Part) part; } else if (part instanceof StringPart) { parts[i] = new com.ning.http.multipart.StringPart(part.getName(), ((StringPart) part).getValue(), ((StringPart) part).getCharset()); } else if (part instanceof FilePart) { parts[i] = new com.ning.http.multipart.FilePart(part.getName(), ((FilePart) part).getFile(), ((FilePart) part).getMimeType(), ((FilePart) part).getCharSet()); } else if (part instanceof ByteArrayPart) { PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(), ((ByteArrayPart) part).getData()); parts[i] = new com.ning.http.multipart.FilePart(part.getName(), source, ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet()); } else if (part == null) { throw new NullPointerException("Part cannot be null"); } else { throw new IllegalArgumentException(String.format("Unsupported part type for multipart parameter %s", part.getName())); } ++i; } return new MultipartRequestEntity(parts, methodParams); } public final static byte[] readFully(InputStream in, int[] lengthWrapper) throws IOException { // just in case available() returns bogus (or -1), allocate non-trivial chunk byte[] b = new byte[Math.max(512, in.available())]; int offset = 0; while (true) { int left = b.length - offset; int count = in.read(b, offset, left); if (count < 0) { // EOF break; } offset += count; if (count == left) { // full buffer, need to expand b = doubleUp(b); } } // wish Java had Tuple return type... lengthWrapper[0] = offset; return b; } private static byte[] doubleUp(byte[] b) { int len = b.length; byte[] b2 = new byte[len + len]; System.arraycopy(b, 0, b2, 0, len); return b2; } public static String encodeCookies(Collection<Cookie> cookies) { StringBuilder sb = new StringBuilder(); for (Cookie cookie : cookies) { if (cookie.getVersion() >= 1) { add(sb, '$' + VERSION, 1); } add(sb, cookie.getName(), cookie.getValue()); if (cookie.getPath() != null) { add(sb, '$' + PATH, cookie.getPath()); } if (cookie.getDomain() != null) { add(sb, '$' + DOMAIN, cookie.getDomain()); } if (cookie.getVersion() >= 1) { if (!cookie.getPorts().isEmpty()) { sb.append('$'); sb.append(PORT); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); for (int port : cookie.getPorts()) { sb.append(port); sb.append((char) COMMA); } sb.setCharAt(sb.length() - 1, (char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } } } sb.setLength(sb.length() - 1); return sb.toString(); } private static void add(StringBuilder sb, String name, String val) { if (val == null) { addQuoted(sb, name, ""); return; } for (int i = 0; i < val.length(); i++) { char c = val.charAt(i); switch (c) { case '\t': case ' ': case '"': case '(': case ')': case ',': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '{': case '}': addQuoted(sb, name, val); return; } } addUnquoted(sb, name, val); } private static void addUnquoted(StringBuilder sb, String name, String val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } private static void addQuoted(StringBuilder sb, String name, String val) { if (val == null) { val = ""; } sb.append(name); sb.append((char) EQUALS); sb.append((char) DOUBLE_QUOTE); sb.append(val.replace("\\", "\\\\").replace("\"", "\\\"")); sb.append((char) DOUBLE_QUOTE); sb.append((char) SEMICOLON); } private static void add(StringBuilder sb, String name, int val) { sb.append(name); sb.append((char) EQUALS); sb.append(val); sb.append((char) SEMICOLON); } public static String constructUserAgent(Class<? extends AsyncHttpProvider> httpProvider, AsyncHttpClientConfig config) { return new StringBuffer(config.getUserAgent()) .append(' ') .append('(') .append(httpProvider.getSimpleName()) .append(" - ") .append(System.getProperty("os.name")) .append(" - ") .append(System.getProperty("os.version")) .append(" - ") .append(System.getProperty("java.version")) .append(" - ") .append(Runtime.getRuntime().availableProcessors()) .append(" core(s))").toString(); } public static String parseCharset(String contentType) { for (String part : contentType.split(";")) { if (part.trim().startsWith("charset=")) { String[] val = part.split("="); if (val.length > 1) { String charset = val[1].trim(); // Quite a lot of sites have charset="CHARSET", // e.g. charset="utf-8". Note the quotes. This is // not correct, but client should be able to handle // it (all browsers do, Apache HTTP Client and Grizzly // strip it by default) // This is a poor man's trim("\"").trim("'") return charset.replaceAll("\"", "").replaceAll("'", ""); } } } return null; } public static Cookie parseCookie(String value) { String[] fields = value.split(";\\s*"); String[] cookie = fields[0].split("=", 2); String cookieName = cookie[0]; String cookieValue = (cookie.length == 1) ? null : cookie[1]; int maxAge = -1; String path = null; String domain = null; boolean secure = false; boolean maxAgeSet = false; boolean expiresSet = false; for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); if (f.length == 1) continue; // Add protection against null field values // favor 'max-age' field over 'expires' if (!maxAgeSet && "max-age".equalsIgnoreCase(f[0])) { try { maxAge = Math.max(Integer.valueOf(removeQuote(f[1])), 0); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie // invalidate a previously parsed expires-field maxAge = -1; } maxAgeSet = true; } else if (!maxAgeSet && !expiresSet && "expires".equalsIgnoreCase(f[0])) { try { maxAge = Math.max(convertExpireField(f[1]), 0); } catch (Exception e) { // original behavior, is this correct at all (expires field with max-age semantics)? try { maxAge = Math.max(Integer.valueOf(f[1]), 0); } catch (NumberFormatException e1) { // ignore failure to parse -> treat as session cookie } } expiresSet = true; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } return new Cookie(domain, cookieName, cookieValue, path, maxAge, secure); } public static int convertExpireField(String timestring) throws Exception { String trimmedTimeString = removeQuote(timestring.trim()); for (SimpleDateFormat sdf : simpleDateFormat.get()) { Date date = sdf.parse(trimmedTimeString, new ParsePosition(0)); if (date != null) { long now = System.currentTimeMillis(); long expire = date.getTime(); return (int) ((expire - now) / 1000); } } throw new IllegalArgumentException("Not a valid expire field " + trimmedTimeString); } private final static String removeQuote(String s) { if (s.startsWith("\"")) { s = s.substring(1); } if (s.endsWith("\"")) { s = s.substring(0, s.length() - 1); } return s; } public static void checkBodyParts(int statusCode, Collection<HttpResponseBodyPart> bodyParts) { if (bodyParts == null || bodyParts.size() == 0) { // We allow empty body on 204 if (statusCode == 204) return; throw new IllegalStateException(BODY_NOT_COMPUTED); } } public static String keepAliveHeaderValue(AsyncHttpClientConfig config) { return config.getAllowPoolingConnection() ? "keep-alive" : "close"; } public static int requestTimeout(AsyncHttpClientConfig config, Request request) { return request.getRequestTimeoutInMs() != 0 ? request.getRequestTimeoutInMs() : config.getRequestTimeoutInMs(); } }
Minor removeQuote clean up
api/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java
Minor removeQuote clean up
<ide><path>pi/src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java <ide> } <ide> <ide> private final static String removeQuote(String s) { <del> if (s.startsWith("\"")) { <del> s = s.substring(1); <del> } <del> <del> if (s.endsWith("\"")) { <del> s = s.substring(0, s.length() - 1); <add> if (MiscUtil.isNonEmpty(s)) { <add> if (s.charAt(0) == '"') <add> s = s.substring(1); <add> <add> if (s.charAt(s.length() - 1) == '"') <add> s = s.substring(0, s.length() - 1); <ide> } <ide> return s; <ide> }
Java
apache-2.0
4cadd7ee666b18749a9f2739ae0f8f1282e2dc14
0
CycloneAxe/phphub-android,CycloneAxe/phphub-android
package org.phphub.app.model; import android.content.Context; import org.phphub.app.api.TopicApi; import org.phphub.app.api.entity.TopicEntity; import org.phphub.app.common.Constant; import org.phphub.app.common.base.BaseModel; import java.util.HashMap; import java.util.Map; import rx.Observable; public class TopicModel extends BaseModel<TopicApi> { public TopicModel(Context context) { super(context, TopicApi.class); } Observable<TopicEntity> getTopics(String filter, int pageIndex) { Map<String, String> options = new HashMap<String, String>(); options.put("include", "user,node,last_reply_user"); options.put("per_page", String.valueOf(Constant.PER_PAGE)); options.put("filter", filter); options.put("page", String.valueOf(pageIndex)); return service.getTopics(options); } public Observable<TopicEntity> getTopicsByExcellent(int pageIndex) { return getTopics("excellent", pageIndex); } public Observable<TopicEntity> getTopicsByRecent(int pageIndex) { return getTopics("recent", pageIndex); } public Observable<TopicEntity> getTopicsByVote(int pageIndex) { return getTopics("vote", pageIndex); } public Observable<TopicEntity> getTopicsByNobody(int pageIndex) { return getTopics("nobody", pageIndex); } public Observable<TopicEntity> getTopicsByWiki(int pageIndex) { return getTopics("wiki", pageIndex); } }
app/src/main/java/org/phphub/app/model/TopicModel.java
package org.phphub.app.model; import android.content.Context; import org.phphub.app.api.TopicApi; import org.phphub.app.api.entity.TopicEntity; import org.phphub.app.common.Constant; import org.phphub.app.common.base.BaseModel; import java.util.HashMap; import java.util.Map; import rx.Observable; public class TopicModel extends BaseModel<TopicApi> { public TopicModel(Context context) { super(context, TopicApi.class); } Observable<TopicEntity> getTopics(String filter, int pageIndex) { Map<String, String> options = new HashMap<String, String>(); options.put("include", "user,node"); options.put("per_page", String.valueOf(Constant.PER_PAGE)); options.put("filter", filter); options.put("page", String.valueOf(pageIndex)); return service.getTopics(options); } public Observable<TopicEntity> getTopicsByExcellent(int pageIndex) { return getTopics("excellent", pageIndex); } public Observable<TopicEntity> getTopicsByRecent(int pageIndex) { return getTopics("recent", pageIndex); } public Observable<TopicEntity> getTopicsByVote(int pageIndex) { return getTopics("vote", pageIndex); } public Observable<TopicEntity> getTopicsByNobody(int pageIndex) { return getTopics("nobody", pageIndex); } public Observable<TopicEntity> getTopicsByWiki(int pageIndex) { return getTopics("wiki", pageIndex); } }
add last reply user to topic include
app/src/main/java/org/phphub/app/model/TopicModel.java
add last reply user to topic include
<ide><path>pp/src/main/java/org/phphub/app/model/TopicModel.java <ide> <ide> Observable<TopicEntity> getTopics(String filter, int pageIndex) { <ide> Map<String, String> options = new HashMap<String, String>(); <del> options.put("include", "user,node"); <add> options.put("include", "user,node,last_reply_user"); <ide> options.put("per_page", String.valueOf(Constant.PER_PAGE)); <ide> options.put("filter", filter); <ide> options.put("page", String.valueOf(pageIndex));
JavaScript
bsd-2-clause
4da0d2bd6092f72dd99462e4c3dbb01298caa7a3
0
oterral/ol3,fredj/ol3,planetlabs/ol3,mechdrew/ol3,colllin/openlayers,dracic/openlayers,wet-boew/openlayers,Gnafu/openlayers,landonb/ol3,mzur/ol3,owenmead/openlayers,freylis/ol3,geonux/ol3,Distem/ol3,kkuunnddaannkk/ol3,aisaacs/ol3,das-peter/ol3,sbrunner/openlayers,alvinlindstam/ol3,klokantech/ol3,colllin/openlayers,llambanna/ol3,oterral/ol3,oterral/ol3,antonio83moura/ol3,fblackburn/ol3,geekdenz/ol3,stweil/ol3,kkuunnddaannkk/ol3,tsauerwein/ol3,jmiller-boundless/ol3,pgiraud/openlayers,denilsonsa/ol3,richstoner/ol3,t27/ol3,CandoImage/ol3,elbakai/openlayers,klokantech/ol3raster,PetrDlouhy/openlayers,kjelderg/ol3,adh1365/openlayers,NOAA-ORR-ERD/ol3,epointal/ol3,sanak/ol2,jacmendt/ol3,Andrey-Pavlov/ol3,tschaub/ol3,tsauerwein/ol3,klokantech/ol3,ahocevar/ol2,freylis/ol3,owenmead/openlayers,fredj/ol3,xiaoqqchen/ol3,llambanna/ol3,epointal/ol3,Morgul/ol3,jmiller-boundless/ol3,openlayers/ol2,adh1365/openlayers,mechdrew/ol3,mzur/ol3,kjelderg/ol3,ahocevar/ol3,mzur/ol3,WayTo/openlayers,NOAA-ORR-ERD/ol3,t27/ol3,bartvde/ol3,geekdenz/openlayers,alexbrault/ol3,xiaoqqchen/ol3,ahocevar/openlayers,mechdrew/ol3,pvalsecc/openlayers,ahocevar/openlayers,elemoine/ol3,alvinlindstam/ol3,geonux/ol3,dracic/openlayers,pgiraud/openlayers,Gnafu/openlayers,altamiracorp/openlayers,thhomas/ol3,colllin/openlayers,Morgul/ol3,tamarmot/ol3,aisaacs/ol3,kartverket/openlayers,fperucic/ol3,kkuunnddaannkk/ol3,PetrDlouhy/openlayers,alexbrault/ol3,adh1365/openlayers,bill-chadwick/ol3,t27/ol3,planetlabs/ol3,landonb/ol3,altamiracorp/openlayers,NOAA-ORR-ERD/ol3,stweil/openlayers,tschaub/openlayers-raster,PetrDlouhy/openlayers,geekdenz/ol3,georchestra/openlayers,CandoImage/ol3,gingerik/ol3,denilsonsa/ol3,antonio83moura/ol3,Morgul/ol3,WayTo/openlayers,pmlrsg/ol3,avinet/openlayers,ahocevar/ol2,tschaub/ol3,epointal/ol3,alvinlindstam/ol3,boundlessgeo/openlayers,Distem/ol3,fblackburn/ol3,hafenr/ol3,Distem/ol3,bill-chadwick/ol3,adh1365/openlayers,dracic/openlayers,tamarmot/ol3,richstoner/ol3,dracic/openlayers,kjelderg/ol3,landonb/ol3,ahocevar/ol2,richstoner/ol3,PublicStuff/openlayers,planetlabs/ol3,WayTo/openlayers,jacmendt/ol3,boundlessgeo/openlayers,epointal/ol3,freylis/ol3,jmiller-boundless/ol3,denilsonsa/ol3,kartverket/openlayers,bartvde/ol3,colllin/openlayers,altamiracorp/openlayers,pmlrsg/ol3,tsauerwein/ol3,tschaub/openlayers-raster,Antreasgr/ol3,yinxiaomei/ol3,ahocevar/ol3,das-peter/ol3,shevawen/openlayers,klokantech/ol3,adube/ol3,thhomas/ol3,antonio83moura/ol3,das-peter/ol3,v5analytics/openlayers,freylis/ol3,geekdenz/ol3,NOAA-ORR-ERD/ol3,sanak/ol2,PublicStuff/openlayers,xiaoqqchen/ol3,openlayers/ol2,stweil/openlayers,v5analytics/openlayers,Gnafu/openlayers,v5analytics/openlayers,fperucic/ol3,kartverket/openlayers,thomasmoelhave/ol3,bill-chadwick/ol3,adube/ol3,PublicStuff/openlayers,itayod/ol3,ahocevar/ol3,jmiller-boundless/ol3,Morgul/ol3,wet-boew/openlayers,bjornharrtell/ol3,hafenr/ol3,elemoine/ol3,yinxiaomei/ol3,kartverket/openlayers,thomasmoelhave/ol3,llambanna/ol3,t27/ol3,bartvde/ol3,openlayers/openlayers,avinet/openlayers,bartvde/ol3,fblackburn/ol3,bjornharrtell/ol3,klokantech/ol3,wlerner/ol3,kjelderg/ol3,Gnafu/openlayers,gingerik/ol3,richstoner/ol3,ahocevar/ol3,Andrey-Pavlov/ol3,geekdenz/openlayers,alvinlindstam/ol3,itayod/ol3,xiaoqqchen/ol3,stweil/ol3,pvalsecc/openlayers,yinxiaomei/ol3,georchestra/openlayers,elemoine/ol3,avinet/openlayers,openlayers/ol2,geekdenz/openlayers,bogdanvaduva/ol3,owenmead/openlayers,Antreasgr/ol3,antonio83moura/ol3,v5analytics/openlayers,thhomas/ol3,tschaub/ol3,elemoine/ol3,avinet/openlayers,sbrunner/openlayers,landonb/ol3,pmlrsg/ol3,elbakai/openlayers,ahocevar/openlayers,wet-boew/openlayers,jacmendt/ol3,gingerik/ol3,klokantech/ol3raster,fblackburn/ol3,fperucic/ol3,CandoImage/ol3,pvalsecc/openlayers,stweil/ol3,jmiller-boundless/ol3,openlayers/ol2,shevawen/openlayers,stweil/openlayers,fredj/ol3,tschaub/openlayers-raster,georchestra/openlayers,shevawen/openlayers,Andrey-Pavlov/ol3,klokantech/ol3raster,itayod/ol3,wlerner/ol3,thomasmoelhave/ol3,adube/ol3,owenmead/openlayers,Antreasgr/ol3,stweil/ol3,denilsonsa/ol3,wet-boew/openlayers,gingerik/ol3,aisaacs/ol3,bill-chadwick/ol3,hafenr/ol3,WayTo/openlayers,sbrunner/openlayers,geoext/GXM,PetrDlouhy/openlayers,tschaub/ol3,boundlessgeo/openlayers,bjornharrtell/ol3,bogdanvaduva/ol3,pgiraud/openlayers,shevawen/openlayers,boundlessgeo/openlayers,mzur/ol3,Antreasgr/ol3,kkuunnddaannkk/ol3,llambanna/ol3,geoext/GXM,bogdanvaduva/ol3,openlayers/openlayers,alexbrault/ol3,jacmendt/ol3,alexbrault/ol3,bogdanvaduva/ol3,Andrey-Pavlov/ol3,altamiracorp/openlayers,elbakai/openlayers,hafenr/ol3,planetlabs/ol3,sanak/ol2,thhomas/ol3,elbakai/openlayers,fperucic/ol3,Distem/ol3,itayod/ol3,wlerner/ol3,geonux/ol3,yinxiaomei/ol3,wlerner/ol3,PublicStuff/openlayers,fredj/ol3,sanak/ol2,mechdrew/ol3,openlayers/openlayers,thomasmoelhave/ol3,sbrunner/openlayers,pmlrsg/ol3,pgiraud/openlayers,tamarmot/ol3,geonux/ol3,pvalsecc/openlayers,klokantech/ol3raster,geekdenz/ol3,tamarmot/ol3,das-peter/ol3,CandoImage/ol3,aisaacs/ol3,tsauerwein/ol3
/* Copyright (c) 2006 MetaCarta, Inc., published under a modified BSD license. * See http://svn.openlayers.org/trunk/openlayers/repository-license.txt * for the full text of the license. */ /** * @requires OpenLayers/Events.js * * Class: OpenLayers.Handler * Base class to construct a higher-level handler for event sequences. All * handlers have activate and deactivate methods. In addition, they have * methods named like browser events. When a handler is activated, any * additional methods named like a browser event is registered as a * listener for the corresponding event. When a handler is deactivated, * those same methods are unregistered as event listeners. * * Handlers also typically have a callbacks object with keys named like * the abstracted events or event sequences that they are in charge of * handling. The controls that wrap handlers define the methods that * correspond to these abstract events - so instead of listening for * individual browser events, they only listen for the abstract events * defined by the handler. * * Handlers are created by controls, which ultimately have the responsibility * of making changes to the the state of the application. Handlers * themselves may make temporary changes, but in general are expected to * return the application in the same state that they found it. */ OpenLayers.Handler = OpenLayers.Class.create(); OpenLayers.Handler.MOD_NONE = 0; OpenLayers.Handler.MOD_SHIFT = 1; OpenLayers.Handler.MOD_CTRL = 2; OpenLayers.Handler.MOD_ALT = 4; OpenLayers.Handler.prototype = { /** * Property: id * {String} */ id: null, /** * APIProperty: control * {<OpenLayers.Control>}. The control that initialized this handler. The * control is assumed to have a valid map property - that map is used * in the handler's own setMap method. */ control: null, /** * Property: map * {<OpenLayers.Map>} */ map: null, /** * Property: keyMask * {Integer} */ keyMask: null, /** * Property: active * {Boolean} */ active: false, /** * Constructor: OpenLayers.Handler * Construct a handler. * * Parameters: * control - {<OpenLayers.Control>} The control that initialized this * handler. The control is assumed to have a valid map property; that * map is used in the handler's own setMap method. * callbacks - {Object} An object whose properties correspond to abstracted * events or sequences of browser events. The values for these * properties are functions defined by the control that get called by * the handler. * options - {Object} An optional object whose properties will be set on * the handler. */ initialize: function(control, callbacks, options) { OpenLayers.Util.extend(this, options); this.control = control; this.callbacks = callbacks; if (control.map) { this.setMap(control.map); } OpenLayers.Util.extend(this, options); this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); }, /** * Method: setMap */ setMap: function (map) { this.map = map; }, /** * Method: checkModifiers */ checkModifiers: function (evt) { if(this.keyMask == null) { return true; } /* calculate the keyboard modifier mask for this event */ var keyModifiers = (evt.shiftKey ? OpenLayers.Handler.MOD_SHIFT : 0) | (evt.ctrlKey ? OpenLayers.Handler.MOD_CTRL : 0) | (evt.altKey ? OpenLayers.Handler.MOD_ALT : 0); /* if it differs from the handler object's key mask, bail out of the event handler */ return (keyModifiers == this.keyMask); }, /** * APIMethod: activate * Turn on the handler. Returns false if the handler was already active. * * Return: * {Boolean} The handler was activated. */ activate: function() { if(this.active) { return false; } // register for event handlers defined on this class. var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0; i < events.length; i++) { if (this[events[i]]) { this.register(events[i], this[events[i]]); } } this.active = true; return true; }, /** * APIMethod: deactivate * Turn off the handler. Returns false if the handler was already inactive. * * Return: * {Boolean} The handler was deactivated. */ deactivate: function() { if(!this.active) { return false; } // unregister event handlers defined on this class. var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0; i < events.length; i++) { if (this[events[i]]) { this.unregister(events[i], this[events[i]]); } } this.active = false; return true; }, /** * Method: callback * Trigger the control's named callback with the given arguments * * Parameters: * name - {String} The key for the callback that is one of the properties * of the handler's callbacks object. * args - {Array} An array of arguments with which to call the callback * (defined by the control). */ callback: function (name, args) { if (this.callbacks[name]) { this.callbacks[name].apply(this.control, args); } }, /** * Method: register * register an event on the map */ register: function (name, method) { // TODO: deal with registerPriority in 3.0 this.map.events.registerPriority(name, this, method); }, /** * Method: unregister * unregister an event from the map */ unregister: function (name, method) { this.map.events.unregister(name, this, method); }, /** * Method: destroy * Deconstruct the handler. */ destroy: function () { // eliminate circular references this.control = this.map = null; }, /** @final @type String */ CLASS_NAME: "OpenLayers.Handler" };
lib/OpenLayers/Handler.js
/* Copyright (c) 2006 MetaCarta, Inc., published under a modified BSD license. * See http://svn.openlayers.org/trunk/openlayers/repository-license.txt * for the full text of the license. */ /** * Class: OpenLayers.Handler * Base class to construct a higher-level handler for event sequences. * Handlers are created by controls, which ultimately have the responsibility * of making changes to the map. */ OpenLayers.Handler = OpenLayers.Class.create(); OpenLayers.Handler.MOD_NONE = 0; OpenLayers.Handler.MOD_SHIFT = 1; OpenLayers.Handler.MOD_CTRL = 2; OpenLayers.Handler.MOD_ALT = 4; OpenLayers.Handler.prototype = { /** * Property: id * {String} */ id: null, /** * Property: control * {<OpenLayers.Control>}. The control that initialized this * handler. */ control: null, /** * Property: map * {<OpenLayers.Map>} */ map: null, /** * Property: keyMask * {Integer} */ keyMask: null, /** * Property: active * {Boolean} */ active: false, /** * Constructor: OpenLayers.Handler * Construct a handler. * * Parameters: * control - {<OpenLayers.Control>} * callbacks - {Object} A hash of callback functions * options - {Object} */ initialize: function(control, callbacks, options) { OpenLayers.Util.extend(this, options); this.control = control; this.callbacks = callbacks; if (control.map) { this.setMap(control.map); } OpenLayers.Util.extend(this, options); this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME + "_"); }, /** * Method: setMap */ setMap: function (map) { this.map = map; }, /** * Method: checkModifiers */ checkModifiers: function (evt) { if(this.keyMask == null) { return true; } /* calculate the keyboard modifier mask for this event */ var keyModifiers = (evt.shiftKey ? OpenLayers.Handler.MOD_SHIFT : 0) | (evt.ctrlKey ? OpenLayers.Handler.MOD_CTRL : 0) | (evt.altKey ? OpenLayers.Handler.MOD_ALT : 0); /* if it differs from the handler object's key mask, bail out of the event handler */ return (keyModifiers == this.keyMask); }, /** * Method: activate * Turn on the handler. Returns false if the handler was already active. * * Return: * {Boolean} */ activate: function() { if(this.active) { return false; } // register for event handlers defined on this class. var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0; i < events.length; i++) { if (this[events[i]]) { this.register(events[i], this[events[i]]); } } this.active = true; return true; }, /** * Method: deactivate * Turn off the handler. Returns false if the handler was already inactive. * * Return: {Boolean} */ deactivate: function() { if(!this.active) { return false; } // unregister event handlers defined on this class. var events = OpenLayers.Events.prototype.BROWSER_EVENTS; for (var i = 0; i < events.length; i++) { if (this[events[i]]) { this.unregister(events[i], this[events[i]]); } } this.active = false; return true; }, /** * Method: callback * trigger the control's named callback with the given arguments */ callback: function (name, args) { if (this.callbacks[name]) { this.callbacks[name].apply(this.control, args); } }, /** * Method: register * register an event on the map */ register: function (name, method) { // TODO: deal with registerPriority in 3.0 this.map.events.registerPriority(name, this, method); }, /** * Method: unregister * unregister an event from the map */ unregister: function (name, method) { this.map.events.unregister(name, this, method); }, /** * Method: destroy */ destroy: function () { // eliminate circular references this.control = this.map = null; }, /** @final @type String */ CLASS_NAME: "OpenLayers.Handler" };
adding in some docs for the Handler base class git-svn-id: 86a4f41f9d0383640198789122b520d4105b319a@3658 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
lib/OpenLayers/Handler.js
adding in some docs for the Handler base class
<ide><path>ib/OpenLayers/Handler.js <ide> <ide> <ide> /** <add> * @requires OpenLayers/Events.js <add> * <ide> * Class: OpenLayers.Handler <del> * Base class to construct a higher-level handler for event sequences. <add> * Base class to construct a higher-level handler for event sequences. All <add> * handlers have activate and deactivate methods. In addition, they have <add> * methods named like browser events. When a handler is activated, any <add> * additional methods named like a browser event is registered as a <add> * listener for the corresponding event. When a handler is deactivated, <add> * those same methods are unregistered as event listeners. <add> * <add> * Handlers also typically have a callbacks object with keys named like <add> * the abstracted events or event sequences that they are in charge of <add> * handling. The controls that wrap handlers define the methods that <add> * correspond to these abstract events - so instead of listening for <add> * individual browser events, they only listen for the abstract events <add> * defined by the handler. <add> * <ide> * Handlers are created by controls, which ultimately have the responsibility <del> * of making changes to the map. <add> * of making changes to the the state of the application. Handlers <add> * themselves may make temporary changes, but in general are expected to <add> * return the application in the same state that they found it. <ide> */ <ide> OpenLayers.Handler = OpenLayers.Class.create(); <ide> <ide> id: null, <ide> <ide> /** <del> * Property: control <del> * {<OpenLayers.Control>}. The control that initialized this <del> * handler. <add> * APIProperty: control <add> * {<OpenLayers.Control>}. The control that initialized this handler. The <add> * control is assumed to have a valid map property - that map is used <add> * in the handler's own setMap method. <ide> */ <ide> control: null, <ide> <ide> * Construct a handler. <ide> * <ide> * Parameters: <del> * control - {<OpenLayers.Control>} <del> * callbacks - {Object} A hash of callback functions <del> * options - {Object} <add> * control - {<OpenLayers.Control>} The control that initialized this <add> * handler. The control is assumed to have a valid map property; that <add> * map is used in the handler's own setMap method. <add> * callbacks - {Object} An object whose properties correspond to abstracted <add> * events or sequences of browser events. The values for these <add> * properties are functions defined by the control that get called by <add> * the handler. <add> * options - {Object} An optional object whose properties will be set on <add> * the handler. <ide> */ <ide> initialize: function(control, callbacks, options) { <ide> OpenLayers.Util.extend(this, options); <ide> }, <ide> <ide> /** <del> * Method: activate <add> * APIMethod: activate <ide> * Turn on the handler. Returns false if the handler was already active. <ide> * <ide> * Return: <del> * {Boolean} <add> * {Boolean} The handler was activated. <ide> */ <ide> activate: function() { <ide> if(this.active) { <ide> }, <ide> <ide> /** <del> * Method: deactivate <add> * APIMethod: deactivate <ide> * Turn off the handler. Returns false if the handler was already inactive. <ide> * <del> * Return: {Boolean} <add> * Return: <add> * {Boolean} The handler was deactivated. <ide> */ <ide> deactivate: function() { <ide> if(!this.active) { <ide> <ide> /** <ide> * Method: callback <del> * trigger the control's named callback with the given arguments <add> * Trigger the control's named callback with the given arguments <add> * <add> * Parameters: <add> * name - {String} The key for the callback that is one of the properties <add> * of the handler's callbacks object. <add> * args - {Array} An array of arguments with which to call the callback <add> * (defined by the control). <ide> */ <ide> callback: function (name, args) { <ide> if (this.callbacks[name]) { <ide> <ide> /** <ide> * Method: destroy <add> * Deconstruct the handler. <ide> */ <ide> destroy: function () { <ide> // eliminate circular references
Java
apache-2.0
e9d5e0293812f308364e37df6298e95d44888893
0
apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.wicket.ui.components.scalars.datepicker; import java.util.Locale; import java.util.Map; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.util.convert.IConverter; import org.apache.isis.applib.locale.UserLocale; import org.apache.isis.core.runtime.context.IsisAppCommonContext; import org.apache.isis.viewer.wicket.model.converter.ConverterBasedOnValueSemantics; import org.apache.isis.viewer.wicket.model.models.ScalarModel; import static de.agilecoders.wicket.jquery.JQuery.$; import de.agilecoders.wicket.core.util.Attributes; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerIconConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome6IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.DatetimePickerCssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.DatetimePickerJsReference; import de.agilecoders.wicket.jquery.Config; import lombok.val; /** * A text input field that is used as a date or date/time picker. * It uses <a href="https://github.com/Eonasdan/bootstrap-datetimepicker">Bootstrap Datetime picker</a> * JavaScript widget. * For options (5.39.0) see <a href="https://getdatepicker.com/5-4/Options/">https://getdatepicker.com/5-4/Options/</a> * * @param <T> The type of the date/time */ public class TextFieldWithDateTimePicker<T> extends TextField<T> implements IConverter<T> { private static final long serialVersionUID = 1L; protected final IConverter<T> converter; private final DateTimeConfig config; public TextFieldWithDateTimePicker( final String id, final ScalarModel scalarModel, final Class<T> type, final IConverter<T> converter) { super(id, scalarModel.unwrapped(type), type); setOutputMarkupId(true); this.config = createDatePickerConfig( scalarModel.getCommonContext(), ((ConverterBasedOnValueSemantics<T>) converter).getEditingPattern(), !scalarModel.isRequired()); this.converter = converter; /* debug new IConverter<T>() { @Override public T convertToObject(final String value, final Locale locale) throws ConversionException { System.err.printf("convertToObject %s%n", value); try { val obj = converter.convertToObject(value, locale); System.err.printf("convertedToObject %s%n", obj); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public String convertToString(final T value, final Locale locale) { val s = converter.convertToString(value, locale); System.err.printf("convertedToString %s%n", s); return s; } }; */ //XXX ISIS-2834 //Adding OnChangeAjaxBehavior registers a JavaScript event listener on change event. //Since OnChangeAjaxBehavior extends AjaxFormComponentUpdatingBehavior the Ajax request // also updates the Wicket model for this form component on the server side. // onUpdate() is a callback method that you could use to do something more or don't do anything add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(final AjaxRequestTarget target) { // nothing to do } }); } @Override public T convertToObject(final String value, final Locale locale) { return converter.convertToObject(value, locale); } @Override public String convertToString(final T value, final Locale locale) { return converter.convertToString(value, locale); } @SuppressWarnings("unchecked") @Override public <C> IConverter<C> getConverter(final Class<C> type) { // we use isAssignableFrom rather than a simple == to handle // the persistence of JDO/DataNucleus: // if persisting a java.sql.Date, the object we are given is actually a // org.datanucleus.store.types.simple.SqlDate (a subclass of java.sql.Date) if (super.getType().isAssignableFrom(type)) { return (IConverter<C>) this; } return super.getConverter(type); } @Override protected void onComponentTag(final ComponentTag tag) { super.onComponentTag(tag); if(!isEnabled()) { return; } checkComponentTag(tag, "input"); Attributes.addClass(tag, "datetimepicker-input"); Attributes.set(tag, "type", "text"); Attributes.set(tag, "data-toggle", "datetimepicker"); Attributes.set(tag, "data-target", getMarkupId()); Attributes.set(tag, "autocomplete", "off"); } @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); if(!isEnabled()) { return; } response.render(DatetimePickerCssReference.asHeaderItem()); response.render(DatetimePickerJsReference.asHeaderItem()); response.render(OnDomReadyHeaderItem.forScript(createScript(config))); } // -- HELPER private DateTimeConfig createDatePickerConfig( final IsisAppCommonContext commonContext, final String temporalPattern, final boolean isInputNullable) { val config = new DateTimeConfig(); config.useLocale(commonContext.currentUserLocale() .map(UserLocale::getLanguageLocale) .orElse(Locale.US)); config.withFormat(_TimeFormatUtil.convertToMomentJsFormat(temporalPattern)); config.useCalendarWeeks(true); config.useCurrent(false); config.withButtons(Map.of( DatetimePickerConfig.BTN_SHOW_TODAY, true, DatetimePickerConfig.BTN_SHOW_CLEAR, isInputNullable, DatetimePickerConfig.BTN_SHOW_CLOSE, true)); //config.highlightToday(true); /* time: 'far fa-clock', date: 'far fa-calendar', up: 'far fa-arrow-up', down: 'far fa-arrow-down', previous: 'far fa-chevron-left', next: 'far fa-chevron-right', today: 'far fa-calendar-check-o', clear: 'far fa-trash', close: 'far fa-times' */ config.withIcons(new DatetimePickerIconConfig() .useTimeIcon(FontAwesome6IconType.clock_r) .useDateIcon(FontAwesome6IconType.calendar_r) .useUpIcon(FontAwesome6IconType.arrow_up_s) .useDownIcon(FontAwesome6IconType.arrow_down_s) .usePreviousIcon(FontAwesome6IconType.chevron_left_s) .useNextIcon(FontAwesome6IconType.chevron_right_s) .useTodayIcon(FontAwesome6IconType.calendar_check_r) .useClearIcon(FontAwesome6IconType.trash_can_r) .useCloseIcon(FontAwesome6IconType.check_s) ); //XXX future extensions might allow to set bounds on a per member basis (via ValueSemantics annotation) //config.withMinDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().minDateAsJavaUtilDate()); //config.withMaxDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().maxDateAsJavaUtilDate()); config.minDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().getMinDate()); config.maxDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().getMaxDate()); return config; } /** * Returns the initializer script. */ private CharSequence createScript(final Config config) { val script = $(this).chain("datetimepicker", config).get(); //debug //System.err.printf("script: %s%n", script); return script; } }
viewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/datepicker/TextFieldWithDateTimePicker.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.wicket.ui.components.scalars.datepicker; import java.util.Locale; import java.util.Map; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.util.convert.IConverter; import org.apache.isis.applib.locale.UserLocale; import org.apache.isis.core.runtime.context.IsisAppCommonContext; import org.apache.isis.viewer.wicket.model.converter.ConverterBasedOnValueSemantics; import org.apache.isis.viewer.wicket.model.models.ScalarModel; import static de.agilecoders.wicket.jquery.JQuery.$; import de.agilecoders.wicket.core.util.Attributes; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerIconConfig; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesome6IconType; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.DatetimePickerCssReference; import de.agilecoders.wicket.extensions.markup.html.bootstrap.references.DatetimePickerJsReference; import de.agilecoders.wicket.jquery.Config; import lombok.val; /** * A text input field that is used as a date or date/time picker. * It uses <a href="https://github.com/Eonasdan/bootstrap-datetimepicker">Bootstrap Datetime picker</a> * JavaScript widget. * For options (5.39.0) see <a href="https://getdatepicker.com/5-4/Options/">https://getdatepicker.com/5-4/Options/</a> * * @param <T> The type of the date/time */ public class TextFieldWithDateTimePicker<T> extends TextField<T> implements IConverter<T> { private static final long serialVersionUID = 1L; protected final IConverter<T> converter; private final DateTimeConfig config; public TextFieldWithDateTimePicker( final String id, final ScalarModel scalarModel, final Class<T> type, final IConverter<T> converter) { super(id, scalarModel.unwrapped(type), type); setOutputMarkupId(true); this.converter = converter; this.config = createDatePickerConfig( scalarModel.getCommonContext(), !scalarModel.isRequired()); /* debug new IConverter<T>() { @Override public T convertToObject(final String value, final Locale locale) throws ConversionException { System.err.printf("convertToObject %s%n", value); try { val obj = converter.convertToObject(value, locale); System.err.printf("convertedToObject %s%n", obj); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public String convertToString(final T value, final Locale locale) { val s = converter.convertToString(value, locale); System.err.printf("convertedToString %s%n", s); return s; } }; */ //XXX ISIS-2834 //Adding OnChangeAjaxBehavior registers a JavaScript event listener on change event. //Since OnChangeAjaxBehavior extends AjaxFormComponentUpdatingBehavior the Ajax request // also updates the Wicket model for this form component on the server side. // onUpdate() is a callback method that you could use to do something more or don't do anything add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(final AjaxRequestTarget target) { // nothing to do } }); } @Override public T convertToObject(final String value, final Locale locale) { return converter.convertToObject(value, locale); } @Override public String convertToString(final T value, final Locale locale) { return converter.convertToString(value, locale); } @SuppressWarnings("unchecked") @Override public <C> IConverter<C> getConverter(final Class<C> type) { // we use isAssignableFrom rather than a simple == to handle // the persistence of JDO/DataNucleus: // if persisting a java.sql.Date, the object we are given is actually a // org.datanucleus.store.types.simple.SqlDate (a subclass of java.sql.Date) if (super.getType().isAssignableFrom(type)) { return (IConverter<C>) this; } return super.getConverter(type); } @Override protected void onComponentTag(final ComponentTag tag) { super.onComponentTag(tag); if(!isEnabled()) { return; } checkComponentTag(tag, "input"); Attributes.addClass(tag, "datetimepicker-input"); Attributes.set(tag, "type", "text"); Attributes.set(tag, "data-toggle", "datetimepicker"); Attributes.set(tag, "data-target", getMarkupId()); Attributes.set(tag, "autocomplete", "off"); } @Override public void renderHead(final IHeaderResponse response) { super.renderHead(response); if(!isEnabled()) { return; } response.render(DatetimePickerCssReference.asHeaderItem()); response.render(DatetimePickerJsReference.asHeaderItem()); response.render(OnDomReadyHeaderItem.forScript(createScript(config))); } // -- HELPER private DateTimeConfig createDatePickerConfig( final IsisAppCommonContext commonContext, final boolean isInputNullable) { val config = new DateTimeConfig(); config.useLocale(commonContext.currentUserLocale() .map(UserLocale::getLanguageLocale) .orElse(Locale.US)); // if this text field is for a LocalDate, then the pattern obtained will just be a simple date format // (with no hour/minute components). final String dateTimePattern = ((ConverterBasedOnValueSemantics<T>)converter).getEditingPattern(); config.withFormat(_TimeFormatUtil.convertToMomentJsFormat(dateTimePattern)); config.useCalendarWeeks(true); config.useCurrent(false); config.withButtons(Map.of( DatetimePickerConfig.BTN_SHOW_TODAY, true, DatetimePickerConfig.BTN_SHOW_CLEAR, isInputNullable, DatetimePickerConfig.BTN_SHOW_CLOSE, true)); //config.highlightToday(true); /* time: 'far fa-clock', date: 'far fa-calendar', up: 'far fa-arrow-up', down: 'far fa-arrow-down', previous: 'far fa-chevron-left', next: 'far fa-chevron-right', today: 'far fa-calendar-check-o', clear: 'far fa-trash', close: 'far fa-times' */ config.withIcons(new DatetimePickerIconConfig() .useTimeIcon(FontAwesome6IconType.clock_r) .useDateIcon(FontAwesome6IconType.calendar_r) .useUpIcon(FontAwesome6IconType.arrow_up_s) .useDownIcon(FontAwesome6IconType.arrow_down_s) .usePreviousIcon(FontAwesome6IconType.chevron_left_s) .useNextIcon(FontAwesome6IconType.chevron_right_s) .useTodayIcon(FontAwesome6IconType.calendar_check_r) .useClearIcon(FontAwesome6IconType.trash_can_r) .useCloseIcon(FontAwesome6IconType.xmark_s) ); //XXX future extensions might allow to set bounds on a per member basis (via ValueSemantics annotation) //config.withMinDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().minDateAsJavaUtilDate()); //config.withMaxDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().maxDateAsJavaUtilDate()); config.minDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().getMinDate()); config.maxDate(commonContext.getConfiguration().getViewer().getWicket().getDatePicker().getMaxDate()); return config; } /** * Returns the initializer script. */ private CharSequence createScript(final Config config) { val script = $(this).chain("datetimepicker", config).get(); //debug //System.err.printf("script: %s%n", script); return script; } }
ISIS-3085: change icon for time-picker close: use 'check' icon rather than 'close' icon
viewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/datepicker/TextFieldWithDateTimePicker.java
ISIS-3085: change icon for time-picker close: use 'check' icon
<ide><path>iewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/datepicker/TextFieldWithDateTimePicker.java <ide> super(id, scalarModel.unwrapped(type), type); <ide> setOutputMarkupId(true); <ide> <del> this.converter = converter; <ide> this.config = createDatePickerConfig( <ide> scalarModel.getCommonContext(), <add> ((ConverterBasedOnValueSemantics<T>) converter).getEditingPattern(), <ide> !scalarModel.isRequired()); <add> <add> this.converter = converter; <ide> <ide> /* debug <ide> new IConverter<T>() { <ide> <ide> private DateTimeConfig createDatePickerConfig( <ide> final IsisAppCommonContext commonContext, <add> final String temporalPattern, <ide> final boolean isInputNullable) { <ide> val config = new DateTimeConfig(); <ide> <ide> .map(UserLocale::getLanguageLocale) <ide> .orElse(Locale.US)); <ide> <del> // if this text field is for a LocalDate, then the pattern obtained will just be a simple date format <del> // (with no hour/minute components). <del> final String dateTimePattern = ((ConverterBasedOnValueSemantics<T>)converter).getEditingPattern(); <del> config.withFormat(_TimeFormatUtil.convertToMomentJsFormat(dateTimePattern)); <del> <add> config.withFormat(_TimeFormatUtil.convertToMomentJsFormat(temporalPattern)); <ide> config.useCalendarWeeks(true); <ide> config.useCurrent(false); <ide> <ide> .useNextIcon(FontAwesome6IconType.chevron_right_s) <ide> .useTodayIcon(FontAwesome6IconType.calendar_check_r) <ide> .useClearIcon(FontAwesome6IconType.trash_can_r) <del> .useCloseIcon(FontAwesome6IconType.xmark_s) <add> .useCloseIcon(FontAwesome6IconType.check_s) <ide> ); <ide> <ide> //XXX future extensions might allow to set bounds on a per member basis (via ValueSemantics annotation)
JavaScript
mit
13a42c5df512d22d961c65aa805c8ce1e8dada8a
0
computationclub/computationclub.github.io,computationclub/computationclub.github.io
/* jshint bitwise: false */ /* global window */ (function (exports) { 'use strict'; var Rule = (function () { var constructor = function (number) { this.number = number; }; constructor.prototype.apply = function (p, q, r) { return !!(this.number & (1 << ((p << 2) | (q << 1) | (r << 0)))); }; return constructor; }()); var CellularAutomaton = (function () { var constructor = function (options) { this.rule = options.rule; this.cells = [true]; this.origin = 0; }; constructor.prototype.step = function () { var prefix = this.rule.apply(false, false, this.cells[0]), suffix = this.rule.apply(this.cells[this.cells.length - 1], false, false); this.cells = this.cells.map(function (middle, column) { return this.rule.apply(this.cells[column - 1], middle, this.cells[column + 1]); }, this); if (prefix) { this.cells.unshift(prefix); this.origin++; } if (suffix) { this.cells.push(suffix); } }; constructor.prototype.cellAt = function (column) { return this.cells[this.origin + column]; }; return constructor; }()); var drawCells = function (cellularAutomaton, context, row, cellCount, cellSize) { for (var column = -cellCount + 1; column <= 0; ++column) { if (cellularAutomaton.cellAt(column)) { context.fillRect((column + cellCount - 1) * cellSize, row * cellSize, cellSize, cellSize); } } }; var scrollContext = function (context, cellCount, rowCount, cellSize) { var width = cellCount * cellSize, height = rowCount * cellSize; var imageData = context.getImageData(0, cellSize, width, height - cellSize); context.putImageData(imageData, 0, 0); context.clearRect(0, height - cellSize, width, cellSize); }; exports.drawCellularAutomaton = function (options) { var canvas = options.canvas, cellSize = options.cellSize, rule = options.rule, rowsPerSecond = options.rowsPerSecond; var context = canvas.getContext('2d'); var cellCount = Math.floor(canvas.width / cellSize); var cellularAutomaton = new CellularAutomaton({ rule: rule }); var rowCount = Math.floor(canvas.height / cellSize); var row = 0; window.setInterval(function () { drawCells(cellularAutomaton, context, row, cellCount, cellSize); cellularAutomaton.step(); if (row < rowCount - 1) { ++row; } else { scrollContext(context, cellCount, rowCount, cellSize); } }, 1000 / rowsPerSecond); }; exports.Rule = Rule; }(this));
cellular-automaton.js
/* jshint bitwise: false */ /* global window */ (function (exports) { 'use strict'; var Rule = (function () { var constructor = function (number) { this.number = number; }; constructor.prototype.apply = function (p, q, r) { return !!(this.number & (1 << ((p << 2) | (q << 1) | (r << 0)))); }; return constructor; }()); var CellularAutomaton = (function () { var makeCells = function (cellCount) { var cells = []; for (var i = 0; i < cellCount; ++i) { cells[i] = false; } cells[cells.length - 1] = true; return cells; }; var constructor = function (options) { this.rule = options.rule; this.cells = makeCells(options.cellCount); this.origin = this.cells.length - 1; }; constructor.prototype.step = function () { var prefix = this.rule.apply(false, false, this.cells[0]), suffix = this.rule.apply(this.cells[this.cells.length - 1], false, false); this.cells = this.cells.map(function (middle, column) { return this.rule.apply(this.cells[column - 1], middle, this.cells[column + 1]); }, this); if (prefix) { this.cells.unshift(prefix); this.origin++; } if (suffix) { this.cells.push(suffix); } }; constructor.prototype.cellAt = function (column) { return this.cells[this.origin + column]; }; return constructor; }()); var drawCells = function (cellularAutomaton, context, row, cellCount, cellSize) { for (var column = -cellCount + 1; column <= 0; ++column) { if (cellularAutomaton.cellAt(column)) { context.fillRect((column + cellCount - 1) * cellSize, row * cellSize, cellSize, cellSize); } } }; var scrollContext = function (context, cellCount, rowCount, cellSize) { var width = cellCount * cellSize, height = rowCount * cellSize; var imageData = context.getImageData(0, cellSize, width, height - cellSize); context.putImageData(imageData, 0, 0); context.clearRect(0, height - cellSize, width, cellSize); }; exports.drawCellularAutomaton = function (options) { var canvas = options.canvas, cellSize = options.cellSize, rule = options.rule, rowsPerSecond = options.rowsPerSecond; var context = canvas.getContext('2d'); var cellCount = Math.floor(canvas.width / cellSize); var cellularAutomaton = new CellularAutomaton({ rule: rule, cellCount: cellCount }); var rowCount = Math.floor(canvas.height / cellSize); var row = 0; window.setInterval(function () { drawCells(cellularAutomaton, context, row, cellCount, cellSize); cellularAutomaton.step(); if (row < rowCount - 1) { ++row; } else { scrollContext(context, cellCount, rowCount, cellSize); } }, 1000 / rowsPerSecond); }; exports.Rule = Rule; }(this));
Start with one cell and let it grow
cellular-automaton.js
Start with one cell and let it grow
<ide><path>ellular-automaton.js <ide> }()); <ide> <ide> var CellularAutomaton = (function () { <del> var makeCells = function (cellCount) { <del> var cells = []; <del> for (var i = 0; i < cellCount; ++i) { <del> cells[i] = false; <del> } <del> cells[cells.length - 1] = true; <del> <del> return cells; <del> }; <del> <ide> var constructor = function (options) { <ide> this.rule = options.rule; <del> this.cells = makeCells(options.cellCount); <del> this.origin = this.cells.length - 1; <add> this.cells = [true]; <add> this.origin = 0; <ide> }; <ide> <ide> constructor.prototype.step = function () { <ide> var context = canvas.getContext('2d'); <ide> <ide> var cellCount = Math.floor(canvas.width / cellSize); <del> var cellularAutomaton = new CellularAutomaton({ <del> rule: rule, <del> cellCount: cellCount <del> }); <add> var cellularAutomaton = new CellularAutomaton({ rule: rule }); <ide> <ide> var rowCount = Math.floor(canvas.height / cellSize); <ide> var row = 0;
Java
mit
06c9785b6152b8a57ee3eab7832022433467915c
0
TheHolyWaffle/TeamSpeak-3-Java-API,Barofioso/TeamSpeak-3-Java-API,Barofioso/TeamSpeak-3-Java-API
package com.github.theholywaffle.teamspeak3; /* * #%L * TeamSpeak 3 Java API * %% * Copyright (C) 2014 Bert De Geyter * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.github.theholywaffle.teamspeak3.api.Callback; import com.github.theholywaffle.teamspeak3.commands.Command; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; public class SocketReader extends Thread { private final TS3Query ts3; private final ExecutorService userThreadPool; private final Map<Command, Callback> callbackMap; private String lastEvent; public SocketReader(TS3Query ts3) { super("[TeamSpeak-3-Java-API] SocketReader"); this.ts3 = ts3; this.userThreadPool = Executors.newScheduledThreadPool(1); this.callbackMap = Collections.synchronizedMap(new LinkedHashMap<Command, Callback>()); this.lastEvent = ""; try { int i = 0; while (i < 4 || ts3.getIn().ready()) { TS3Query.log.info("< " + ts3.getIn().readLine()); i++; } } catch (final IOException e) { e.printStackTrace(); } } @Override public void run() { while (ts3.getSocket() != null && ts3.getSocket().isConnected() && ts3.getIn() != null && !isInterrupted()) { final String line; try { // Will block until a full line of text could be read. line = ts3.getIn().readLine(); } catch (IOException io) { if (!isInterrupted()) { io.printStackTrace(); } break; } if (line == null) { break; // The underlying socket was closed } else if (line.isEmpty()) { continue; // The server is sending garbage } final Command c = ts3.getCommandList().peek(); if (line.startsWith("notify")) { TS3Query.log.info("< [event] " + line); // Filter out duplicate events for join, quit and channel move events if (isDuplicate(line)) continue; userThreadPool.execute(new Runnable() { @Override public void run() { final String arr[] = line.split(" ", 2); ts3.getEventManager().fireEvent(arr[0], arr[1]); } }); } else if (c != null && c.isSent()) { TS3Query.log.info("[" + c.getName() + "] < " + line); if (line.startsWith("error")) { c.feedError(line.substring("error ".length())); if (c.getError().getId() != 0) { TS3Query.log.severe("[ERROR] " + c.getError()); } c.setAnswered(); ts3.getCommandList().remove(c); answerCallback(c); } else { c.feed(line); } } else { TS3Query.log.info("< " + line); } } userThreadPool.shutdown(); if (!isInterrupted()) { TS3Query.log.warning("SocketReader has stopped!"); } } private void answerCallback(Command c) { final Callback callback = callbackMap.get(c); // Command had no callback registered if (callback == null) return; // To avoid the possibility of clogging the map with callbacks for // inexistent commands, remove all entries before the current one // Typically, this will exit without removing a single entry Set<Command> keySet = callbackMap.keySet(); synchronized (callbackMap) { Iterator<Command> iterator = keySet.iterator(); while (iterator.hasNext() && !c.equals(iterator.next())) { iterator.remove(); } } userThreadPool.execute(new Runnable() { @Override public void run() { try { callback.handle(); } catch (Throwable t) { TS3Query.log.log(Level.WARNING, "User callback threw exception", t); } } }); } void registerCallback(Command command, Callback callback) { callbackMap.put(command, callback); } private boolean isDuplicate(String eventMessage) { if (!(eventMessage.startsWith("notifyclientmoved") || eventMessage.startsWith("notifycliententerview") || eventMessage.startsWith("notifyclientleftview"))) { // Event that will never cause duplicates return false; } if (eventMessage.equals(lastEvent)) { // Duplicate event! lastEvent = ""; // Let's only ever filter one duplicate return true; } lastEvent = eventMessage; return false; } }
src/main/java/com/github/theholywaffle/teamspeak3/SocketReader.java
package com.github.theholywaffle.teamspeak3; /* * #%L * TeamSpeak 3 Java API * %% * Copyright (C) 2014 Bert De Geyter * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.github.theholywaffle.teamspeak3.api.Callback; import com.github.theholywaffle.teamspeak3.commands.Command; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; public class SocketReader extends Thread { private final TS3Query ts3; private final ExecutorService userThreadPool; private final Map<Command, Callback> callbackMap; public SocketReader(TS3Query ts3) { super("[TeamSpeak-3-Java-API] SocketReader"); this.ts3 = ts3; this.userThreadPool = Executors.newScheduledThreadPool(1); this.callbackMap = Collections.synchronizedMap(new LinkedHashMap<Command, Callback>()); try { int i = 0; while (i < 4 || ts3.getIn().ready()) { TS3Query.log.info("< " + ts3.getIn().readLine()); i++; } } catch (final IOException e) { e.printStackTrace(); } } @Override public void run() { while (ts3.getSocket() != null && ts3.getSocket().isConnected() && ts3.getIn() != null && !isInterrupted()) { final String line; try { // Will block until a full line of text could be read. line = ts3.getIn().readLine(); } catch (IOException io) { if (!isInterrupted()) { io.printStackTrace(); } break; } if (line == null) { break; // The underlying socket was closed } else if (line.isEmpty()) { continue; // The server is sending garbage } final Command c = ts3.getCommandList().peek(); if (line.startsWith("notify")) { TS3Query.log.info("< [event] " + line); userThreadPool.execute(new Runnable() { @Override public void run() { final String arr[] = line.split(" ", 2); ts3.getEventManager().fireEvent(arr[0], arr[1]); } }); } else if (c != null && c.isSent()) { TS3Query.log.info("[" + c.getName() + "] < " + line); if (line.startsWith("error")) { c.feedError(line.substring("error ".length())); if (c.getError().getId() != 0) { TS3Query.log.severe("[ERROR] " + c.getError()); } c.setAnswered(); ts3.getCommandList().remove(c); answerCallback(c); } else { c.feed(line); } } else { TS3Query.log.info("< " + line); } } userThreadPool.shutdown(); if (!isInterrupted()) { TS3Query.log.warning("SocketReader has stopped!"); } } private void answerCallback(Command c) { final Callback callback = callbackMap.get(c); // Command had no callback registered if (callback == null) return; // To avoid the possibility of clogging the map with callbacks for // inexistent commands, remove all entries before the current one // Typically, this will exit without removing a single entry Set<Command> keySet = callbackMap.keySet(); synchronized (callbackMap) { Iterator<Command> iterator = keySet.iterator(); while (iterator.hasNext() && !c.equals(iterator.next())) { iterator.remove(); } } userThreadPool.execute(new Runnable() { @Override public void run() { try { callback.handle(); } catch (Throwable t) { TS3Query.log.log(Level.WARNING, "User callback threw exception", t); } } }); } void registerCallback(Command command, Callback callback) { callbackMap.put(command, callback); } }
Add filter for duplicate join, quit and channel move events to SocketReader. Fixes #36
src/main/java/com/github/theholywaffle/teamspeak3/SocketReader.java
Add filter for duplicate join, quit and channel move events to SocketReader. Fixes #36
<ide><path>rc/main/java/com/github/theholywaffle/teamspeak3/SocketReader.java <ide> private final ExecutorService userThreadPool; <ide> private final Map<Command, Callback> callbackMap; <ide> <add> private String lastEvent; <add> <ide> public SocketReader(TS3Query ts3) { <ide> super("[TeamSpeak-3-Java-API] SocketReader"); <ide> this.ts3 = ts3; <ide> this.userThreadPool = Executors.newScheduledThreadPool(1); <ide> this.callbackMap = Collections.synchronizedMap(new LinkedHashMap<Command, Callback>()); <add> this.lastEvent = ""; <ide> <ide> try { <ide> int i = 0; <ide> <ide> if (line.startsWith("notify")) { <ide> TS3Query.log.info("< [event] " + line); <add> <add> // Filter out duplicate events for join, quit and channel move events <add> if (isDuplicate(line)) continue; <ide> <ide> userThreadPool.execute(new Runnable() { <ide> @Override <ide> callbackMap.put(command, callback); <ide> } <ide> <add> private boolean isDuplicate(String eventMessage) { <add> if (!(eventMessage.startsWith("notifyclientmoved") <add> || eventMessage.startsWith("notifycliententerview") <add> || eventMessage.startsWith("notifyclientleftview"))) { <add> <add> // Event that will never cause duplicates <add> return false; <add> } <add> <add> if (eventMessage.equals(lastEvent)) { <add> // Duplicate event! <add> lastEvent = ""; // Let's only ever filter one duplicate <add> return true; <add> } <add> <add> lastEvent = eventMessage; <add> return false; <add> } <ide> }
Java
apache-2.0
79e674f9580e2769221b7f4e819d24813e4190f9
0
Taskana/taskana,Taskana/taskana,Taskana/taskana,Taskana/taskana,Taskana/taskana
package pro.taskana.common.rest.assembler; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.hateoas.Link; import org.springframework.hateoas.PagedModel.PageMetadata; import org.springframework.hateoas.RepresentationModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; import pro.taskana.common.rest.models.TaskanaPagedModel; import pro.taskana.common.rest.models.TaskanaPagedModelKeys; public interface TaskanaPagingAssembler<T, D extends RepresentationModel<? super D>> extends RepresentationModelAssembler<T, D> { TaskanaPagedModelKeys getProperty(); default TaskanaPagedModel<D> toPageModel(Iterable<T> entities, PageMetadata pageMetadata) { return StreamSupport.stream(entities.spliterator(), false) .map(this::toModel) .collect( Collectors.collectingAndThen( Collectors.toList(), l -> new TaskanaPagedModel<>(getProperty(), l, pageMetadata))); } default TaskanaPagedModel<D> toPageModel(Iterable<T> entities) { return toPageModel(entities, null); } default TaskanaPagedModel<D> addLinksToPagedResource(TaskanaPagedModel<D> model) { final UriComponentsBuilder original = ServletUriComponentsBuilder.fromCurrentRequest(); final PageMetadata page = model.getMetadata(); model.add(Link.of(original.toUriString()).withSelfRel()); if (page != null) { model.add( Link.of(original.replaceQueryParam("page", 1).toUriString()) .withRel(IanaLinkRelations.FIRST)); model.add( Link.of(original.replaceQueryParam("page", page.getTotalPages()).toUriString()) .withRel(IanaLinkRelations.LAST)); if (page.getNumber() > 1) { model.add( Link.of(original.replaceQueryParam("page", page.getNumber() - 1).toUriString()) .withRel(IanaLinkRelations.PREV)); } if (page.getNumber() < page.getTotalPages()) { model.add( Link.of(original.replaceQueryParam("page", page.getNumber() + 1).toUriString()) .withRel(IanaLinkRelations.NEXT)); } } return model; } }
rest/taskana-rest-spring/src/main/java/pro/taskana/common/rest/assembler/TaskanaPagingAssembler.java
package pro.taskana.common.rest.assembler; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.servlet.http.HttpServletRequest; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.hateoas.Link; import org.springframework.hateoas.PagedModel.PageMetadata; import org.springframework.hateoas.RepresentationModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; import pro.taskana.common.rest.models.TaskanaPagedModel; import pro.taskana.common.rest.models.TaskanaPagedModelKeys; public interface TaskanaPagingAssembler<T, D extends RepresentationModel<? super D>> extends RepresentationModelAssembler<T, D> { TaskanaPagedModelKeys getProperty(); default TaskanaPagedModel<D> toPageModel(Iterable<T> entities, PageMetadata pageMetadata) { return StreamSupport.stream(entities.spliterator(), false) .map(this::toModel) .collect( Collectors.collectingAndThen( Collectors.toList(), l -> new TaskanaPagedModel<>(getProperty(), l, pageMetadata))); } default TaskanaPagedModel<D> toPageModel(Iterable<T> entities) { return toPageModel(entities, null); } default TaskanaPagedModel<D> addLinksToPagedResource(TaskanaPagedModel<D> model) { final UriComponentsBuilder original = getBaseUri(); final PageMetadata page = model.getMetadata(); model.add(Link.of(original.toUriString()).withSelfRel()); if (page != null) { model.add( Link.of(original.replaceQueryParam("page", 1).toUriString()) .withRel(IanaLinkRelations.FIRST)); model.add( Link.of(original.replaceQueryParam("page", page.getTotalPages()).toUriString()) .withRel(IanaLinkRelations.LAST)); if (page.getNumber() > 1) { model.add( Link.of(original.replaceQueryParam("page", page.getNumber() - 1).toUriString()) .withRel(IanaLinkRelations.PREV)); } if (page.getNumber() < page.getTotalPages()) { model.add( Link.of(original.replaceQueryParam("page", page.getNumber() + 1).toUriString()) .withRel(IanaLinkRelations.NEXT)); } } return model; } default UriComponentsBuilder getBaseUri() { final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); final UriComponentsBuilder baseUri = ServletUriComponentsBuilder.fromServletMapping(request).path(request.getRequestURI()); for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { for (String value : entry.getValue()) { baseUri.queryParam(entry.getKey(), value); } } return baseUri; } }
TSK-1368: removed duplicate context root in self ref links
rest/taskana-rest-spring/src/main/java/pro/taskana/common/rest/assembler/TaskanaPagingAssembler.java
TSK-1368: removed duplicate context root in self ref links
<ide><path>est/taskana-rest-spring/src/main/java/pro/taskana/common/rest/assembler/TaskanaPagingAssembler.java <ide> package pro.taskana.common.rest.assembler; <ide> <del>import java.util.Map; <ide> import java.util.stream.Collectors; <ide> import java.util.stream.StreamSupport; <del>import javax.servlet.http.HttpServletRequest; <ide> import org.springframework.hateoas.IanaLinkRelations; <ide> import org.springframework.hateoas.Link; <ide> import org.springframework.hateoas.PagedModel.PageMetadata; <ide> import org.springframework.hateoas.RepresentationModel; <ide> import org.springframework.hateoas.server.RepresentationModelAssembler; <del>import org.springframework.web.context.request.RequestContextHolder; <del>import org.springframework.web.context.request.ServletRequestAttributes; <ide> import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> } <ide> <ide> default TaskanaPagedModel<D> addLinksToPagedResource(TaskanaPagedModel<D> model) { <del> final UriComponentsBuilder original = getBaseUri(); <add> final UriComponentsBuilder original = ServletUriComponentsBuilder.fromCurrentRequest(); <ide> final PageMetadata page = model.getMetadata(); <ide> <ide> model.add(Link.of(original.toUriString()).withSelfRel()); <ide> <ide> return model; <ide> } <del> <del> default UriComponentsBuilder getBaseUri() { <del> final HttpServletRequest request = <del> ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); <del> final UriComponentsBuilder baseUri = <del> ServletUriComponentsBuilder.fromServletMapping(request).path(request.getRequestURI()); <del> <del> for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { <del> for (String value : entry.getValue()) { <del> baseUri.queryParam(entry.getKey(), value); <del> } <del> } <del> <del> return baseUri; <del> } <ide> }
Java
apache-2.0
3b3b751f5fd0f67d89258766987b301c676fdf68
0
jasperhoogland/jautomata
package net.jhoogland.jautomata; import java.util.Collection; import java.util.Comparator; import net.jhoogland.jautomata.semirings.Semiring; /** * * All automata (acceptors, transducers, multi-tape automata, and their weighted variants) implement this interface. * The methods <code>initialStates()</code>, <code>transitionsOut(state)</code>, * <code>initialWeight(state)</code>, <code>finalWeight(state)</code>, <code>from(transition)</code>, * <code>to(transition)</code>, <code>label(transition)</code>, * and <code>transitionWeight(transition)</code> define the automaton. * The method <code>semiring()</code> returns the {@link Semiring} over which the automaton is defined. * The method <code>topologicalOrder()</code> makes it possible to specify a topological order on the automaton states, if it exists. * Some algorithms are faster if a topological order is specified. * * @author Jasper Hoogland * * @param <L> * label type * * @param <K> * weight type * (Boolean for regular automata and Double for weighted automata) * */ public interface Automaton<L, K> { /** * * @return * Collection of initial states * */ public Collection<Object> initialStates(); // /** // * // * @return // * Collection of labels of outgoing transitions from the specified state // * // */ // // public Collection<L> labelsOut(Object state); // // // /** // * // * @return // * Collection of outgoing transitions with the specified label from the specified // * // */ // // public Collection<Object> transitionsOut(Object state, L label); /** * * @return * Collection of outgoing transitions from the specified * */ public Collection<Object> transitionsOut(Object state); /** * * @return * The initial weight of the specified state if it is an initial state, * returns semiring().zero() otherwise. * */ public K initialWeight(Object state); /** * * @return * the final weight of the specified state if it is an final state, * semiring().zero() otherwise * */ public K finalWeight(Object state); /** * * @return * the source state of the specified transition * */ public Object from(Object transition); /** * * @return * the destination state of the specified transition * */ public Object to(Object transition); /** * * @return * the label of the specified transition * */ public L label(Object transition); /** * @return * the weight of the specified transition */ public K transitionWeight(Object transition); /** * @return * the {@link Semiring} over which this automaton is defined * */ public Semiring<K> semiring(); /** * * @return * a topological order over the states of this automaton if one is known, * <code>null</code> otherwise * */ public Comparator<Object> topologicalOrder(); }
jautomata/src/main/java/net/jhoogland/jautomata/Automaton.java
package net.jhoogland.jautomata; import java.util.Collection; import java.util.Comparator; import net.jhoogland.jautomata.semirings.Semiring; /** * * All automata (acceptors, transducers, multi-tape automata, and their weighted variants) implement this interface. * The methods <code>initialStates()</code>, <code>transitionsOut(state)</code>, * <code>initialWeight(state)</code>, <code>finalWeight(state)</code>, <code>previousState(transition)</code>, * <code>nextState(transition)</code>, <code>label(transition)</code>, * and <code>transitionWeight(transition)</code> define the automaton. * The method <code>semiring()</code> returns the {@link Semiring} over which the automaton is defined. * The method <code>topologicalOrder()</code> makes it possible to specify a topological order on the automaton states, if it exists. * Some algorithms are faster if a topological order is specified. * * @author Jasper Hoogland * * @param <L> * label type * * @param <K> * weight type * (Boolean for regular automata and Double for weighted automata) * */ public interface Automaton<L, K> { /** * * @return * Collection of initial states * */ public Collection<Object> initialStates(); // /** // * // * @return // * Collection of labels of outgoing transitions from the specified state // * // */ // // public Collection<L> labelsOut(Object state); // // // /** // * // * @return // * Collection of outgoing transitions with the specified label from the specified // * // */ // // public Collection<Object> transitionsOut(Object state, L label); /** * * @return * Collection of outgoing transitions from the specified * */ public Collection<Object> transitionsOut(Object state); /** * * @return * The initial weight of the specified state if it is an initial state, * returns semiring().zero() otherwise. * */ public K initialWeight(Object state); /** * * @return * the final weight of the specified state if it is an final state, * semiring().zero() otherwise * */ public K finalWeight(Object state); /** * * @return * the state from which the specified transition is an outgoing transition * */ public Object from(Object transition); /** * * @return * the state to which the specified transition is an incoming transition * */ public Object to(Object transition); /** * * @return * the label of the specified transition * */ public L label(Object transition); /** * @return * the weight of the specified transition */ public K transitionWeight(Object transition); /** * @return * the {@link Semiring} over which this automaton is defined * */ public Semiring<K> semiring(); /** * * @return * a topological order over the states of this automaton if one is known, * <code>null</code> otherwise * */ public Comparator<Object> topologicalOrder(); }
Javadoc update.
jautomata/src/main/java/net/jhoogland/jautomata/Automaton.java
Javadoc update.
<ide><path>automata/src/main/java/net/jhoogland/jautomata/Automaton.java <ide> * <ide> * All automata (acceptors, transducers, multi-tape automata, and their weighted variants) implement this interface. <ide> * The methods <code>initialStates()</code>, <code>transitionsOut(state)</code>, <del> * <code>initialWeight(state)</code>, <code>finalWeight(state)</code>, <code>previousState(transition)</code>, <del> * <code>nextState(transition)</code>, <code>label(transition)</code>, <add> * <code>initialWeight(state)</code>, <code>finalWeight(state)</code>, <code>from(transition)</code>, <add> * <code>to(transition)</code>, <code>label(transition)</code>, <ide> * and <code>transitionWeight(transition)</code> define the automaton. <ide> * The method <code>semiring()</code> returns the {@link Semiring} over which the automaton is defined. <ide> * The method <code>topologicalOrder()</code> makes it possible to specify a topological order on the automaton states, if it exists. <ide> /** <ide> * <ide> * @return <del> * the state from which the specified transition is an outgoing transition <add> * the source state of the specified transition <ide> * <ide> */ <ide> <ide> /** <ide> * <ide> * @return <del> * the state to which the specified transition is an incoming transition <add> * the destination state of the specified transition <ide> * <ide> */ <ide>
Java
apache-2.0
error: pathspec 'extended/src/main/java/io/kubernetes/client/extended/kubectl/util/deployment/DeploymentHelper.java' did not match any file(s) known to git
f7d40c20cb30cd8a3617708af43f0c661721249e
1
kubernetes-client/java,kubernetes-client/java
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.extended.kubectl.util.deployment; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.apis.AppsV1Api; import io.kubernetes.client.openapi.models.V1Deployment; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1OwnerReference; import io.kubernetes.client.openapi.models.V1PodTemplateSpec; import io.kubernetes.client.openapi.models.V1ReplicaSet; import io.kubernetes.client.openapi.models.V1ReplicaSetList; import io.kubernetes.client.util.Yaml; import io.kubernetes.client.util.labels.LabelSelector; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; public class DeploymentHelper { public static final String DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY = "pod-template-hash"; public static final String REVISION_ANNOTATION = "deployment.kubernetes.io/revision"; /** * getAllReplicaSets get the old replica sets and return new replica targeted by the given * Deployment. It gets PodList and ReplicaSetList from client interface. Note that the first set * of old replica sets doesn't include the ones with no pods, and the second set of old replica * sets include all old replica sets. The returned value is the new replica set, and it may be nil * if it doesn't exist yet. * * @param deployment the given deployment * @param api the client interface * @param oldRSes container of all old ReplicaSet exclude the ones with no pods * @param allOldRSes container of all old ReplicaSet * @return the new replica set */ public static V1ReplicaSet getAllReplicaSets( V1Deployment deployment, AppsV1Api api, List<V1ReplicaSet> oldRSes, List<V1ReplicaSet> allOldRSes) throws ApiException { List<V1ReplicaSet> rsList = listReplicaSets(deployment, api); V1ReplicaSet newRs = findNewReplicaSet(deployment, rsList); findOldReplicaSets(rsList, newRs, oldRSes, allOldRSes); return newRs; } /** * revision returns the revision number of the input object. * * @param meta metadata of object * @return the revision number */ public static Long revision(V1ObjectMeta meta) { String v = meta.getAnnotations().get(REVISION_ANNOTATION); return v == null ? 0L : Long.parseLong(v); } /** * listReplicaSets returns a list of RSes the given deployment targets. Note that this does NOT * attempt to reconcile ControllerRef (adopt/orphan), because only the controller itself should do * that. However, it does filter out anything whose ControllerRef doesn't match. */ private static List<V1ReplicaSet> listReplicaSets(V1Deployment deployment, AppsV1Api api) throws ApiException { String namespace = deployment.getMetadata().getNamespace(); LabelSelector selector = LabelSelector.parse(deployment.getSpec().getSelector()); List<V1ReplicaSet> all = rsListFromClient(namespace, selector.toString(), api); List<V1ReplicaSet> owned = new ArrayList<>(all.size()); for (V1ReplicaSet rs : all) { List<V1OwnerReference> refs = rs.getMetadata().getOwnerReferences(); Optional<V1OwnerReference> ref = refs.stream().filter(o -> o.getController() != null && o.getController()).findAny(); // Only include those whose ControllerRef matches the Deployment. if (ref.isPresent() && ref.get().getUid().equals(deployment.getMetadata().getUid())) { owned.add(rs); } } return owned; } private static List<V1ReplicaSet> rsListFromClient( String namespace, String selector, AppsV1Api api) throws ApiException { V1ReplicaSetList rsList = api.listNamespacedReplicaSet( namespace, null, null, null, null, selector, null, null, null, null, null); return rsList.getItems(); } /** * findNewReplicaSet returns the new RS this given deployment targets (the one with the same pod * template) */ private static V1ReplicaSet findNewReplicaSet( V1Deployment deployment, List<V1ReplicaSet> rsList) { rsList.sort( (o1, o2) -> { if (o1.getMetadata() .getCreationTimestamp() .equals(o2.getMetadata().getCreationTimestamp())) { return o1.getMetadata().getName().compareTo(o2.getMetadata().getName()); } if (o1.getMetadata() .getCreationTimestamp() .isBefore(o2.getMetadata().getCreationTimestamp())) { return -1; } return 1; }); for (V1ReplicaSet rs : rsList) { if (equalIgnoreHash(rs.getSpec().getTemplate(), deployment.getSpec().getTemplate())) { return rs; } } // new ReplicaSet does not exist. return null; } /** * EqualIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value * of Labels[pod-template-hash] We ignore pod-template-hash because: 1. The hash result would be * different upon podTemplateSpec API changes (e.g. the addition of a new field will cause the * hash code to change) 2. The deployment template won't have hash labels */ private static boolean equalIgnoreHash(V1PodTemplateSpec template1, V1PodTemplateSpec template2) { if (!Objects.equals(template1.getSpec(), template2.getSpec())) return false; V1ObjectMeta m1Copy = objectMetaDeepCopy(template1.getMetadata()); V1ObjectMeta m2Copy = objectMetaDeepCopy(template2.getMetadata()); m1Copy.getLabels().remove(DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY); m2Copy.getLabels().remove(DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY); return m1Copy.equals(m2Copy); } /** * FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the * given list of RSes. Note that the first set of old replica sets doesn't include the ones with * no pods, and the second set of old replica sets include all old replica sets. */ private static void findOldReplicaSets( List<V1ReplicaSet> rsList, V1ReplicaSet newRs, List<V1ReplicaSet> oldRSes, List<V1ReplicaSet> allOldRSes) { for (V1ReplicaSet rs : rsList) { // Filter out new replica set if (newRs != null && rs.getMetadata().getUid().equals(newRs.getMetadata().getUid())) { continue; } allOldRSes.add(rs); if (!rs.getSpec().getReplicas().equals(0)) { oldRSes.add(rs); } } } private static V1ObjectMeta objectMetaDeepCopy(V1ObjectMeta meta) { String data = Yaml.dump(meta); return Yaml.loadAs(data, V1ObjectMeta.class); } }
extended/src/main/java/io/kubernetes/client/extended/kubectl/util/deployment/DeploymentHelper.java
feat : add kubectl deployment util
extended/src/main/java/io/kubernetes/client/extended/kubectl/util/deployment/DeploymentHelper.java
feat : add kubectl deployment util
<ide><path>xtended/src/main/java/io/kubernetes/client/extended/kubectl/util/deployment/DeploymentHelper.java <add>/* <add>Copyright 2021 The Kubernetes Authors. <add>Licensed under the Apache License, Version 2.0 (the "License"); <add>you may not use this file except in compliance with the License. <add>You may obtain a copy of the License at <add>http://www.apache.org/licenses/LICENSE-2.0 <add>Unless required by applicable law or agreed to in writing, software <add>distributed under the License is distributed on an "AS IS" BASIS, <add>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add>See the License for the specific language governing permissions and <add>limitations under the License. <add>*/ <add>package io.kubernetes.client.extended.kubectl.util.deployment; <add> <add>import io.kubernetes.client.openapi.ApiException; <add>import io.kubernetes.client.openapi.apis.AppsV1Api; <add>import io.kubernetes.client.openapi.models.V1Deployment; <add>import io.kubernetes.client.openapi.models.V1ObjectMeta; <add>import io.kubernetes.client.openapi.models.V1OwnerReference; <add>import io.kubernetes.client.openapi.models.V1PodTemplateSpec; <add>import io.kubernetes.client.openapi.models.V1ReplicaSet; <add>import io.kubernetes.client.openapi.models.V1ReplicaSetList; <add>import io.kubernetes.client.util.Yaml; <add>import io.kubernetes.client.util.labels.LabelSelector; <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Objects; <add>import java.util.Optional; <add> <add>public class DeploymentHelper { <add> <add> public static final String DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY = "pod-template-hash"; <add> public static final String REVISION_ANNOTATION = "deployment.kubernetes.io/revision"; <add> <add> /** <add> * getAllReplicaSets get the old replica sets and return new replica targeted by the given <add> * Deployment. It gets PodList and ReplicaSetList from client interface. Note that the first set <add> * of old replica sets doesn't include the ones with no pods, and the second set of old replica <add> * sets include all old replica sets. The returned value is the new replica set, and it may be nil <add> * if it doesn't exist yet. <add> * <add> * @param deployment the given deployment <add> * @param api the client interface <add> * @param oldRSes container of all old ReplicaSet exclude the ones with no pods <add> * @param allOldRSes container of all old ReplicaSet <add> * @return the new replica set <add> */ <add> public static V1ReplicaSet getAllReplicaSets( <add> V1Deployment deployment, <add> AppsV1Api api, <add> List<V1ReplicaSet> oldRSes, <add> List<V1ReplicaSet> allOldRSes) <add> throws ApiException { <add> List<V1ReplicaSet> rsList = listReplicaSets(deployment, api); <add> V1ReplicaSet newRs = findNewReplicaSet(deployment, rsList); <add> findOldReplicaSets(rsList, newRs, oldRSes, allOldRSes); <add> return newRs; <add> } <add> <add> /** <add> * revision returns the revision number of the input object. <add> * <add> * @param meta metadata of object <add> * @return the revision number <add> */ <add> public static Long revision(V1ObjectMeta meta) { <add> String v = meta.getAnnotations().get(REVISION_ANNOTATION); <add> return v == null ? 0L : Long.parseLong(v); <add> } <add> <add> /** <add> * listReplicaSets returns a list of RSes the given deployment targets. Note that this does NOT <add> * attempt to reconcile ControllerRef (adopt/orphan), because only the controller itself should do <add> * that. However, it does filter out anything whose ControllerRef doesn't match. <add> */ <add> private static List<V1ReplicaSet> listReplicaSets(V1Deployment deployment, AppsV1Api api) <add> throws ApiException { <add> String namespace = deployment.getMetadata().getNamespace(); <add> LabelSelector selector = LabelSelector.parse(deployment.getSpec().getSelector()); <add> List<V1ReplicaSet> all = rsListFromClient(namespace, selector.toString(), api); <add> List<V1ReplicaSet> owned = new ArrayList<>(all.size()); <add> for (V1ReplicaSet rs : all) { <add> List<V1OwnerReference> refs = rs.getMetadata().getOwnerReferences(); <add> Optional<V1OwnerReference> ref = <add> refs.stream().filter(o -> o.getController() != null && o.getController()).findAny(); <add> // Only include those whose ControllerRef matches the Deployment. <add> if (ref.isPresent() && ref.get().getUid().equals(deployment.getMetadata().getUid())) { <add> owned.add(rs); <add> } <add> } <add> return owned; <add> } <add> <add> private static List<V1ReplicaSet> rsListFromClient( <add> String namespace, String selector, AppsV1Api api) throws ApiException { <add> V1ReplicaSetList rsList = <add> api.listNamespacedReplicaSet( <add> namespace, null, null, null, null, selector, null, null, null, null, null); <add> return rsList.getItems(); <add> } <add> <add> /** <add> * findNewReplicaSet returns the new RS this given deployment targets (the one with the same pod <add> * template) <add> */ <add> private static V1ReplicaSet findNewReplicaSet( <add> V1Deployment deployment, List<V1ReplicaSet> rsList) { <add> rsList.sort( <add> (o1, o2) -> { <add> if (o1.getMetadata() <add> .getCreationTimestamp() <add> .equals(o2.getMetadata().getCreationTimestamp())) { <add> return o1.getMetadata().getName().compareTo(o2.getMetadata().getName()); <add> } <add> if (o1.getMetadata() <add> .getCreationTimestamp() <add> .isBefore(o2.getMetadata().getCreationTimestamp())) { <add> return -1; <add> } <add> return 1; <add> }); <add> for (V1ReplicaSet rs : rsList) { <add> if (equalIgnoreHash(rs.getSpec().getTemplate(), deployment.getSpec().getTemplate())) { <add> return rs; <add> } <add> } <add> // new ReplicaSet does not exist. <add> return null; <add> } <add> <add> /** <add> * EqualIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value <add> * of Labels[pod-template-hash] We ignore pod-template-hash because: 1. The hash result would be <add> * different upon podTemplateSpec API changes (e.g. the addition of a new field will cause the <add> * hash code to change) 2. The deployment template won't have hash labels <add> */ <add> private static boolean equalIgnoreHash(V1PodTemplateSpec template1, V1PodTemplateSpec template2) { <add> if (!Objects.equals(template1.getSpec(), template2.getSpec())) return false; <add> V1ObjectMeta m1Copy = objectMetaDeepCopy(template1.getMetadata()); <add> V1ObjectMeta m2Copy = objectMetaDeepCopy(template2.getMetadata()); <add> m1Copy.getLabels().remove(DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY); <add> m2Copy.getLabels().remove(DEFAULT_DEPLOYMENT_UNIQUE_LABEL_KEY); <add> return m1Copy.equals(m2Copy); <add> } <add> <add> /** <add> * FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the <add> * given list of RSes. Note that the first set of old replica sets doesn't include the ones with <add> * no pods, and the second set of old replica sets include all old replica sets. <add> */ <add> private static void findOldReplicaSets( <add> List<V1ReplicaSet> rsList, <add> V1ReplicaSet newRs, <add> List<V1ReplicaSet> oldRSes, <add> List<V1ReplicaSet> allOldRSes) { <add> for (V1ReplicaSet rs : rsList) { <add> // Filter out new replica set <add> if (newRs != null && rs.getMetadata().getUid().equals(newRs.getMetadata().getUid())) { <add> continue; <add> } <add> allOldRSes.add(rs); <add> if (!rs.getSpec().getReplicas().equals(0)) { <add> oldRSes.add(rs); <add> } <add> } <add> } <add> <add> private static V1ObjectMeta objectMetaDeepCopy(V1ObjectMeta meta) { <add> String data = Yaml.dump(meta); <add> return Yaml.loadAs(data, V1ObjectMeta.class); <add> } <add>}
JavaScript
apache-2.0
0f7abf1de69cbaeeea60d3a3158cd96fb009ad4b
0
marlonruo/weather,marlonruo/weather
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { // onSuccess Callback // This method accepts a Position object, which contains the // current GPS coordinates // // onSuccess Callback // This method accepts a `Position` object, which contains // the current GPS coordinates // function onSuccess(position) { var element = document.getElementById('ubi'); element.innerHTML = position.coords.latitude+", "+position.coords.longitude var cordenadas = position.coords.latitude+", "+position.coords.longitude var Result0 = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text=%2219.5787916,-99.2462466%22%20and%20gflags=%22R%22&format=json", "", function (data0) { alert(data0.query.results.Result.line3) $('#tt1').html(data0.query.results.Result.line3) }); } // onError Callback receives a PositionError object // function onError(error) { } // Options: throw an error if no update is received every 30 seconds. // var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {enableHighAccuracy: true }); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } };
www/js/index.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { // onSuccess Callback // This method accepts a Position object, which contains the // current GPS coordinates // // onSuccess Callback // This method accepts a `Position` object, which contains // the current GPS coordinates // function onSuccess(position) { var element = document.getElementById('ubi'); element.innerHTML = position.coords.latitude+", "+position.coords.longitude var cordenadas = position.coords.latitude+", "+position.coords.longitude var Result0 = $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22atizapan%20mexico%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", "", function (data0) { $('#tt1').html(data0.query.results.Result.line3) }); } // onError Callback receives a PositionError object // function onError(error) { } // Options: throw an error if no update is received every 30 seconds. // var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {enableHighAccuracy: true }); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } };
as as
www/js/index.js
as
<ide><path>ww/js/index.js <ide> var cordenadas = position.coords.latitude+", "+position.coords.longitude <ide> <ide> <del> var Result0 = $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22atizapan%20mexico%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", "", <add> var Result0 = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text=%2219.5787916,-99.2462466%22%20and%20gflags=%22R%22&format=json", "", <ide> function (data0) <ide> { <add> alert(data0.query.results.Result.line3) <ide> $('#tt1').html(data0.query.results.Result.line3) <ide> }); <ide>
JavaScript
bsd-3-clause
6165e23f41f0555b9115325e91eca6493d899156
0
taras101/simple_grove,taras101/simple_grove,taras101/simple_grove
$(document).ready(function(){ var treeData = { name: "Grove", value: 1, contents: [ {name: "First Tree", value: -6, contents: [ { name: "", value: -13, contents: [ { name: "", value: -17, contents: [ { name: "1T2", value: 6 }, { name: "1T3", value: -16 }, { name: "1T4", value: -5 } ] }, { name: "", value: 7, contents: [ { name: "1T9" , value: 19 }, { name: "1T15" , value: -5} ] }, { name: "", value: 1, contents: [ { name: "", value: -18, contents: [ { name: "1T6", value: 19 }, { name: "1T7", value: -55 }, { name: "1T8", value: -19 } ] }, { name: "", value: 5, contents: [ { name: "1T10", value: -12 } ] }, { name: "", value: -12, contents: [ { name: "1T11", value: 4}, { name: "", value: 4, contents: [ { name: "1T12", value: 4}, { name: "1T13", value: 1}, { name: "1T14", value: 6} ] } ] }, { name: "", value: 3, contents: [ { name: "1T1", value: -4 } ] } ] }, { name: "1T5", value: -20 } ] }, ] }, { name: "Second Tree", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "2T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "2T2", value: 14 }, { name: "2T3", value: 4 } ] }, { name: "", value: 4, contents: [ { name: "2T4", value: -39 }, { name: "2T5", value: 6 }, { name: "2T6", value: -14 }, { name: "2T7", value: 6 }, { name: "2T8", value: 60 }, { name: "", value: 4, contents: [ { name: "2T9", value: -6 }, { name: "2T10", value: 2, contents: [ { name: "2T11", value: 18 }, { name: "2T12", value: 15 }, ] }, ] }, { name: "", value: 2, contents: [ { name: "2T13", value: 15 }, { name: "2T14", value: -6 }, { name: "2T15", value: 4 } ] }, ] } ] }, { name: "Third Tree", value: 6, contents: [ { name: "", value: 14, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents:[ { name: "3T1", value: -4 } ] }, ] }, { name: "", value: 4, contents: [ { name: "3T2", value: 7 }, { name: "3T3", value: -4 }, { name: "3T4", value: 4 }, { name: "3T5", value: 1, contents: [ { name: "3T12", value: -9 }, { name: "3T13", value: 12 }, { name: "3T14", value: 8 }, { name: "3T15", value: -6 }, { name: "3T16", value: 4 } ] }, { name: "3T6", value: 2 }, { name: "3T7", value: -44 }, { name: "3T8", value: 7 }, { name: "3T9", value: -23 }, { name: "3T10", value: 9 }, { name: "3T11", value: 4 } ] }, { name: "", value: -6, contents: [ { name: "", value: -2, contents: [ { name: "3T17", value: -3 }, { name: "3T18", value: 8 }, { name: "", value: 12, contents: [ { name: "3T19", value: 11 }, { name: "3T20", value: -4 } ] }, ] }, ] }, { name: "", value: 2, contents: [ { name: "", value: -2, contents: [ { name: "3T21", value: 8 }, { name: "3T22", value: -2 }, { name: "", value: -12, contents: [ { name: "3T24", value: 11 }, { name: "3T25", value: -4 } ] }, { name: "", value: 2, contents: [ { name: "3T23", value: -4 } ] }, ] }, ] }, { name: "", value: 28, contents: [ { name: "", value: -10, contents: [ { name: "3T26", value: -42 }, ] }, ] }, { name: "", value: 6, contents: [ { name: "", value: 10, contents: [ { name: "3T27", value: 1 }, ] }, ] }, { name: "", value: 4, contents: [ { name: "", value: -4, contents: [ { name: "3T28", value: 12 }, ] }, ] }, { name: "", value: 3, contents: [ { name: "", value: -18, contents: [ { name: "3T29", value: -15 }, ] }, ] }, { name: "", value: 12, contents: [ { name: "", value: 6, contents: [ { name: "", value: 7, contents: [ { name: "3T30", value: 12 }, ] }, ] }, ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "3T31", value: 12 }, ] }, ] } ] } ] }, { name: "Forth Tree", value: 6, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "4T1", value: 4 }, ] } ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "4T2", value: 13 }, { name: "4T3", value: 2 }, { name: "", value: -12, contents: [ { name: "4T4", value: 6 } ] }, ] } ] }, { name: "", value: -4, contents: [ { name: "4T5", value: 14, } ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "4T6", value: 13 }, { name: "", value: -12, contents: [ { name: "4T7", value: 19 } ] }, { name: "", value: 2, contents: [ { name: "4T8", value: -5 } ] }, { name: "", value: -2, contents: [ { name: "", value: 8 , contents: [ { name: "4T9", value: -7 } ] }, ] }, { name: "", value: 4, contents: [ { name: "4T10", value: 6, contents: [ { name: "4T9", value: 13 } ] } ] }, { name: "", value: 2, contents: [ { name: "4T11", value: 17 } ] }, ] }, ] }, ] }, { name: "Fifth Tree", value: 6, contents: [ { name: "", value: 4, contents: [ { name: "5T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "5T2", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "5T3", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "", value: 10, contents: [ { name: "5T6", value: 13 } ] }, ] }, { name: "", value: -4, contents: [ { name: "5T4", value: 14, } ] }, { name: "", value: 10, contents: [ { name: "5T5", value: -14, } ] }, { name: "", value: -4, contents: [ { name: "5T7", value: -33, } ] }, { name: "", value: -4, contents: [ { name: "5T8", value: -69, } ] }, { name: "", value: 4, contents: [ { name: "5T9", value: 19, } ] }, { name: "", value: 14, contents: [ { name: "5T10", value: 5 } ] } ] }, { name: "Sixth Tree", value: 16, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "6T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "6T2", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "6T3", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "6T6", value: 10 }, ] }, { name: "", value: -4, contents: [ { name: "6T4", value: -23, } ] }, { name: "", value: 10, contents: [ { name: "6T5", value: 34, } ] }, { name: "", value: -4, contents: [ { name: "", value: -3, contents: [ { name: "6T12", value: 21 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -2, contents: [ { name: "", value: 6, contents: [ { name: "6T14", value: 16, } ] } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -9, contents: [ { name: "6T13", value: -21 } ] } ] }, { name: "", value: 1, contents: [ { name: "6T10", value: 5 } ] }, { name: "", value: -4, contents: [ { name: "6T11", value: -15 } ] }, { name: "", value: 16, contents: [ { name: "6T7", value: -45 } ] }, { name: "", value: 11, contents: [ { name: "6T9", value: -15 } ] }, { name: "", value: 14, contents: [ { name: "6T8", value: -25 } ] } ] } ] } ] }, { name: "Seventh Tree", value: 10, contents: [ { name: "", value: 4, contents: [ { name: "7T1", value: 14 } ] }, { name: "", value: 6, contents: [ { name: "7T2", value: -1 } ] }, { name: "", value: -4, contents: [ { name: "7T3", value: 44, } ] }, { name: "", value: 16, contents: [ { name: "7T4", value: 13 }, ] }, { name: "", value: -4, contents: [ { name: "7T5", value: 3, } ] }, { name: "", value: 10, contents: [ { name: "7T6", value: 11, } ] }, { name: "", value: -4, contents: [ { name: "", value: 9, contents: [ { name: "7T7", value:-66 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -8, contents: [ { name: "7T8", value: 16 } ] } ] }, { name: "", value: 4, contents: [ { name: "", value: -9, contents: [ { name: "7T9", value: -13 } ] } ] }, { name: "", value: 1, contents: [ { name: "", value: 5, contents: [ { name: "7T10", value: 5 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: 0, contents: [ { name: "7T11", value: -19 } ] } ] }, { name: "", value: 16, contents: [ { name: "", value: -5, contents: [ { name: "7T12", value: -13 } ] } ] }, { name: "", value: 11, contents: [ { name: "7T13", value: -15 } ] }, { name: "", value: 14, contents: [ { name: "7T14", value: -25 }, { name: "7T15", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "7T16", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "7T17", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "7T18", value: 10 }, ] }, { name: "", value: -4, contents: [ { name: "7T19", value: -23, } ] }, { name: "", value: 10, contents: [ { name: "7T20", value: 34, } ] }, { name: "", value: -4, contents: [ { name: "", value: -3, contents: [ { name: "7T21", value: 21 } ] } ] } ] } ] }; function visit(parent, visitFn, childrenFn) { if (!parent) return; visitFn(parent); var children = childrenFn(parent); if (children) { var count = children.length; for (var i = 0; i < count; i++) { visit(children[i], visitFn, childrenFn); } }; } var ui; function buildTree(containerName, customOptions) { // build the options object var options = $.extend({ nodeRadius: 4, fontSize: 12 }, customOptions); // Calculate total nodes, max label length var totalNodes = 0; var maxLabelLength = 0; visit(treeData, function(d) { totalNodes++; maxLabelLength = Math.max(d.name.length, maxLabelLength); }, function(d) { return d.contents && d.contents.length > 0 ? d.contents : null; }); // size of the diagram var size = { width:$(containerName).outerWidth() , height: (totalNodes * 4) }; var tree = d3.layout.tree() .sort(null) .size([size.width -15, size.height - 40]) .children(function(d) { return (!d.contents || d.contents.length === 0) ? null : d.contents; }); var nodes = tree.nodes(treeData); var links = tree.links(nodes); var svgRoot = d3.select(containerName) .append("svg:svg").attr("height", size.height+10).attr("width", size.width); // Add the clipping path svgRoot.append("svg:clipPath").attr("id", "clipper") .append("svg:rect") .attr('id', 'clip-rect'); var layoutRoot = svgRoot .append("svg:g") .attr("class", "container") .attr("transform", "translate(5," + size.height + ")"); // Edges between nodes as a <path class="link" /> var link = d3.svg.diagonal() .projection(function(d) { if(d.value !=undefined){ return [(d.x - d.value) , (-d.y + d.value) ]; } else{ return [d.x , (-d.y ) ]; } }); var linkGroup = layoutRoot.append("svg:g"); linkGroup.selectAll("path.link") .data(links) .enter() .append("svg:path") .attr("class", "link") .attr("d", link); var animGroup = layoutRoot.append("svg:g") .attr("clip-path", "url(#clipper)"); var nodeGroup = layoutRoot.selectAll("g.node") .data(nodes) .enter() .append("svg:g") .attr("class", "node") .attr("transform", function(d) { var transpointx = d.x - d.value; var transpointy = -d.y + d.value; return "translate(" + transpointx + "," + transpointy + ")"; }); // Cache the UI elements ui = { svgRoot: svgRoot, nodeGroup: nodeGroup, linkGroup: linkGroup, animGroup: animGroup }; // Attach the hover and click handlers setupMouseEvents(); nodeGroup.append("svg:image") .attr("id", "leaf") .attr("xlink:href", "svg-leave3.svg") .attr("width", 20) .attr("height", 20) .attr("transform", "translate(-10,-10)"); }// close build tree var dur = 0; var matchedLinks = []; function setupMouseEvents(){ ui.nodeGroup.on('mouseover', function(d, i) {if(d.name != ""){ d3.select(this).select("image") .attr('href','svg-leave4.svg') .attr("height", "24px") .attr("width", "24px") .classed("hovers", true); } }) .on('mouseout', function(d, i) {if(d.name != ""){ d3.select(this).select("image") .attr('href','svg-leave3.svg') .attr("height", "20px") .attr("width", "20px") .classed("hovers", false); } }) .on('click', function(nd, i) {if(nd.name != ""){ d3.select(this).select("image") .attr('href','svg-leave4.svg') .attr("height", "24px") .attr("width", "24px"); //animate leaf falling d3.select(this).select("image") .transition() .attr("transform", "translate(-25,35) rotate(75)") .duration(1600) .delay(800) .transition() .attr("transform", "translate(15,80) rotate(25)") .duration(1600) .delay(2000) .transition() .attr("transform", "translate(-25,135) rotate(75)") .duration(1600) .delay(3200) .transition() .attr("transform", "translate(35,185) rotate(25)") .duration(1600) .delay(4400) .transition() .attr("transform", "translate(-45,235) rotate(75)") .duration(1600) .delay(5600) .transition() .attr("transform", "translate(35,285) rotate(25)") .duration(1600) .delay(6800) .transition() .attr("transform", "translate(-45,335) rotate(75)") .duration(1600) .delay(8000) .transition() .attr("transform", "translate(35,385) rotate(25)") .duration(1600) .delay(9200) .transition() .attr("transform", "translate(-45,435) rotate(75)") .duration(1600) .delay(10400) .transition() .attr("transform", "translate(35,485) rotate(25)") .duration(1600) .delay(11600) .transition() .attr("transform", "translate(-45,535) rotate(75)") .duration(1600) .delay(12800) .transition() .attr("transform", "translate(35,585) rotate(25)") .duration(1600) .delay(14000) .transition() .attr("transform", "translate(-45,635) rotate(75)") .duration(1600) .delay(15200) .transition() .attr("transform", "translate(35,685) rotate(25)") .duration(1600) .delay(16400) .transition() .attr("transform", "translate(-45,735) rotate(75)") .duration(1600) .delay(17600) .transition() .attr("transform", "translate(35,785) rotate(25)") .duration(1600) .delay(18800) .remove(); // Walk parent chain var ancestors = []; var parent = nd; while (!_.isUndefined(parent)) { ancestors.push(parent); parent = parent.parent; }; // Get the matched links ui.linkGroup.selectAll('path.link') .filter(function(d, i) { return _.any(ancestors, function(p) { return p === d.target; }); }) .each(function(d) { matchedLinks.push(d); }); var last_element = matchedLinks[matchedLinks.length - 1]; // SC.initialize({ // client_id: "d99a29c1a7bd281b1ef4a833d3ab6dad" // //client secret e2e93639e0df982ea9aed3b69a7492f5 // }); var track = last_element.target.name; //play track soundManager.play(track); //set node to empty name so mouseout does not happen nd.name =""; } }); } var nodeVPosition=0; function animateParentChain(links){ var linkRenderer = d3.svg.diagonal() .projection(function(d){ if(d.value !=undefined){ nodeVPosition = d.y; return [(d.x - d.value) , (-d.y + d.value) ]; } else{ return [d.x , (-d.y ) ]; } }); // Links ui.animGroup.selectAll("path.selected") .data([]) .exit().remove(); ui.animGroup .selectAll("path.selected") .data(links) .enter().append("svg:path") .attr("class", "selected") .attr("d", linkRenderer); // Animate the clipping path var overlayBox = ui.svgRoot.node().getBBox(); ui.svgRoot.select("#clip-rect") .attr("x", overlayBox.x ) .attr("y", 0) .attr("width", overlayBox.width) .attr("height", 50) .transition().duration(soundDuration) .ease("linear") .attr("y", overlayBox.y -(115 + nodeVPosition)) .attr("height", 50); } //Soundmanager //set client id for soundcloud var sid = "/stream?client_id=d99a29c1a7bd281b1ef4a833d3ab6dad"; soundManager.setup({ // where to find flash audio SWFs, as needed url: '/.', onready: function() { soundManager.createSound({ id: 'two', // optional: provide your own unique id url: 'PIano Improvs6-first tree2.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; // console.log(soundDuration); //setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); console.log(soundDuration); animateParentChain(matchedLinks,soundManager); // },2500); } } }); soundManager.createSound({ id: 'three', // optional: provide your own unique id url: 'PIano Improvs6-first tree3.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; console.log(soundDuration); } } }); soundManager.createSound({ id: '6T1', // optional: provide your own unique id url: 'PIano Improvs6-first tree2.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; // console.log(soundDuration); //setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); console.log(soundDuration); animateParentChain(matchedLinks,soundManager); // },2500); } } }); soundManager.createSound({ id: 'ten', // optional: provide your own unique id url: 'http://api.soundcloud.com/tracks/155037359' + sid, multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration ; // setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); animateParentChain(matchedLinks); //animateParentChain(matchedLinks,soundManager); // },2500); } console.log(soundDuration); } }); soundManager.createSound({ id: '1T5', // optional: provide your own unique id url: 'http://api.soundcloud.com/tracks/155037359' + sid, multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration ; // setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); animateParentChain(matchedLinks); //animateParentChain(matchedLinks,soundManager); // },2500); } console.log(soundDuration); } }); }//close onready });//close soundmanager setup $(function(){ buildTree("#tree-container"); }); });
index2.js
$(document).ready(function(){ var treeData = { name: "Grove", value: 1, contents: [ {name: "First Tree", value: -6, contents: [ { name: "", value: -13, contents: [ { name: "", value: -17, contents: [ { name: "two", value: 6 }, { name: "three", value: -16 }, { name: "4", value: -5 } ] }, { name: "", value: 7, contents: [ { name: "9" , value: 19 }, { name: "15" , value: -5} ] }, { name: "", value: 1, contents: [ { name: "", value: -18, contents: [ { name: "6", value: 19 }, { name: "7", value: -55 }, { name: "8", value: -19 } ] }, { name: "", value: 5, contents: [ { name: "ten", value: -12 } ] }, { name: "", value: -12, contents: [ { name: "11", value: 4}, { name: "", value: 4, contents: [ { name: "4", value: 4}, { name: "13", value: 1}, { name: "14", value: 6} ] } ] }, { name: "", value: 3, contents: [ { name: "1", value: -4 } ] } ] }, { name: "5", value: -20, contents: [] } ] }, ] }, { name: "Second Tree", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "2T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "2T2", value: 14 }, { name: "2T3", value: 4 } ] }, { name: "", value: 4, contents: [ { name: "2T4", value: -39 }, { name: "2T5", value: 6 }, { name: "2T6", value: -14 }, { name: "2T7", value: 6 }, { name: "2T8", value: 60 }, { name: "", value: 4, contents: [ { name: "2T9", value: -6 }, { name: "2T10", value: 2, contents: [ { name: "2T11", value: 18 }, { name: "2T12", value: 15 }, ] }, ] }, { name: "", value: 2, contents: [ { name: "2T13", value: 15 }, { name: "2T14", value: -6 }, { name: "2T15", value: 4 } ] }, ] } ] }, { name: "Third Tree", value: 6, contents: [ { name: "", value: 14, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents:[ { name: "3T1", value: -4 } ] }, ] }, { name: "", value: 4, contents: [ { name: "3T2", value: 7 }, { name: "3T3", value: -4 }, { name: "3T4", value: 4 }, { name: "3T5", value: 1, contents: [ { name: "3T12", value: -9 }, { name: "3T13", value: 12 }, { name: "3T14", value: 8 }, { name: "3T15", value: -6 }, { name: "3T16", value: 4 } ] }, { name: "3T6", value: 2 }, { name: "3T7", value: -44 }, { name: "3T8", value: 7 }, { name: "3T9", value: -23 }, { name: "3T10", value: 9 }, { name: "3T11", value: 4 } ] }, { name: "", value: -6, contents: [ { name: "", value: -2, contents: [ { name: "3T17", value: -3 }, { name: "3T18", value: 8 }, { name: "", value: 12, contents: [ { name: "3T19", value: 11 }, { name: "3T20", value: -4 } ] }, ] }, ] }, { name: "", value: 2, contents: [ { name: "", value: -2, contents: [ { name: "3T21", value: 8 }, { name: "3T22", value: -2 }, { name: "", value: -12, contents: [ { name: "3T24", value: 11 }, { name: "3T25", value: -4 } ] }, { name: "", value: 2, contents: [ { name: "3T23", value: -4 } ] }, ] }, ] }, { name: "", value: 28, contents: [ { name: "", value: -10, contents: [ { name: "3T26", value: -42 }, ] }, ] }, { name: "", value: 6, contents: [ { name: "", value: 10, contents: [ { name: "3T27", value: 1 }, ] }, ] }, { name: "", value: 4, contents: [ { name: "", value: -4, contents: [ { name: "3T28", value: 12 }, ] }, ] }, { name: "", value: 3, contents: [ { name: "", value: -18, contents: [ { name: "3T29", value: -15 }, ] }, ] }, { name: "", value: 12, contents: [ { name: "", value: 6, contents: [ { name: "", value: 7, contents: [ { name: "3T30", value: 12 }, ] }, ] }, ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "3T31", value: 12 }, ] }, ] } ] } ] }, { name: "Forth Tree", value: 6, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "4T1", value: 4 }, ] } ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "4T2", value: 13 }, { name: "4T3", value: 2 }, { name: "", value: -12, contents: [ { name: "4T4", value: 6 } ] }, ] } ] }, { name: "", value: -4, contents: [ { name: "4T5", value: 14, } ] }, { name: "", value: 6, contents: [ { name: "", value: -10, contents: [ { name: "4T6", value: 13 }, { name: "", value: -12, contents: [ { name: "4T7", value: 19 } ] }, { name: "", value: 2, contents: [ { name: "4T8", value: -5 } ] }, { name: "", value: -2, contents: [ { name: "", value: 8 , contents: [ { name: "4T9", value: -7 } ] }, ] }, { name: "", value: 4, contents: [ { name: "4T10", value: 6, contents: [ { name: "4T9", value: 13 } ] } ] }, { name: "", value: 2, contents: [ { name: "4T11", value: 17 } ] }, ] }, ] }, ] }, { name: "Fifth Tree", value: 6, contents: [ { name: "", value: 4, contents: [ { name: "5T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "5T2", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "5T3", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "", value: 10, contents: [ { name: "5T6", value: 13 } ] }, ] }, { name: "", value: -4, contents: [ { name: "5T4", value: 14, } ] }, { name: "", value: 10, contents: [ { name: "5T5", value: -14, } ] }, { name: "", value: -4, contents: [ { name: "5T7", value: -33, } ] }, { name: "", value: -4, contents: [ { name: "5T8", value: -69, } ] }, { name: "", value: 4, contents: [ { name: "5T9", value: 19, } ] }, { name: "", value: 14, contents: [ { name: "5T10", value: 5 } ] } ] }, { name: "Sixth Tree", value: 16, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "", value: 4, contents: [ { name: "6T1", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "6T2", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "6T3", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "6T6", value: 10 }, ] }, { name: "", value: -4, contents: [ { name: "6T4", value: -23, } ] }, { name: "", value: 10, contents: [ { name: "6T5", value: 34, } ] }, { name: "", value: -4, contents: [ { name: "", value: -3, contents: [ { name: "6T12", value: 21 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -2, contents: [ { name: "", value: 6, contents: [ { name: "6T14", value: 16, } ] } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -9, contents: [ { name: "6T13", value: -21 } ] } ] }, { name: "", value: 1, contents: [ { name: "6T10", value: 5 } ] }, { name: "", value: -4, contents: [ { name: "6T11", value: -15 } ] }, { name: "", value: 16, contents: [ { name: "6T7", value: -45 } ] }, { name: "", value: 11, contents: [ { name: "6T9", value: -15 } ] }, { name: "", value: 14, contents: [ { name: "6T8", value: -25 } ] } ] } ] } ] }, { name: "Seventh Tree", value: 10, contents: [ { name: "", value: 4, contents: [ { name: "7T1", value: 14 } ] }, { name: "", value: 6, contents: [ { name: "7T2", value: -1 } ] }, { name: "", value: -4, contents: [ { name: "7T3", value: 44, } ] }, { name: "", value: 16, contents: [ { name: "7T4", value: 13 }, ] }, { name: "", value: -4, contents: [ { name: "7T5", value: 3, } ] }, { name: "", value: 10, contents: [ { name: "7T6", value: 11, } ] }, { name: "", value: -4, contents: [ { name: "", value: 9, contents: [ { name: "7T7", value:-66 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: -8, contents: [ { name: "7T8", value: 16 } ] } ] }, { name: "", value: 4, contents: [ { name: "", value: -9, contents: [ { name: "7T9", value: -13 } ] } ] }, { name: "", value: 1, contents: [ { name: "", value: 5, contents: [ { name: "7T10", value: 5 } ] } ] }, { name: "", value: -4, contents: [ { name: "", value: 0, contents: [ { name: "7T11", value: -19 } ] } ] }, { name: "", value: 16, contents: [ { name: "", value: -5, contents: [ { name: "7T12", value: -13 } ] } ] }, { name: "", value: 11, contents: [ { name: "7T13", value: -15 } ] }, { name: "", value: 14, contents: [ { name: "7T14", value: -25 }, { name: "7T15", value: 4 } ] }, { name: "", value: 6, contents: [ { name: "7T16", value: -10 } ] }, { name: "", value: -4, contents: [ { name: "7T17", value: 14, } ] }, { name: "", value: 16, contents: [ { name: "7T18", value: 10 }, ] }, { name: "", value: -4, contents: [ { name: "7T19", value: -23, } ] }, { name: "", value: 10, contents: [ { name: "7T20", value: 34, } ] }, { name: "", value: -4, contents: [ { name: "", value: -3, contents: [ { name: "7T21", value: 21 } ] } ] } ] } ] }; function visit(parent, visitFn, childrenFn) { if (!parent) return; visitFn(parent); var children = childrenFn(parent); if (children) { var count = children.length; for (var i = 0; i < count; i++) { visit(children[i], visitFn, childrenFn); } }; } var ui; function buildTree(containerName, customOptions) { // build the options object var options = $.extend({ nodeRadius: 4, fontSize: 12 }, customOptions); // Calculate total nodes, max label length var totalNodes = 0; var maxLabelLength = 0; visit(treeData, function(d) { totalNodes++; maxLabelLength = Math.max(d.name.length, maxLabelLength); }, function(d) { return d.contents && d.contents.length > 0 ? d.contents : null; }); // size of the diagram var size = { width:$(containerName).outerWidth() , height: (totalNodes * 4) }; var tree = d3.layout.tree() .sort(null) .size([size.width -15, size.height - 40]) .children(function(d) { return (!d.contents || d.contents.length === 0) ? null : d.contents; }); var nodes = tree.nodes(treeData); var links = tree.links(nodes); var svgRoot = d3.select(containerName) .append("svg:svg").attr("height", size.height+10).attr("width", size.width); // Add the clipping path svgRoot.append("svg:clipPath").attr("id", "clipper") .append("svg:rect") .attr('id', 'clip-rect'); var layoutRoot = svgRoot .append("svg:g") .attr("class", "container") .attr("transform", "translate(5," + size.height + ")"); // Edges between nodes as a <path class="link" /> var link = d3.svg.diagonal() .projection(function(d) { if(d.value !=undefined){ return [(d.x - d.value) , (-d.y + d.value) ]; } else{ return [d.x , (-d.y ) ]; } }); var linkGroup = layoutRoot.append("svg:g"); linkGroup.selectAll("path.link") .data(links) .enter() .append("svg:path") .attr("class", "link") .attr("d", link); var animGroup = layoutRoot.append("svg:g") .attr("clip-path", "url(#clipper)"); var nodeGroup = layoutRoot.selectAll("g.node") .data(nodes) .enter() .append("svg:g") .attr("class", "node") .attr("transform", function(d) { var transpointx = d.x - d.value; var transpointy = -d.y + d.value; return "translate(" + transpointx + "," + transpointy + ")"; }); // Cache the UI elements ui = { svgRoot: svgRoot, nodeGroup: nodeGroup, linkGroup: linkGroup, animGroup: animGroup }; // Attach the hover and click handlers setupMouseEvents(); nodeGroup.append("svg:image") .attr("id", "leaf") .attr("xlink:href", "svg-leave3.svg") .attr("width", 20) .attr("height", 20) .attr("transform", "translate(-10,-10)"); }// close build tree var dur = 0; var matchedLinks = []; function setupMouseEvents(){ ui.nodeGroup.on('mouseover', function(d, i) {if(d.name != ""){ d3.select(this).select("image") .attr('href','svg-leave4.svg') .attr("height", "24px") .attr("width", "24px") .classed("hovers", true); } }) .on('mouseout', function(d, i) {if(d.name != ""){ d3.select(this).select("image") .attr('href','svg-leave3.svg') .attr("height", "20px") .attr("width", "20px") .classed("hovers", false); } }) .on('click', function(nd, i) {if(nd.name != ""){ d3.select(this).select("image") .attr('href','svg-leave4.svg') .attr("height", "24px") .attr("width", "24px"); //animate leaf falling d3.select(this).select("image") .transition() .attr("transform", "translate(-25,35) rotate(75)") .duration(1600) .delay(800) .transition() .attr("transform", "translate(15,80) rotate(25)") .duration(1600) .delay(2000) .transition() .attr("transform", "translate(-25,135) rotate(75)") .duration(1600) .delay(3200) .transition() .attr("transform", "translate(35,185) rotate(25)") .duration(1600) .delay(4400) .transition() .attr("transform", "translate(-45,235) rotate(75)") .duration(1600) .delay(5600) .transition() .attr("transform", "translate(35,285) rotate(25)") .duration(1600) .delay(6800) .transition() .attr("transform", "translate(-45,335) rotate(75)") .duration(1600) .delay(8000) .transition() .attr("transform", "translate(35,385) rotate(25)") .duration(1600) .delay(9200) .transition() .attr("transform", "translate(-45,435) rotate(75)") .duration(1600) .delay(10400) .transition() .attr("transform", "translate(35,485) rotate(25)") .duration(1600) .delay(11600) .transition() .attr("transform", "translate(-45,535) rotate(75)") .duration(1600) .delay(12800) .transition() .attr("transform", "translate(35,585) rotate(25)") .duration(1600) .delay(14000) .transition() .attr("transform", "translate(-45,635) rotate(75)") .duration(1600) .delay(15200) .transition() .attr("transform", "translate(35,685) rotate(25)") .duration(1600) .delay(16400) .transition() .attr("transform", "translate(-45,735) rotate(75)") .duration(1600) .delay(17600) .transition() .attr("transform", "translate(35,785) rotate(25)") .duration(1600) .delay(18800) .remove(); // Walk parent chain var ancestors = []; var parent = nd; while (!_.isUndefined(parent)) { ancestors.push(parent); parent = parent.parent; }; // Get the matched links ui.linkGroup.selectAll('path.link') .filter(function(d, i) { return _.any(ancestors, function(p) { return p === d.target; }); }) .each(function(d) { matchedLinks.push(d); }); var last_element = matchedLinks[matchedLinks.length - 1]; // SC.initialize({ // client_id: "d99a29c1a7bd281b1ef4a833d3ab6dad" // //client secret e2e93639e0df982ea9aed3b69a7492f5 // }); var track = last_element.target.name; //play track soundManager.play(track); //set node to empty name so mouseout does not happen nd.name =""; } }); } var nodeVPosition=0; function animateParentChain(links){ var linkRenderer = d3.svg.diagonal() .projection(function(d){ if(d.value !=undefined){ nodeVPosition = d.y; return [(d.x - d.value) , (-d.y + d.value) ]; } else{ return [d.x , (-d.y ) ]; } }); // Links ui.animGroup.selectAll("path.selected") .data([]) .exit().remove(); ui.animGroup .selectAll("path.selected") .data(links) .enter().append("svg:path") .attr("class", "selected") .attr("d", linkRenderer); // Animate the clipping path var overlayBox = ui.svgRoot.node().getBBox(); ui.svgRoot.select("#clip-rect") .attr("x", overlayBox.x ) .attr("y", 0) .attr("width", overlayBox.width) .attr("height", 50) .transition().duration(soundDuration) .ease("linear") .attr("y", overlayBox.y -(115 + nodeVPosition)) .attr("height", 50); } //Soundmanager //set client id for soundcloud var sid = "/stream?client_id=d99a29c1a7bd281b1ef4a833d3ab6dad"; soundManager.setup({ // where to find flash audio SWFs, as needed url: '/.', onready: function() { soundManager.createSound({ id: 'two', // optional: provide your own unique id url: 'PIano Improvs6-first tree2.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; // console.log(soundDuration); //setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); console.log(soundDuration); animateParentChain(matchedLinks,soundManager); // },2500); } } }); soundManager.createSound({ id: 'three', // optional: provide your own unique id url: 'PIano Improvs6-first tree3.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; console.log(soundDuration); } } }); soundManager.createSound({ id: '6T1', // optional: provide your own unique id url: 'PIano Improvs6-first tree2.mp3', multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration; // console.log(soundDuration); //setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); console.log(soundDuration); animateParentChain(matchedLinks,soundManager); // },2500); } } }); soundManager.createSound({ id: 'ten', // optional: provide your own unique id url: 'http://api.soundcloud.com/tracks/155037359' + sid, multiShot: false, onload: function() { if( this.readyState ===3 ) { soundDuration = this.duration ; // setTimeout(function(){ // dur = soundManager.getSoundById(track).duration // var dur = soundManager.getSoundById(track).duration; // console.log(dur); animateParentChain(matchedLinks); //animateParentChain(matchedLinks,soundManager); // },2500); } console.log(soundDuration); } }); }//close onready });//close soundmanager setup $(function(){ buildTree("#tree-container"); }); });
changed first tree names
index2.js
changed first tree names
<ide><path>ndex2.js <ide> name: "", <ide> value: -17, <ide> contents: [ <del> { name: "two", <add> { name: "1T2", <ide> value: 6 }, <del> { name: "three", <add> { name: "1T3", <ide> value: -16 }, <del> { name: "4", <add> { name: "1T4", <ide> value: -5 } <ide> ] <ide> }, <ide> name: "", <ide> value: 7, <ide> contents: [ <del> { name: "9" , <add> { name: "1T9" , <ide> value: 19 <add> }, <add> { name: "1T15" , <add> value: -5} <add> ] <ide> }, <del> { name: "15" , <del> value: -5} <del> ] <del> }, <ide> { <ide> name: "", <ide> value: 1, <ide> name: "", <ide> value: -18, <ide> contents: [ <del> { name: "6", <add> { name: "1T6", <ide> value: 19 }, <del> { name: "7", <add> { name: "1T7", <ide> value: -55 }, <del> { name: "8", <add> { name: "1T8", <ide> value: -19 } <ide> ] <ide> }, <ide> name: "", <ide> value: 5, <ide> contents: [ <del> { name: "ten", <add> { name: "1T10", <ide> value: -12 } <ide> ] <ide> }, <ide> name: "", <ide> value: -12, <ide> contents: [ <del> { name: "11", <add> { name: "1T11", <ide> value: 4}, <ide> { <ide> name: "", <ide> value: 4, <ide> contents: [ <del> { name: "4", <add> { name: "1T12", <ide> value: 4}, <del> { name: "13", <add> { name: "1T13", <ide> value: 1}, <del> { name: "14", <add> { name: "1T14", <ide> value: 6} <ide> ] <ide> } <ide> name: "", <ide> value: 3, <ide> contents: [ <del> { name: "1", <add> { name: "1T1", <ide> value: -4 } <ide> ] <ide> } <ide> ] <ide> }, <ide> { <del> name: "5", <del> value: -20, <del> contents: [] <add> name: "1T5", <add> value: -20 <ide> } <ide> ] <ide> }, <ide> console.log(soundDuration); <ide> } <ide> }); <add> soundManager.createSound({ <add> id: '1T5', // optional: provide your own unique id <add> url: 'http://api.soundcloud.com/tracks/155037359' + sid, <add> multiShot: false, <add> onload: function() { <add> if( this.readyState ===3 ) { <add> soundDuration = this.duration ; <add> // setTimeout(function(){ <add> // dur = soundManager.getSoundById(track).duration <add> // var dur = soundManager.getSoundById(track).duration; <add> // console.log(dur); <add> animateParentChain(matchedLinks); <add> //animateParentChain(matchedLinks,soundManager); <add> // },2500); <add> } <add> console.log(soundDuration); <add> } <add> }); <ide> }//close onready <ide> });//close soundmanager setup <ide>
Java
apache-2.0
6e1b51ab2fb615d4f2b8e6c76ec4ee3f7223c169
0
SeleniumHQ/buck,facebook/buck,Addepar/buck,zpao/buck,brettwooldridge/buck,nguyentruongtho/buck,nguyentruongtho/buck,SeleniumHQ/buck,JoelMarcey/buck,rmaz/buck,facebook/buck,romanoid/buck,SeleniumHQ/buck,rmaz/buck,rmaz/buck,zpao/buck,Addepar/buck,brettwooldridge/buck,SeleniumHQ/buck,zpao/buck,brettwooldridge/buck,brettwooldridge/buck,kageiit/buck,romanoid/buck,brettwooldridge/buck,kageiit/buck,nguyentruongtho/buck,romanoid/buck,JoelMarcey/buck,Addepar/buck,romanoid/buck,brettwooldridge/buck,kageiit/buck,zpao/buck,rmaz/buck,rmaz/buck,SeleniumHQ/buck,nguyentruongtho/buck,Addepar/buck,rmaz/buck,SeleniumHQ/buck,SeleniumHQ/buck,JoelMarcey/buck,romanoid/buck,JoelMarcey/buck,brettwooldridge/buck,Addepar/buck,Addepar/buck,romanoid/buck,nguyentruongtho/buck,brettwooldridge/buck,JoelMarcey/buck,zpao/buck,romanoid/buck,SeleniumHQ/buck,Addepar/buck,brettwooldridge/buck,JoelMarcey/buck,Addepar/buck,rmaz/buck,facebook/buck,facebook/buck,Addepar/buck,zpao/buck,Addepar/buck,brettwooldridge/buck,Addepar/buck,romanoid/buck,rmaz/buck,kageiit/buck,romanoid/buck,JoelMarcey/buck,romanoid/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,rmaz/buck,romanoid/buck,JoelMarcey/buck,rmaz/buck,facebook/buck,facebook/buck,rmaz/buck,JoelMarcey/buck,JoelMarcey/buck,kageiit/buck,kageiit/buck,nguyentruongtho/buck,SeleniumHQ/buck,rmaz/buck,brettwooldridge/buck,JoelMarcey/buck,romanoid/buck,JoelMarcey/buck,romanoid/buck,SeleniumHQ/buck,SeleniumHQ/buck,SeleniumHQ/buck,SeleniumHQ/buck,Addepar/buck,brettwooldridge/buck,rmaz/buck,nguyentruongtho/buck,facebook/buck,brettwooldridge/buck,zpao/buck
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.features.project.intellij; import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig; import com.facebook.buck.artifact_cache.config.DirCacheEntry; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; import java.util.concurrent.TimeUnit; /** Cleans out any unwanted IntelliJ IDEA project files. */ public class IJProjectCleaner { private static final Logger LOG = Logger.get(IJProjectCleaner.class); private static final int EXECUTOR_SHUTDOWN_TIMEOUT = 1; private static final TimeUnit EXECUTOR_SHUTDOWN_TIME_UNIT = TimeUnit.MINUTES; private static final FilenameFilter IML_FILENAME_FILTER = (dir, name) -> name.endsWith(".iml"); private static final FilenameFilter XML_FILENAME_FILTER = (dir, name) -> name.endsWith(".xml"); private static final FileFilter SUBDIRECTORY_FILTER = File::isDirectory; private final ProjectFilesystem projectFilesystem; private final Set<File> filesToKeep = Sets.newConcurrentHashSet(); public IJProjectCleaner(ProjectFilesystem projectFilesystem) { this.projectFilesystem = projectFilesystem; } /** @param path The path to not include in the cleaning operation. */ public void doNotDelete(Path path) { filesToKeep.add(convertPathToFile(path)); } public void writeFilesToKeepToFile(String filename) throws IOException { Files.write( projectFilesystem.resolve(filename), filesToKeep .stream() .map(File::getAbsolutePath) .map(Paths::get) .map(projectFilesystem::relativize) .map(Path::toString) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()))); } private File convertPathToFile(Path path) { if (!path.isAbsolute()) { path = projectFilesystem.resolve(path); } try { return path.toRealPath().toFile(); } catch (IOException e) { LOG.warn("Problem resolving " + path, e); return path.toAbsolutePath().toFile(); } } /** * We shouldn't use all the processors available because this can bog down the system, but using * n/2 with an upper limit of 4 as the thread limit should give us enough threads to keep SSDs * busy whilst not bogging down systems with slow rotating disks. */ private int getParallelismLimit() { int limit = Math.max(Runtime.getRuntime().availableProcessors() / 2, 4); return limit > 0 ? limit : 1; } public void clean( BuckConfig buckConfig, Path ideaConfigDir, Path librariesXmlBase, boolean runPostGenerationCleaner, boolean removeOldLibraries) { if (!runPostGenerationCleaner && !removeOldLibraries) { return; } Set<File> buckDirectories = new HashSet<>(); buckDirectories.add( convertPathToFile( projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()))); ArtifactCacheBuckConfig cacheBuckConfig = new ArtifactCacheBuckConfig(buckConfig); for (DirCacheEntry entry : cacheBuckConfig.getCacheEntries().getDirCacheEntries()) { buckDirectories.add(convertPathToFile(entry.getCacheDir())); } ForkJoinPool cleanExecutor = new ForkJoinPool(getParallelismLimit()); try { cleanExecutor.invoke( new RecursiveAction() { @Override protected void compute() { List<RecursiveAction> topLevelTasks = new ArrayList<>(2); if (runPostGenerationCleaner) { topLevelTasks.add( new CandidateFinderWithExclusions( convertPathToFile(projectFilesystem.resolve("")), IML_FILENAME_FILTER, buckDirectories)); topLevelTasks.add( new CandidateFinderWithExclusions( ideaConfigDir.toFile(), IML_FILENAME_FILTER, buckDirectories)); } topLevelTasks.add( new CandidateFinder(convertPathToFile(librariesXmlBase), XML_FILENAME_FILTER)); invokeAll(topLevelTasks); } }); } finally { cleanExecutor.shutdown(); try { cleanExecutor.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT, EXECUTOR_SHUTDOWN_TIME_UNIT); } catch (InterruptedException e) { Logger.get(IJProjectCleaner.class).warn("Timeout during executor shutdown.", e); } } } private class DirectoryCleaner extends RecursiveAction { private File directory; private FilenameFilter filenameFilter; DirectoryCleaner(File directory, FilenameFilter filenameFilter) { this.directory = directory; this.filenameFilter = filenameFilter; } @Override protected void compute() { File[] files = directory.listFiles(filenameFilter); if (files == null) { return; } for (File file : files) { file = file.getAbsoluteFile(); if (filesToKeep.contains(file)) { LOG.warn("Skipping " + file); continue; } LOG.warn("Deleting " + file); if (!file.delete()) { LOG.warn("Unable to delete " + file); } } } } private class CandidateFinder extends RecursiveAction { private File directory; private FilenameFilter filenameFilter; CandidateFinder(File directory, FilenameFilter filenameFilter) { this.directory = directory; this.filenameFilter = filenameFilter; } protected void addCandidateDirectoryFinder(List<RecursiveAction> finders, File subdirectory) { finders.add(new CandidateFinder(subdirectory, filenameFilter)); } @Override public void compute() { File[] subdirectories = directory.listFiles(SUBDIRECTORY_FILTER); if (subdirectories == null) { return; } List<RecursiveAction> actions = new ArrayList<>(subdirectories.length + 1); actions.add(new DirectoryCleaner(directory, filenameFilter)); for (File subdirectory : subdirectories) { if (Files.isSymbolicLink(subdirectory.toPath())) { continue; } addCandidateDirectoryFinder(actions, subdirectory); } invokeAll(actions); } } private class CandidateFinderWithExclusions extends CandidateFinder { Set<File> exclusions; CandidateFinderWithExclusions( File directory, FilenameFilter filenameFilter, Set<File> exclusions) { super(directory, filenameFilter); this.exclusions = exclusions; } @Override protected void addCandidateDirectoryFinder(List<RecursiveAction> actions, File subdirectory) { if (exclusions.contains(subdirectory)) { return; } super.addCandidateDirectoryFinder(actions, subdirectory); } } }
src/com/facebook/buck/features/project/intellij/IJProjectCleaner.java
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.features.project.intellij; import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig; import com.facebook.buck.artifact_cache.config.DirCacheEntry; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; import java.util.concurrent.TimeUnit; /** Cleans out any unwanted IntelliJ IDEA project files. */ public class IJProjectCleaner { private static final Logger LOG = Logger.get(IJProjectCleaner.class); private static final int EXECUTOR_SHUTDOWN_TIMEOUT = 1; private static final TimeUnit EXECUTOR_SHUTDOWN_TIME_UNIT = TimeUnit.MINUTES; private static final FilenameFilter IML_FILENAME_FILTER = (dir, name) -> name.endsWith(".iml"); private static final FilenameFilter XML_FILENAME_FILTER = (dir, name) -> name.endsWith(".xml"); private static final FileFilter SUBDIRECTORY_FILTER = File::isDirectory; private final ProjectFilesystem projectFilesystem; private final Set<File> filesToKeep = new HashSet<>(); public IJProjectCleaner(ProjectFilesystem projectFilesystem) { this.projectFilesystem = projectFilesystem; } /** @param path The path to not include in the cleaning operation. */ public void doNotDelete(Path path) { filesToKeep.add(convertPathToFile(path)); } public void writeFilesToKeepToFile(String filename) throws IOException { Files.write( projectFilesystem.resolve(filename), filesToKeep .stream() .map(File::getAbsolutePath) .map(Paths::get) .map(projectFilesystem::relativize) .map(Path::toString) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()))); } private File convertPathToFile(Path path) { if (!path.isAbsolute()) { path = projectFilesystem.resolve(path); } try { return path.toRealPath().toFile(); } catch (IOException e) { LOG.warn("Problem resolving " + path, e); return path.toAbsolutePath().toFile(); } } /** * We shouldn't use all the processors available because this can bog down the system, but using * n/2 with an upper limit of 4 as the thread limit should give us enough threads to keep SSDs * busy whilst not bogging down systems with slow rotating disks. */ private int getParallelismLimit() { int limit = Math.max(Runtime.getRuntime().availableProcessors() / 2, 4); return limit > 0 ? limit : 1; } public void clean( BuckConfig buckConfig, Path ideaConfigDir, Path librariesXmlBase, boolean runPostGenerationCleaner, boolean removeOldLibraries) { if (!runPostGenerationCleaner && !removeOldLibraries) { return; } Set<File> buckDirectories = new HashSet<>(); buckDirectories.add( convertPathToFile( projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()))); ArtifactCacheBuckConfig cacheBuckConfig = new ArtifactCacheBuckConfig(buckConfig); for (DirCacheEntry entry : cacheBuckConfig.getCacheEntries().getDirCacheEntries()) { buckDirectories.add(convertPathToFile(entry.getCacheDir())); } ForkJoinPool cleanExecutor = new ForkJoinPool(getParallelismLimit()); try { cleanExecutor.invoke( new RecursiveAction() { @Override protected void compute() { List<RecursiveAction> topLevelTasks = new ArrayList<>(2); if (runPostGenerationCleaner) { topLevelTasks.add( new CandidateFinderWithExclusions( convertPathToFile(projectFilesystem.resolve("")), IML_FILENAME_FILTER, buckDirectories)); topLevelTasks.add( new CandidateFinderWithExclusions( ideaConfigDir.toFile(), IML_FILENAME_FILTER, buckDirectories)); } topLevelTasks.add( new CandidateFinder(convertPathToFile(librariesXmlBase), XML_FILENAME_FILTER)); invokeAll(topLevelTasks); } }); } finally { cleanExecutor.shutdown(); try { cleanExecutor.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT, EXECUTOR_SHUTDOWN_TIME_UNIT); } catch (InterruptedException e) { Logger.get(IJProjectCleaner.class).warn("Timeout during executor shutdown.", e); } } } private class DirectoryCleaner extends RecursiveAction { private File directory; private FilenameFilter filenameFilter; DirectoryCleaner(File directory, FilenameFilter filenameFilter) { this.directory = directory; this.filenameFilter = filenameFilter; } @Override protected void compute() { File[] files = directory.listFiles(filenameFilter); if (files == null) { return; } for (File file : files) { file = file.getAbsoluteFile(); if (filesToKeep.contains(file)) { LOG.warn("Skipping " + file); continue; } LOG.warn("Deleting " + file); if (!file.delete()) { LOG.warn("Unable to delete " + file); } } } } private class CandidateFinder extends RecursiveAction { private File directory; private FilenameFilter filenameFilter; CandidateFinder(File directory, FilenameFilter filenameFilter) { this.directory = directory; this.filenameFilter = filenameFilter; } protected void addCandidateDirectoryFinder(List<RecursiveAction> finders, File subdirectory) { finders.add(new CandidateFinder(subdirectory, filenameFilter)); } @Override public void compute() { File[] subdirectories = directory.listFiles(SUBDIRECTORY_FILTER); if (subdirectories == null) { return; } List<RecursiveAction> actions = new ArrayList<>(subdirectories.length + 1); actions.add(new DirectoryCleaner(directory, filenameFilter)); for (File subdirectory : subdirectories) { if (Files.isSymbolicLink(subdirectory.toPath())) { continue; } addCandidateDirectoryFinder(actions, subdirectory); } invokeAll(actions); } } private class CandidateFinderWithExclusions extends CandidateFinder { Set<File> exclusions; CandidateFinderWithExclusions( File directory, FilenameFilter filenameFilter, Set<File> exclusions) { super(directory, filenameFilter); this.exclusions = exclusions; } @Override protected void addCandidateDirectoryFinder(List<RecursiveAction> actions, File subdirectory) { if (exclusions.contains(subdirectory)) { return; } super.addCandidateDirectoryFinder(actions, subdirectory); } } }
make 'filesToKeep' thread safe Summary: Generating and writing project files in parallel causes generated files list to not always be correct. Reviewed By: styurin fbshipit-source-id: 94a262faa8
src/com/facebook/buck/features/project/intellij/IJProjectCleaner.java
make 'filesToKeep' thread safe
<ide><path>rc/com/facebook/buck/features/project/intellij/IJProjectCleaner.java <ide> import com.facebook.buck.io.filesystem.ProjectFilesystem; <ide> import com.google.common.collect.ImmutableSortedSet; <ide> import com.google.common.collect.Ordering; <add>import com.google.common.collect.Sets; <ide> import java.io.File; <ide> import java.io.FileFilter; <ide> import java.io.FilenameFilter; <ide> <ide> private final ProjectFilesystem projectFilesystem; <ide> <del> private final Set<File> filesToKeep = new HashSet<>(); <add> private final Set<File> filesToKeep = Sets.newConcurrentHashSet(); <ide> <ide> public IJProjectCleaner(ProjectFilesystem projectFilesystem) { <ide> this.projectFilesystem = projectFilesystem;
Java
epl-1.0
5ecf4cda0dbfd5afab5e0fa2302659d41421e113
0
junit-team/junit-lambda
/* * Copyright 2015-2020 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * https://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.launcher.listeners; import static org.apiguardian.api.API.Status.EXPERIMENTAL; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import jdk.jfr.Category; import jdk.jfr.Event; import jdk.jfr.Label; import jdk.jfr.MetadataDefinition; import jdk.jfr.Name; import jdk.jfr.Relational; import jdk.jfr.StackTrace; import org.apiguardian.api.API; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.engine.reporting.ReportEntry; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.TestPlan; /** * A {@link TestExecutionListener} that generates Java Flight Recorder * events. * * @see <a href="https://openjdk.java.net/jeps/328">JEP 328: Flight Recorder</a> * @since 1.7 */ @API(status = EXPERIMENTAL, since = "1.7") public class FlightRecordingListener implements TestExecutionListener { private final AtomicReference<TestPlanExecutionEvent> testPlanExecutionEvent = new AtomicReference<>(); private final Map<String, TestExecutionEvent> testExecutionEventMap = new ConcurrentHashMap<>(); @Override public void testPlanExecutionStarted(TestPlan plan) { TestPlanExecutionEvent event = new TestPlanExecutionEvent(); event.containsTests = plan.containsTests(); event.engineNames = plan.getRoots().stream().map(TestIdentifier::getDisplayName).collect( Collectors.joining(", ")); testPlanExecutionEvent.set(event); event.begin(); } @Override public void testPlanExecutionFinished(TestPlan plan) { TestPlanExecutionEvent event = testPlanExecutionEvent.get(); event.commit(); } @Override public void executionSkipped(TestIdentifier test, String reason) { SkippedTestEvent event = new SkippedTestEvent(); event.initialize(test); event.reason = reason; event.commit(); } @Override public void executionStarted(TestIdentifier test) { TestExecutionEvent event = new TestExecutionEvent(); testExecutionEventMap.put(test.getUniqueId(), event); event.initialize(test); event.begin(); } @Override public void executionFinished(TestIdentifier test, TestExecutionResult result) { if (test.isContainer() && result.getStatus().equals(TestExecutionResult.Status.SUCCESSFUL)) { return; } Optional<Throwable> throwable = result.getThrowable(); TestExecutionEvent event = testExecutionEventMap.get(test.getUniqueId()); // TODO Remove? event.end(); event.result = result.getStatus().toString(); event.exceptionClass = throwable.map(Throwable::getClass).orElse(null); event.exceptionMessage = throwable.map(Throwable::getMessage).orElse(null); event.commit(); } @Override public void reportingEntryPublished(TestIdentifier test, ReportEntry reportEntry) { for (Map.Entry<String, String> entry : reportEntry.getKeyValuePairs().entrySet()) { ReportEntryEvent event = new ReportEntryEvent(); event.uniqueId = test.getUniqueId(); event.key = entry.getKey(); event.value = entry.getValue(); event.commit(); } } @Category("JUnit") @Label("Test Plan") @Name("org.junit.TestPlan") @StackTrace(false) static class TestPlanExecutionEvent extends Event { @Label("Contains Tests") boolean containsTests; @Label("Engine Names") String engineNames; } @MetadataDefinition @Relational @Name("org.junit.UniqueId") @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UniqueId { } @Category("JUnit") @StackTrace(false) abstract static class TestEvent extends Event { @UniqueId @Label("Unique Id") String uniqueId; @Label("Display Name") String displayName; @Label("Tags") String tags; @Label("Type") String type; void initialize(TestIdentifier test) { this.uniqueId = test.getUniqueId(); this.displayName = test.getDisplayName(); this.tags = test.getTags().isEmpty() ? null : test.getTags().toString(); this.type = test.getType().name(); } } @Label("Skipped Test") @Name("org.junit.SkippedTest") static class SkippedTestEvent extends TestEvent { @Label("Reason") String reason; } @Label("Test") @Name("org.junit.TestExecution") static class TestExecutionEvent extends TestEvent { @Label("Result") String result; @Label("Exception Class") Class<?> exceptionClass; @Label("Exception Message") String exceptionMessage; } @Category("JUnit") @Label("Report Entry") @Name("org.junit.ReportEntry") @StackTrace(false) static class ReportEntryEvent extends Event { @UniqueId @Label("Unique Id") String uniqueId; @Label("Key") String key; @Label("Value") String value; } }
junit-platform-launcher/src/main/java9/org/junit/platform/launcher/listeners/FlightRecordingListener.java
/* * Copyright 2015-2020 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * https://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.launcher.listeners; import static org.apiguardian.api.API.Status.EXPERIMENTAL; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import jdk.jfr.Category; import jdk.jfr.Event; import jdk.jfr.Label; import jdk.jfr.MetadataDefinition; import jdk.jfr.Name; import jdk.jfr.Relational; import jdk.jfr.StackTrace; import org.apiguardian.api.API; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.engine.reporting.ReportEntry; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.TestPlan; /** * A {@link TestExecutionListener} that generates Java Flight Recorder * events. * * @see <a href="https://openjdk.java.net/jeps/328">JEP 328: Flight Recorder</a> * @since 1.7 */ @API(status = EXPERIMENTAL, since = "1.7") public class FlightRecordingListener implements TestExecutionListener { private final AtomicReference<TestPlanExecutionEvent> testPlanExecutionEvent = new AtomicReference<>(); private final Map<String, TestExecutionEvent> testExecutionEventMap = new ConcurrentHashMap<>(); @Override public void testPlanExecutionStarted(TestPlan plan) { TestPlanExecutionEvent event = new TestPlanExecutionEvent(); event.containsTests = plan.containsTests(); event.engineNames = plan.getRoots().stream().map(TestIdentifier::getDisplayName).collect( Collectors.joining(", ")); testPlanExecutionEvent.set(event); event.begin(); } @Override public void testPlanExecutionFinished(TestPlan plan) { TestPlanExecutionEvent event = testPlanExecutionEvent.get(); event.commit(); } @Override public void executionSkipped(TestIdentifier test, String reason) { SkippedTestEvent event = new SkippedTestEvent(); event.initialize(test); event.reason = reason; event.commit(); } @Override public void executionStarted(TestIdentifier test) { TestExecutionEvent event = new TestExecutionEvent(); testExecutionEventMap.put(test.getUniqueId(), event); event.initialize(test); event.begin(); } @Override public void executionFinished(TestIdentifier test, TestExecutionResult result) { if (test.isContainer() && result.getStatus().equals(TestExecutionResult.Status.SUCCESSFUL)) { return; } Optional<Throwable> throwable = result.getThrowable(); TestExecutionEvent event = testExecutionEventMap.get(test.getUniqueId()); // TODO Remove? event.end(); event.result = result.getStatus().toString(); event.exceptionClass = throwable.map(Throwable::getClass).orElse(null); event.exceptionMessage = throwable.map(Throwable::getMessage).orElse(null); event.commit(); } @Override public void reportingEntryPublished(TestIdentifier test, ReportEntry reportEntry) { for (Map.Entry<String, String> entry : reportEntry.getKeyValuePairs().entrySet()) { ReportEntryEvent event = new ReportEntryEvent(); event.uniqueId = test.getUniqueId(); event.key = entry.getKey(); event.value = entry.getValue(); event.commit(); } } @Category("JUnit") @Label("Test Plan") @Name("org.junit.TestPlan") @StackTrace(false) static class TestPlanExecutionEvent extends Event { @Label("Contains Tests") boolean containsTests; @Label("Engine Names") String engineNames; } @MetadataDefinition @Relational @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UniqueId { } @Category("JUnit") @StackTrace(false) abstract static class TestEvent extends Event { @UniqueId @Label("Unique Id") String uniqueId; @Label("Display Name") String displayName; @Label("Tags") String tags; @Label("Type") String type; void initialize(TestIdentifier test) { this.uniqueId = test.getUniqueId(); this.displayName = test.getDisplayName(); this.tags = test.getTags().isEmpty() ? null : test.getTags().toString(); this.type = test.getType().name(); } } @Label("Skipped Test") @Name("org.junit.SkippedTest") static class SkippedTestEvent extends TestEvent { @Label("Reason") String reason; } @Label("Test") @Name("org.junit.TestExecution") static class TestExecutionEvent extends TestEvent { @Label("Result") String result; @Label("Exception Class") Class<?> exceptionClass; @Label("Exception Message") String exceptionMessage; } @Category("JUnit") @Label("Report Entry") @Name("org.junit.ReportEntry") @StackTrace(false) static class ReportEntryEvent extends Event { @UniqueId @Label("Unique Id") String uniqueId; @Label("Key") String key; @Label("Value") String value; } }
Attach label to UniqueId's metadata definition
junit-platform-launcher/src/main/java9/org/junit/platform/launcher/listeners/FlightRecordingListener.java
Attach label to UniqueId's metadata definition
<ide><path>unit-platform-launcher/src/main/java9/org/junit/platform/launcher/listeners/FlightRecordingListener.java <ide> <ide> @MetadataDefinition <ide> @Relational <add> @Name("org.junit.UniqueId") <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Target(ElementType.FIELD) <ide> public @interface UniqueId {
Java
apache-2.0
0419d57bf80a8a4125cf9a769d2b6f159795ff9d
0
Apelon-VA/ISAAC,DongwonChoi/ISAAC,Apelon-VA/ISAAC,vaskaloidis/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/ISAAC,Apelon-VA/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,vaskaloidis/va-isaac-gui
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.va.isaac.gui.dialog; import gov.va.isaac.AppContext; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.model.InformationModelType; import gov.va.isaac.models.InformationModel; import gov.va.isaac.models.InformationModel.Metadata; import gov.va.isaac.models.cem.CEMInformationModel; import gov.va.isaac.models.cem.exporter.CEMExporter; import gov.va.isaac.models.fhim.FHIMInformationModel; import gov.va.isaac.models.fhim.exporter.FHIMExporter; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.UUID; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.Cursor; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.TextArea; import javafx.stage.Stage; import org.ihtsdo.otf.tcc.api.time.TimeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * Controller class for {@link InformationModelDetailsDialog}. * * @author ocarlsen */ public class InformationModelDetailsDialogController { private static final Logger LOG = LoggerFactory.getLogger(InformationModelDetailsDialogController.class); @FXML private Label modelNameLabel; @FXML private Label modelTypeLabel; @FXML private Label focusConceptLabel; @FXML private Label uuidLabel; @FXML private Label importerNameLabel; @FXML private Label importDateLabel; @FXML private Label importPathLabel; @FXML private Label importModuleLabel; @FXML private TextArea modelXmlTextArea; @FXML private ProgressIndicator modelXmlProgress; private Stage stage; @FXML public void initialize() { } public void setStage(Stage stage) { this.stage = stage; } public void displayModel(InformationModel informationModel) { Preconditions.checkNotNull(informationModel); // Make sure in application thread. FxUtils.checkFxUserThread(); if (informationModel.getType() == InformationModelType.CEM) { displayCEM((CEMInformationModel) informationModel); } else if (informationModel.getType() == InformationModelType.FHIM) { displayFHIM((FHIMInformationModel) informationModel); } else { throw new UnsupportedOperationException(informationModel.getType() + " display not yet supported in ISAAC."); } } private void displayFHIM(FHIMInformationModel fhimModel) { // Do work in background. Task<String> task = new DetailsTask(fhimModel) { @Override protected String call() throws Exception { // Do work. OutputStream out = new ByteArrayOutputStream(); FHIMExporter exporter = new FHIMExporter(out); UUID conceptUUID = infoModel.getFocusConceptUUID(); exporter.exportModel(conceptUUID); return out.toString(); } }; scheduleTask(fhimModel, task); } private void displayCEM(CEMInformationModel cemModel) { // Do work in background. Task<String> task = new DetailsTask(cemModel) { @Override protected String call() throws Exception { // Do work. OutputStream out = new ByteArrayOutputStream(); CEMExporter exporter = new CEMExporter(out); UUID conceptUUID = infoModel.getFocusConceptUUID(); exporter.exportModel(conceptUUID); return out.toString(); } }; scheduleTask(cemModel, task); } private void scheduleTask(InformationModel infoModel, Task<String> task) { // Bind cursor to task state. ObjectBinding<Cursor> cursorBinding = Bindings.when(task.runningProperty()).then(Cursor.WAIT).otherwise(Cursor.DEFAULT); this.stage.getScene().cursorProperty().bind(cursorBinding); // Bind progress indicator to task state. modelXmlProgress.visibleProperty().bind(task.runningProperty()); Thread t = new Thread(task, "Display_" + infoModel.getName()); t.setDaemon(true); t.start(); } /** * Common superclass {@link Task} for showing {@link InformationModel} details. * * @author ocarlsen */ private abstract class DetailsTask extends Task<String> { protected final InformationModel infoModel; protected DetailsTask(InformationModel infoModel) { super(); this.infoModel = infoModel; } @Override protected void succeeded() { // Update UI. modelNameLabel.setText(infoModel.getName()); modelTypeLabel.setText(infoModel.getType().getDisplayName()); focusConceptLabel.setText(infoModel.getFocusConceptName()); uuidLabel.setText(infoModel.getFocusConceptUUID().toString()); Metadata metadata = infoModel.getMetadata(); importerNameLabel.setText(metadata.getImporterName()); importDateLabel.setText(TimeHelper.formatDate(metadata.getTime())); importPathLabel.setText(metadata.getPath().toString()); importModuleLabel.setText(metadata.getModuleName()); String modelXML = this.getValue(); modelXmlTextArea.setText(modelXML); } @Override protected void failed() { // Show dialog. Throwable ex = getException(); String title = ex.getClass().getName(); InformationModelType modelType = infoModel.getType(); String msg = String.format("Unexpected error displaying %s model \"%s\"", modelType, infoModel.getName()); LOG.error(msg, ex); AppContext.getCommonDialogs().showErrorDialog(title, msg, ex.getMessage()); } } }
import-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsDialogController.java
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.va.isaac.gui.dialog; import gov.va.isaac.AppContext; import gov.va.isaac.gui.util.FxUtils; import gov.va.isaac.model.InformationModelType; import gov.va.isaac.models.InformationModel; import gov.va.isaac.models.InformationModel.Metadata; import gov.va.isaac.models.cem.CEMInformationModel; import gov.va.isaac.models.cem.exporter.CEMExporter; import gov.va.isaac.models.fhim.FHIMInformationModel; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.UUID; import javafx.beans.binding.Bindings; import javafx.beans.binding.ObjectBinding; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.Cursor; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.TextArea; import javafx.stage.Stage; import org.ihtsdo.otf.tcc.api.time.TimeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * Controller class for {@link InformationModelDetailsDialog}. * * @author ocarlsen */ public class InformationModelDetailsDialogController { private static final Logger LOG = LoggerFactory.getLogger(InformationModelDetailsDialogController.class); @FXML private Label modelNameLabel; @FXML private Label modelTypeLabel; @FXML private Label focusConceptLabel; @FXML private Label uuidLabel; @FXML private Label importerNameLabel; @FXML private Label importDateLabel; @FXML private Label importPathLabel; @FXML private Label importModuleLabel; @FXML private TextArea modelXmlTextArea; @FXML private ProgressIndicator modelXmlProgress; private Stage stage; @FXML public void initialize() { } public void setStage(Stage stage) { this.stage = stage; } public void displayModel(InformationModel informationModel) { Preconditions.checkNotNull(informationModel); // Make sure in application thread. FxUtils.checkFxUserThread(); if (informationModel.getType() == InformationModelType.CEM) { displayCEM((CEMInformationModel) informationModel); } else if (informationModel.getType() == InformationModelType.FHIM) { displayFHIM((FHIMInformationModel) informationModel); } else { throw new UnsupportedOperationException(informationModel.getType() + " display not yet supported in ISAAC."); } } private void displayFHIM(FHIMInformationModel fhimModel) { // Do work in background. Task<String> task = new DetailsTask(fhimModel) { @Override protected String call() throws Exception { // Do work. return "TODO"; } }; scheduleTask(fhimModel, task); } private void displayCEM(CEMInformationModel cemModel) { // Do work in background. Task<String> task = new DetailsTask(cemModel) { @Override protected String call() throws Exception { // Do work. OutputStream out = new ByteArrayOutputStream(); CEMExporter exporter = new CEMExporter(out); UUID conceptUUID = infoModel.getFocusConceptUUID(); exporter.exportModel(conceptUUID); return out.toString(); } }; scheduleTask(cemModel, task); } private void scheduleTask(InformationModel infoModel, Task<String> task) { // Bind cursor to task state. ObjectBinding<Cursor> cursorBinding = Bindings.when(task.runningProperty()).then(Cursor.WAIT).otherwise(Cursor.DEFAULT); this.stage.getScene().cursorProperty().bind(cursorBinding); // Bind progress indicator to task state. modelXmlProgress.visibleProperty().bind(task.runningProperty()); Thread t = new Thread(task, "Display_" + infoModel.getName()); t.setDaemon(true); t.start(); } /** * Common superclass {@link Task} for showing {@link InformationModel} details. * * @author ocarlsen */ private abstract class DetailsTask extends Task<String> { protected final InformationModel infoModel; protected DetailsTask(InformationModel infoModel) { super(); this.infoModel = infoModel; } @Override protected void succeeded() { // Update UI. modelNameLabel.setText(infoModel.getName()); modelTypeLabel.setText(infoModel.getType().getDisplayName()); focusConceptLabel.setText(infoModel.getFocusConceptName()); uuidLabel.setText(infoModel.getFocusConceptUUID().toString()); Metadata metadata = infoModel.getMetadata(); importerNameLabel.setText(metadata.getImporterName()); importDateLabel.setText(TimeHelper.formatDate(metadata.getTime())); importPathLabel.setText(metadata.getPath().toString()); importModuleLabel.setText(metadata.getModuleName()); String modelXML = this.getValue(); modelXmlTextArea.setText(modelXML); } @Override protected void failed() { // Show dialog. Throwable ex = getException(); String title = ex.getClass().getName(); InformationModelType modelType = infoModel.getType(); String msg = String.format("Unexpected error displaying %s model \"%s\"", modelType, infoModel.getName()); LOG.error(msg, ex); AppContext.getCommonDialogs().showErrorDialog(title, msg, ex.getMessage()); } } }
Hooking up real XMI to display FHIM models.
import-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsDialogController.java
Hooking up real XMI to display FHIM models.
<ide><path>mport-export/src/main/java/gov/va/isaac/gui/dialog/InformationModelDetailsDialogController.java <ide> import gov.va.isaac.models.cem.CEMInformationModel; <ide> import gov.va.isaac.models.cem.exporter.CEMExporter; <ide> import gov.va.isaac.models.fhim.FHIMInformationModel; <add>import gov.va.isaac.models.fhim.exporter.FHIMExporter; <ide> <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.OutputStream; <ide> protected String call() throws Exception { <ide> <ide> // Do work. <del> return "TODO"; <add> OutputStream out = new ByteArrayOutputStream(); <add> FHIMExporter exporter = new FHIMExporter(out); <add> UUID conceptUUID = infoModel.getFocusConceptUUID(); <add> exporter.exportModel(conceptUUID); <add> return out.toString(); <ide> } <ide> }; <ide>
Java
apache-2.0
36de545a3b2d878b1d4a7be65cd180fa6a18eafd
0
westei/anno4j,anno4j/anno4j,anno4j/anno4j
package com.github.anno4j.model.impl; import com.github.anno4j.Anno4j; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.GraphQueryResult; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.repository.object.ObjectRepository; import org.openrdf.repository.object.RDFObject; import org.openrdf.repository.object.config.ObjectRepositoryFactory; import org.openrdf.repository.sail.SailRepository; import org.openrdf.sail.memory.MemoryStore; /** * Class to implement RDF in order to create a baseline for every object that we use in Anno4j. */ public class ResourceObject implements RDFObject { /** * Unique identifier for the instance. */ private Resource resource = Anno4j.getInstance().getIdGenerator().generateID(); /** * The current {@link org.openrdf.repository.object.ObjectConnection} this object is attached to. Will be implemented by the proxy object. */ @Override public ObjectConnection getObjectConnection() { // will be implemented by the proxy object return null; } /** * Gets Unique identifier for the instance. * * @return Value of Unique identifier for the instance.. */ public Resource getResource() { return resource; } /** * Sets new Unique identifier for the instance. * * @param resource New value of Unique identifier for the instance.. */ public void setResource(Resource resource) { this.resource = resource; } /** * Sets new Unique identifier for the instance by a given String. * * @param resourceAsString Textual representation of the new value of Unique identifier for the instance. */ public void setResourceAsString(String resourceAsString) { this.resource = new URIImpl(resourceAsString); } /** * Gets new identifier for this instance as String. * @return identifier as String. */ public String getResourceAsString() { return this.resource.stringValue(); } public String getNTriples(){ StringBuilder sb = new StringBuilder(); try { MemoryStore store = new MemoryStore(); Repository sailRepository = new SailRepository(store); sailRepository.initialize(); ObjectRepository objectRepository = new ObjectRepositoryFactory().createRepository(sailRepository); ObjectConnection connection = objectRepository.getConnection(); connection.addObject(this); GraphQueryResult result = sailRepository.getConnection().prepareGraphQuery(QueryLanguage.SPARQL, "CONSTRUCT { ?s ?p ?o. } WHERE { ?s ?p ?o. } ").evaluate(); while (result.hasNext()) { Statement item = result.next(); sb .append(item.getSubject()) .append(" ") .append(item.getPredicate()) .append(" ") .append(item.getObject()) .append(".") .append(System.getProperty("line.separator")); } result.close(); connection.close(); } catch (RepositoryException e) { e.printStackTrace(); } catch (RepositoryConfigException e) { e.printStackTrace(); } catch (MalformedQueryException e) { e.printStackTrace(); } catch (QueryEvaluationException e) { e.printStackTrace(); } return sb.toString(); } }
src/main/java/com/github/anno4j/model/impl/ResourceObject.java
package com.github.anno4j.model.impl; import com.github.anno4j.Anno4j; import org.openrdf.model.Resource; import org.openrdf.model.impl.URIImpl; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.repository.object.RDFObject; /** * Class to implement RDF in order to create a baseline for every object that we use in Anno4j. */ public class ResourceObject implements RDFObject { /** * Unique identifier for the instance. */ private Resource resource = Anno4j.getInstance().getIdGenerator().generateID(); /** * The current {@link org.openrdf.repository.object.ObjectConnection} this object is attached to. Will be implemented by the proxy object. */ @Override public ObjectConnection getObjectConnection() { // will be implemented by the proxy object return null; } /** * Gets Unique identifier for the instance. * * @return Value of Unique identifier for the instance.. */ public Resource getResource() { return resource; } /** * Sets new Unique identifier for the instance. * * @param resource New value of Unique identifier for the instance.. */ public void setResource(Resource resource) { this.resource = resource; } /** * Sets new Unique identifier for the instance by a given String. * * @param resourceAsString Textual representation of the new value of Unique identifier for the instance. */ public void setResourceAsString(String resourceAsString) { this.resource = new URIImpl(resourceAsString); } /** * Gets new identifier for this instance as String. * @return identifier as String. */ public String getResourceAsString() { return this.resource.stringValue(); } }
each object can return ntiples
src/main/java/com/github/anno4j/model/impl/ResourceObject.java
each object can return ntiples
<ide><path>rc/main/java/com/github/anno4j/model/impl/ResourceObject.java <ide> <ide> import com.github.anno4j.Anno4j; <ide> import org.openrdf.model.Resource; <add>import org.openrdf.model.Statement; <ide> import org.openrdf.model.impl.URIImpl; <add>import org.openrdf.query.GraphQueryResult; <add>import org.openrdf.query.MalformedQueryException; <add>import org.openrdf.query.QueryEvaluationException; <add>import org.openrdf.query.QueryLanguage; <add>import org.openrdf.repository.Repository; <add>import org.openrdf.repository.RepositoryException; <add>import org.openrdf.repository.config.RepositoryConfigException; <ide> import org.openrdf.repository.object.ObjectConnection; <add>import org.openrdf.repository.object.ObjectRepository; <ide> import org.openrdf.repository.object.RDFObject; <add>import org.openrdf.repository.object.config.ObjectRepositoryFactory; <add>import org.openrdf.repository.sail.SailRepository; <add>import org.openrdf.sail.memory.MemoryStore; <ide> <ide> /** <ide> * Class to implement RDF in order to create a baseline for every object that we use in Anno4j. <ide> public String getResourceAsString() { <ide> return this.resource.stringValue(); <ide> } <add> <add> public String getNTriples(){ <add> StringBuilder sb = new StringBuilder(); <add> try { <add> MemoryStore store = new MemoryStore(); <add> Repository sailRepository = new SailRepository(store); <add> sailRepository.initialize(); <add> ObjectRepository objectRepository = new ObjectRepositoryFactory().createRepository(sailRepository); <add> ObjectConnection connection = objectRepository.getConnection(); <add> connection.addObject(this); <add> GraphQueryResult result = sailRepository.getConnection().prepareGraphQuery(QueryLanguage.SPARQL, "CONSTRUCT { ?s ?p ?o. } WHERE { ?s ?p ?o. } ").evaluate(); <add> while (result.hasNext()) { <add> Statement item = result.next(); <add> <add> sb <add> .append(item.getSubject()) <add> .append(" ") <add> .append(item.getPredicate()) <add> .append(" ") <add> .append(item.getObject()) <add> .append(".") <add> .append(System.getProperty("line.separator")); <add> } <add> result.close(); <add> connection.close(); <add> } catch (RepositoryException e) { <add> e.printStackTrace(); <add> } catch (RepositoryConfigException e) { <add> e.printStackTrace(); <add> } catch (MalformedQueryException e) { <add> e.printStackTrace(); <add> } catch (QueryEvaluationException e) { <add> e.printStackTrace(); <add> } <add> <add> return sb.toString(); <add> } <ide> }
Java
apache-2.0
b99ef1824db0684accc242d50b8b1ddd1067b6d1
0
xiaoyanit/ImageLoader,lxhxhlw/image-loader,xiaoyanit/ImageLoader,charlialiang/image-loader,ALEXGUOQ/ImageLoader,wang006688/image-loader
package com.novoda.imageloader.acceptance; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.test.InstrumentationTestCase; import com.novoda.imageloader.core.bitmap.BitmapUtil; public class BitmapUtilsInstrumentationTest extends InstrumentationTestCase { private final int scaledBitmapSize = 200; private final boolean allowUpSampling = true; public BitmapUtilsInstrumentationTest(String name) { super(); setName(name); } public void test_bitmaputil_scales_bitmaps_to_specified_size(){ Bitmap bmOriginal = BitmapFactory.decodeResource(getInstrumentation().getContext().getResources(), R.drawable.icon); assertFalse(bmOriginal.getHeight() == scaledBitmapSize); assertFalse(bmOriginal.getWidth() == scaledBitmapSize); Bitmap bm = new BitmapUtil().scaleBitmap(bmOriginal, scaledBitmapSize, scaledBitmapSize, allowUpSampling); assertEquals(scaledBitmapSize, bm.getHeight()); assertEquals(scaledBitmapSize, bm.getWidth()); } public void test_bitmaputil_creates_bitmaps__of_a_specified_size() { Bitmap bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), scaledBitmapSize, scaledBitmapSize, R.drawable.icon, allowUpSampling); assertTrue(bm.getHeight() == scaledBitmapSize); assertTrue(bm.getWidth() == scaledBitmapSize); } }
acceptance/src/com/novoda/imageloader/acceptance/BitmapUtilsInstrumentationTest.java
package com.novoda.imageloader.acceptance; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.test.InstrumentationTestCase; import com.novoda.imageloader.core.bitmap.BitmapUtil; public class BitmapUtilsInstrumentationTest extends InstrumentationTestCase { public BitmapUtilsInstrumentationTest(String name) { super(); setName(name); } public void testScaleBitmap(){ Bitmap bmOriginal = BitmapFactory.decodeResource(getInstrumentation().getContext().getResources(), R.drawable.icon); assertTrue(bmOriginal.getHeight() <= 72); assertTrue(bmOriginal.getWidth() <= 72); Bitmap bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), 200, 200, R.drawable.icon, true); assertEquals(200, bm.getHeight()); assertEquals(200, bm.getWidth()); bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), 200, 200, R.drawable.icon, false); assertEquals(bmOriginal.getHeight(), bm.getHeight()); assertEquals(bmOriginal.getWidth(), bm.getWidth()); bm = new BitmapUtil().scaleBitmap(bmOriginal, 200, 200, false); assertEquals(bmOriginal, bm); bm = new BitmapUtil().scaleBitmap(bmOriginal, 200, 200, true); assertNotSame(bmOriginal, bm); assertEquals(200, bm.getHeight()); assertEquals(200, bm.getWidth()); } }
fixing bitmap utils tests
acceptance/src/com/novoda/imageloader/acceptance/BitmapUtilsInstrumentationTest.java
fixing bitmap utils tests
<ide><path>cceptance/src/com/novoda/imageloader/acceptance/BitmapUtilsInstrumentationTest.java <ide> <ide> public class BitmapUtilsInstrumentationTest extends InstrumentationTestCase { <ide> <del> public BitmapUtilsInstrumentationTest(String name) { <add> private final int scaledBitmapSize = 200; <add> private final boolean allowUpSampling = true; <add> <add> public BitmapUtilsInstrumentationTest(String name) { <ide> super(); <ide> setName(name); <ide> } <ide> <del> public void testScaleBitmap(){ <add> public void test_bitmaputil_scales_bitmaps_to_specified_size(){ <ide> Bitmap bmOriginal = BitmapFactory.decodeResource(getInstrumentation().getContext().getResources(), R.drawable.icon); <del> assertTrue(bmOriginal.getHeight() <= 72); <del> assertTrue(bmOriginal.getWidth() <= 72); <add> assertFalse(bmOriginal.getHeight() == scaledBitmapSize); <add> assertFalse(bmOriginal.getWidth() == scaledBitmapSize); <add> <add> Bitmap bm = new BitmapUtil().scaleBitmap(bmOriginal, scaledBitmapSize, scaledBitmapSize, allowUpSampling); <ide> <del> Bitmap bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), 200, 200, R.drawable.icon, true); <del> <del> assertEquals(200, bm.getHeight()); <del> assertEquals(200, bm.getWidth()); <del> <del> bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), 200, 200, R.drawable.icon, false); <add> assertEquals(scaledBitmapSize, bm.getHeight()); <add> assertEquals(scaledBitmapSize, bm.getWidth()); <add> } <ide> <del> assertEquals(bmOriginal.getHeight(), bm.getHeight()); <del> assertEquals(bmOriginal.getWidth(), bm.getWidth()); <add> public void test_bitmaputil_creates_bitmaps__of_a_specified_size() { <add> Bitmap bm = new BitmapUtil().decodeResourceBitmapAndScale(getInstrumentation().getContext(), <add> scaledBitmapSize, scaledBitmapSize, R.drawable.icon, allowUpSampling); <ide> <del> bm = new BitmapUtil().scaleBitmap(bmOriginal, 200, 200, false); <del> assertEquals(bmOriginal, bm); <del> <del> bm = new BitmapUtil().scaleBitmap(bmOriginal, 200, 200, true); <del> assertNotSame(bmOriginal, bm); <del> assertEquals(200, bm.getHeight()); <del> assertEquals(200, bm.getWidth()); <del> <del> } <add> assertTrue(bm.getHeight() == scaledBitmapSize); <add> assertTrue(bm.getWidth() == scaledBitmapSize); <add> } <ide> <ide> <ide> }
JavaScript
agpl-3.0
08186751883ff504396226b8bcf52bd8056ed970
0
mapcentia/geocloud2,mapcentia/geocloud2,mapcentia/geocloud2,mapcentia/geocloud2,mapcentia/geocloud2,mapcentia/geocloud2
/* * @author Martin Høgh <[email protected]> * @copyright 2013-2018 MapCentia ApS * @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3 * */ /*global Ext:false */ /*global classWizards:false */ /*global store:false */ /*global App:false */ /*global wmsLayer:false */ /*global __:false */ Ext.namespace('classWizards'); classWizards.init = function (record) { "use strict"; var customIsSet = false, legendPanel, classGrid, classes, classStore = new Ext.data.Store({ fields: ['id', 'name', 'color'], writer: new Ext.data.JsonWriter({ writeAllFields: false, encode: false }), reader: new Ext.data.ArrayReader({ idIndex: 0, root: 'data' }, Ext.data.Record.create([ {name: 'id'}, {name: 'name'}, {name: 'color'} ])), proxy: new Ext.data.HttpProxy({ restful: true, type: 'json', api: { update: '/controllers/classification/index/' + record._key_ }, listeners: { write: function () { classGrid.getSelectionModel().clearSelections(); Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load(); }, exception: function (proxy, type, action, options, response, arg) { if (response.status !== 200) { Ext.MessageBox.show({ title: __("Failure"), msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 300, height: 300 }); } } } }), autoSave: true }), updateClassGrid = function () { var myData = [], i; classes = Ext.decode(store.getById(record._key_).json["class"]); for (i = 0; i < classes.length; i = i + 1) { myData.push([i, classes[i].name, classes[i].color]); } classStore.loadData({data: myData}); }; classGrid = new Ext.grid.EditorGridPanel({ store: classStore, frame: false, border: true, region: "center", viewConfig: { forceFit: true, stripeRows: true }, cm: new Ext.grid.ColumnModel({ defaults: { editor: { xtype: "textfield" } }, columns: [ { header: __("Title"), dataIndex: "name", editable: true, flex: 1 }, { header: __("Color"), dataIndex: "color", editable: true, flex: 1, editor: new Ext.grid.GridEditor(new Ext.form.ColorField({}), {}), renderer: function (value, meta) { meta.style = "background-color:" + value; return value; } } ] }) }); legendPanel = new Ext.Panel({ region: 'east', border: false, frame: false, width: 250, layout: "border", items: [classGrid, new Ext.Panel({ region: 'north', border: false, frame: false, // height: 100, html: "<div class=\"layer-desc\">Double click on value in the the legend to change it.</div>" })] }); store.load({ callback: function () { updateClassGrid(); } }); classWizards.setting = Ext.util.JSON.decode(record.classwizard); if (typeof classWizards.setting.custom !== "undefined" && typeof classWizards.setting.custom.pre !== "undefined") { customIsSet = true; } //console.log(classWizards.setting); classWizards.getAddvalues = function (pre) { var values = Ext.getCmp(pre + '_addform').form.getFieldValues(), f = Ext.getCmp(pre + "Form").form.getValues(); f.pre = pre; values.custom = f; return Ext.util.JSON.encode({data: values}); }; classWizards.getAddForm = function (pre) { var c = ((typeof classWizards.setting.custom !== "undefined" && typeof classWizards.setting.custom.pre !== "undefined") && pre === classWizards.setting.custom.pre) ? true : false; return new Ext.Panel({ region: "east", border: false, items: [ { xtype: "form", id: pre + "_addform", layout: "form", border: false, items: [ { xtype: 'fieldset', title: __('Symbol (Optional)'), items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Symbol") + __("Select a symbol for layer drawing. Leave empty for solid line and area style.", true) }, { xtype: 'box', html: __("Angle") + __("Angle, given in degrees, to rotate the symbol (counter clockwise). Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Size") + __("Height, in pixels, of the symbol/pattern to be used. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Outline color") + __('Color to use for outlining polygons and certain marker symbols (ellipse, vector polygons and truetype). Has no effect for lines.', true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ new Ext.form.ComboBox({ store: ['', 'circle', 'square', 'triangle', 'hatch1', 'dashed1', 'dot-dot', 'dashed-line-short', 'dashed-line-long', 'dash-dot', 'dash-dot-dot', 'arrow'], editable: false, triggerAction: 'all', name: "symbol", value: (customIsSet && c) ? classWizards.setting.symbol : "" }), { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "angle", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.angle : "" }, { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "symbolSize", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.symbolSize : "" }, new Ext.form.ColorField({ name: "outlineColor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.outlineColor : "" }) ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Line width") + __('Thickness of line work drawn, in pixels.', true) }, { xtype: 'box', html: __("Opacity") + __('Set opacity level between 1 and 100, where 100 is solid.', true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.ux.form.SpinnerField({ name: "lineWidth", minValue: 0, maxValue: 10, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: true, value: (customIsSet && c) ? classWizards.setting.lineWidth : "" }), new Ext.ux.form.SpinnerField({ name: "opacity", minValue: 0, maxValue: 100, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: true, value: (customIsSet && c) ? classWizards.setting.opacity : "" }) ] } ] }, { xtype: 'fieldset', title: __('Label (Optional)'), items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Text") + __("Text to label features with. Combo field: You write around like &apos;My label [attribute]&apos; or concatenate two or more attributes like &apos;[attribute1] [attribute2]&apos;.", true) }, { xtype: 'box', html: __("Color") + __("Color to draw text with.", true) }, { xtype: 'box', html: __("Size") + __("Size of the text in pixels. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Position") + __("Position of the label relative to the labeling point.", true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: wmsLayer.fieldsForStoreBrackets, editable: true, triggerAction: "all", name: "labelText", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelText : "" }, new Ext.form.ColorField({ name: "labelColor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelColor : "" }), { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "labelSize", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelSize : "" }, { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Auto', value: 'auto' }, { name: '↖', value: 'ul' }, { name: '↑', value: 'uc' }, { name: '↗', value: 'ur' }, { name: '←', value: 'cl' }, { name: '.', value: 'cc' }, { name: '→', value: 'cr' }, { name: '↙', value: 'll' }, { name: '↓', value: 'lc' }, { name: '↘', value: 'lr' } ] }), triggerAction: "all", name: "labelPosition", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelPosition : "" } ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Angle") + __("Angle, counterclockwise, given in degrees, to draw the label. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Background") + __("Color to draw a background rectangle (i.e. billboard)", true) }, { xtype: 'box', html: __("Font") + __("Font to use for labeling.", true) }, { xtype: 'box', html: __("Font weight") + __("Font weight.", true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "labelAngle", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelAngle : "" }, new Ext.form.ColorField({ name: "labelBackgroundcolor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelBackgroundcolor : "" }), { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', triggerAction: "all", name: "labelFont", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelFont : "", store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Arial', value: 'arial' }, { name: 'Courier new', value: 'courier' } ] }) }, { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', triggerAction: "all", name: "labelFontWeight", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelFontWeight : "", store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Normal', value: 'normal' }, { name: 'Bold', value: 'bold' }, { name: 'Italic', value: 'italic' }, { name: 'Bold italic', value: 'bolditalic' } ] }) } ] } ] } ] } ] }); }; classWizards.quantile = new Ext.Panel({ labelWidth: 1, frame: false, border: false, //autoHeight: true, height: 772, region: 'center', layout: "border", split: true, items: [ new Ext.Panel({ region: 'center', border: true, layout: "border", defaults: { border: false }, items: [ new Ext.Panel({ region: "center", items: [ new Ext.TabPanel({ resizeTabs: false, activeTab: (function () { var i, pre; if (customIsSet) { pre = classWizards.setting.custom.pre; if (pre === "single") { i = 0; } if (pre === "unique") { i = 1; } if (pre === "interval") { i = 2; } if (pre === "cluster") { i = 3; } return i; } else { return 0; } }()), border: false, defaults: { border: false }, plain: true, items: [ { title: __("Single"), defaults: { border: false }, items: [ { html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/single_class.png\')"></td></tr>' + '</table>' }, { padding: "5px", border: false, items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: "form", id: "singleForm", layout: "form", items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Color") + __("Select color", true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.form.ColorField({ name: "color", allowBlank: false, value: customIsSet ? classWizards.setting.custom.color : null }) ] } ] } ] }, classWizards.getAddForm("single"), { border: false, items: [ { xtype: 'button', text: 'Create single class', handler: function () { var f = Ext.getCmp('singleForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("single"); Ext.Ajax.request({ url: '/controllers/classification/single/' + record._key_ + '/' + values.color.replace("#", ""), method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: __('Failure'), msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] } ] }, { title: __("Unique"), defaults: { border: false }, items: [ { html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/unique_classes.png\')"></td></tr>' + '</table>' }, { padding: "5px", items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Field") + __("Select attribute field.", true) } ] }, { xtype: "form", id: "uniqueForm", layout: "form", items: [ { xtype: 'container', items: [ { xtype: 'container', layout: 'hbox', items: [ { xtype: "combo", store: wmsLayer.fieldsForStore, editable: false, triggerAction: "all", name: "value", width: 100, allowBlank: false, disabled: (record.type === "RASTER") ? true : false, emptyText: __("Field"), value: (customIsSet && classWizards.setting.custom.pre === "unique") ? classWizards.setting.custom.value : null }, { boxLabel: __("Random colors"), xtype: "radio", name: "colorramp", style: { marginLeft: "4px" }, inputValue: "-1", checked: (!customIsSet || (customIsSet && (typeof classWizards.setting.custom.colorramp === "undefined" || classWizards.setting.custom.colorramp === "-1"))) ? true : null } ] }, { xtype: 'box', height: 7 }, { xtype: 'radiogroup', layout: 'hbox', defaults: { xtype: "radio", name: "colorramp", width: 4, style: { margin: "4px" } }, items: [ { boxLabel: '<span class="color-ramp" style="background-color:#a6cee3;"></span>' + '<span class="color-ramp" style="background-color:#1f78b4;"></span>' + '<span class="color-ramp" style="background-color:#b2df8a;"></span>' + '<span class="color-ramp" style="background-color:#33a02c;"></span>' + '<span class="color-ramp" style="background-color:#fb9a99;"></span>' + '<span class="color-ramp" style="background-color:#e31a1c;"></span>' + '<span class="color-ramp" style="background-color:#fdbf6f;"></span>' + '<span class="color-ramp" style="background-color:#ff7f00;"></span>' + '<span class="color-ramp" style="background-color:#cab2d6;"></span>' + '<span class="color-ramp" style="background-color:#6a3d9a;"></span>' + '<span class="color-ramp" style="background-color:#ffff99;"></span>' + '<span class="color-ramp" style="background-color:#b15928;"></span>', inputValue: "0", checked: (customIsSet && classWizards.setting.custom.colorramp === "0") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#e41a1c;"></span>' + '<span class="color-ramp" style="background-color:#377eb8;"></span>' + '<span class="color-ramp" style="background-color:#4daf4a;"></span>' + '<span class="color-ramp" style="background-color:#984ea3;"></span>' + '<span class="color-ramp" style="background-color:#ff7f00;"></span>' + '<span class="color-ramp" style="background-color:#ffff33;"></span>' + '<span class="color-ramp" style="background-color:#a65628;"></span>' + '<span class="color-ramp" style="background-color:#f781bf;"></span>' + '<span class="color-ramp" style="background-color:#999999;"></span>', inputValue: "3", checked: (customIsSet && classWizards.setting.custom.colorramp === "3") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#7fc97f;"></span>' + '<span class="color-ramp" style="background-color:#beaed4;"></span>' + '<span class="color-ramp" style="background-color:#fdc086;"></span>' + '<span class="color-ramp" style="background-color:#ffff99;"></span>' + '<span class="color-ramp" style="background-color:#386cb0;"></span>' + '<span class="color-ramp" style="background-color:#f0027f;"></span>' + '<span class="color-ramp" style="background-color:#bf5b17;"></span>' + '<span class="color-ramp" style="background-color:#666666;"></span>', inputValue: "4", checked: (customIsSet && classWizards.setting.custom.colorramp === "4") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#1b9e77;"></span>' + '<span class="color-ramp" style="background-color:#d95f02;"></span>' + '<span class="color-ramp" style="background-color:#7570b3;"></span>' + '<span class="color-ramp" style="background-color:#e7298a;"></span>' + '<span class="color-ramp" style="background-color:#66a61e;"></span>' + '<span class="color-ramp" style="background-color:#e6ab02;"></span>' + '<span class="color-ramp" style="background-color:#a6761d;"></span>' + '<span class="color-ramp" style="background-color:#666666;"></span>', inputValue: "5", checked: (customIsSet && classWizards.setting.custom.colorramp === "5") ? true : null } ] }, { xtype: 'radiogroup', layout: 'hbox', defaults: { xtype: "radio", name: "colorramp", width: 4, style: { margin: "4px" } }, items: [ { boxLabel: '<span class="color-ramp" style="background-color:#8dd3c7;"></span>' + '<span class="color-ramp" style="background-color:#ffffb3;"></span>' + '<span class="color-ramp" style="background-color:#bebada;"></span>' + '<span class="color-ramp" style="background-color:#fb8072;"></span>' + '<span class="color-ramp" style="background-color:#80b1d3;"></span>' + '<span class="color-ramp" style="background-color:#fdb462;"></span>' + '<span class="color-ramp" style="background-color:#b3de69;"></span>' + '<span class="color-ramp" style="background-color:#fccde5;"></span>' + '<span class="color-ramp" style="background-color:#d9d9d9;"></span>' + '<span class="color-ramp" style="background-color:#bc80bd;"></span>' + '<span class="color-ramp" style="background-color:#ccebc5;"></span>' + '<span class="color-ramp" style="background-color:#ffed6f;"></span>', inputValue: "1", checked: (customIsSet && classWizards.setting.custom.colorramp === "1") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#fbb4ae;"></span>' + '<span class="color-ramp" style="background-color:#b3cde3;"></span>' + '<span class="color-ramp" style="background-color:#ccebc5;"></span>' + '<span class="color-ramp" style="background-color:#decbe4;"></span>' + '<span class="color-ramp" style="background-color:#fed9a6;"></span>' + '<span class="color-ramp" style="background-color:#ffffcc;"></span>' + '<span class="color-ramp" style="background-color:#e5d8bd;"></span>' + '<span class="color-ramp" style="background-color:#fddaec;"></span>' + '<span class="color-ramp" style="background-color:#f2f2f2;"></span>', inputValue: "2", checked: (customIsSet && classWizards.setting.custom.colorramp === "2") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#66c2a5;"></span>' + '<span class="color-ramp" style="background-color:#fc8d62;"></span>' + '<span class="color-ramp" style="background-color:#8da0cb;"></span>' + '<span class="color-ramp" style="background-color:#e78ac3;"></span>' + '<span class="color-ramp" style="background-color:#a6d854;"></span>' + '<span class="color-ramp" style="background-color:#ffd92f;"></span>' + '<span class="color-ramp" style="background-color:#e5c494;"></span>' + '<span class="color-ramp" style="background-color:#b3b3b3;"></span>', inputValue: "8", checked: (customIsSet && classWizards.setting.custom.colorramp === "8") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#b3e2cd;"></span>' + '<span class="color-ramp" style="background-color:#fdcdac;"></span>' + '<span class="color-ramp" style="background-color:#cbd5e8;"></span>' + '<span class="color-ramp" style="background-color:#f4cae4;"></span>' + '<span class="color-ramp" style="background-color:#e6f5c9;"></span>' + '<span class="color-ramp" style="background-color:#fff2ae;"></span>' + '<span class="color-ramp" style="background-color:#f1e2cc;"></span>' + '<span class="color-ramp" style="background-color:#cccccc;"></span>', inputValue: "7", checked: (customIsSet && classWizards.setting.custom.colorramp === "7") ? true : null } ] }, { xtype: 'box', height: 7 }, { xtype: 'box', html: "<span style='font-size: 7pt'>Colors from www.ColorBrewer.org by Cynthia A. Brewer, Penn State.</span>" } ] } ] } ] }, classWizards.getAddForm("unique"), { layout: 'form', border: false, items: [ { xtype: 'button', text: 'Create unique values', disabled: (record.type === "RASTER") ? true : false, handler: function () { var f = Ext.getCmp('uniqueForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("unique"); Ext.Ajax.request({ url: '/controllers/classification/unique/' + record._key_ + '/' + values.value, method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] } ] }, { title: __("Intervals"), defaults: { border: false }, items: [{ html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/interval_classes.png\')"></td></tr>' + '</table>' }, { padding: '5px', items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Type") + __("How should the intervals be calculated", true) }, { xtype: 'box', html: __("Numeric field") + __("Select attribute field. Only numeric is shown.", true) }, { xtype: 'box', html: __("# of colors") + __("How many intervals should be calculated.", true) } ] }, { xtype: "form", id: "intervalForm", layout: "form", items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: new Ext.data.ArrayStore({ fields: ['type', 'display'], data: (record.type === "RASTER") ? [ ['equal', 'Equal'] ] : [ ['equal', 'Equal'], ['quantile', 'Quantile'] ] }), displayField: 'display', valueField: 'type', editable: false, triggerAction: "all", name: "type", allowBlank: false, mode: 'local', value: customIsSet ? classWizards.setting.custom.type : (record.type === "RASTER") ? 'Equal' : null }, { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: false, triggerAction: "all", name: "value", allowBlank: false, value: (customIsSet && classWizards.setting.custom.pre === "interval") ? classWizards.setting.custom.value : (record.type === "RASTER") ? "pixel" : null }, new Ext.ux.form.SpinnerField({ name: "num", minValue: 1, maxValue: 100, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: false, value: customIsSet ? classWizards.setting.custom.num : null }) ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Start color") + __("Select start color in the color ramp.", true) }, { xtype: 'box', html: __("End color") + __("Select end color in the color ramp.", true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.form.ColorField({ name: "start", allowBlank: false, value: (customIsSet) ? classWizards.setting.custom.start : null }), new Ext.form.ColorField({ name: "end", allowBlank: false, value: (customIsSet) ? classWizards.setting.custom.end : null }) ] } ] } ] }, classWizards.getAddForm("interval"), { layout: 'form', border: false, items: [ { xtype: 'button', border: false, text: __("Create intervals"), width: 'auto', handler: function () { var f = Ext.getCmp('intervalForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("interval"); Ext.Ajax.request({ url: '/controllers/classification/' + values.type.toLowerCase() + '/' + record._key_ + '/' + values.value + '/' + values.num + '/' + values.start.replace("#", "") + '/' + values.end.replace("#", "") + '/', method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: eval('(' + response.responseText + ')').message, buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] }] }, { title: __("Clusters"), defaults: { border: false }, items: [{ html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/cluster_classes.png\')"></td></tr>' + '</table>' }, { padding: "5px", items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: "form", id: "clusterForm", layout: "form", items: [ { xtype: 'container', defaults: { width: 150 }, items: [ new Ext.ux.form.SpinnerField({ name: "clusterdistance", minValue: 1, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: false, emptyText: __("Cluster distance"), disabled: (record.type === "RASTER") ? true : false, value: (customIsSet) ? classWizards.setting.custom.clusterdistance : null }) ] } ] } ] }, { layout: 'form', border: false, items: [ { xtype: 'button', text: 'Create clusters', disabled: (record.type === "RASTER") ? true : false, handler: function () { var f = Ext.getCmp('clusterForm'), values, params; if (f.form.isValid()) { values = f.form.getValues(); Ext.Ajax.request({ url: '/controllers/classification/cluster/' + record._key_ + '/' + values.clusterdistance, method: 'put', params: Ext.util.JSON.encode({ data: { custom: { pre: "cluster", clusterdistance: values.clusterdistance } } }), headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] }] } ] })] }), legendPanel ] }) ] }); };
public/js/admin/classwizards.js
/* * @author Martin Høgh <[email protected]> * @copyright 2013-2018 MapCentia ApS * @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3 * */ /*global Ext:false */ /*global classWizards:false */ /*global store:false */ /*global App:false */ /*global wmsLayer:false */ /*global __:false */ Ext.namespace('classWizards'); classWizards.init = function (record) { "use strict"; var customIsSet = false, legendPanel, classGrid, classes, classStore = new Ext.data.Store({ fields: ['id', 'name', 'color'], writer: new Ext.data.JsonWriter({ writeAllFields: false, encode: false }), reader: new Ext.data.ArrayReader({ idIndex: 0, root: 'data' }, Ext.data.Record.create([ {name: 'id'}, {name: 'name'}, {name: 'color'} ])), proxy: new Ext.data.HttpProxy({ restful: true, type: 'json', api: { update: '/controllers/classification/index/' + record._key_ }, listeners: { write: function () { classGrid.getSelectionModel().clearSelections(); Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load(); }, exception: function (proxy, type, action, options, response, arg) { if (response.status !== 200) { Ext.MessageBox.show({ title: __("Failure"), msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 300, height: 300 }); } } } }), autoSave: true }), updateClassGrid = function () { var myData = [], i; classes = Ext.decode(store.getById(record._key_).json["class"]); for (i = 0; i < classes.length; i = i + 1) { myData.push([i, classes[i].name, classes[i].color]); } classStore.loadData({data: myData}); }; classGrid = new Ext.grid.EditorGridPanel({ store: classStore, frame: false, border: true, region: "center", viewConfig: { forceFit: true, stripeRows: true }, cm: new Ext.grid.ColumnModel({ defaults: { editor: { xtype: "textfield" } }, columns: [ { header: __("Title"), dataIndex: "name", editable: true, flex: 1 }, { header: __("Color"), dataIndex: "color", editable: true, flex: 1, editor: new Ext.grid.GridEditor(new Ext.form.ColorField({}), {}), renderer: function (value, meta) { meta.style = "background-color:" + value; return value; } } ] }) }); legendPanel = new Ext.Panel({ region: 'east', border: false, frame: false, width: 250, layout: "border", items: [classGrid, new Ext.Panel({ region: 'north', border: false, frame: false, // height: 100, html: "<div class=\"layer-desc\">Double click on value in the the legend to change it.</div>" })] }); store.load({ callback: function () { updateClassGrid(); } }); classWizards.setting = Ext.util.JSON.decode(record.classwizard); if (typeof classWizards.setting.custom !== "undefined" && typeof classWizards.setting.custom.pre !== "undefined") { customIsSet = true; } //console.log(classWizards.setting); classWizards.getAddvalues = function (pre) { var values = Ext.getCmp(pre + '_addform').form.getFieldValues(), f = Ext.getCmp(pre + "Form").form.getValues(); f.pre = pre; values.custom = f; return Ext.util.JSON.encode({data: values}); }; classWizards.getAddForm = function (pre) { var c = ((typeof classWizards.setting.custom !== "undefined" && typeof classWizards.setting.custom.pre !== "undefined") && pre === classWizards.setting.custom.pre) ? true : false; return new Ext.Panel({ region: "east", border: false, items: [ { xtype: "form", id: pre + "_addform", layout: "form", border: false, items: [ { xtype: 'fieldset', title: __('Symbol (Optional)'), items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Symbol") + __("Select a symbol for layer drawing. Leave empty for solid line and area style.", true) }, { xtype: 'box', html: __("Angle") + __("Angle, given in degrees, to rotate the symbol (counter clockwise). Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Size") + __("Height, in pixels, of the symbol/pattern to be used. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Outline color") + __('Color to use for outlining polygons and certain marker symbols (ellipse, vector polygons and truetype). Has no effect for lines.', true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ new Ext.form.ComboBox({ store: ['', 'circle', 'square', 'triangle', 'hatch1', 'dashed1', 'dot-dot', 'dashed-line-short', 'dashed-line-long', 'dash-dot', 'dash-dot-dot', 'arrow'], editable: false, triggerAction: 'all', name: "symbol", value: (customIsSet && c) ? classWizards.setting.symbol : "" }), { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "angle", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.angle : "" }, { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "symbolSize", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.symbolSize : "" }, new Ext.form.ColorField({ name: "outlineColor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.outlineColor : "" }) ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Line width") + __('Thickness of line work drawn, in pixels.', true) }, { xtype: 'box', html: __("Opacity") + __('Set opacity level between 1 and 100, where 100 is solid.', true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.ux.form.SpinnerField({ name: "lineWidth", minValue: 0, maxValue: 10, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: true, value: (customIsSet && c) ? classWizards.setting.lineWidth : "" }), new Ext.ux.form.SpinnerField({ name: "opacity", minValue: 0, maxValue: 100, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: true, value: (customIsSet && c) ? classWizards.setting.opacity : "" }) ] } ] }, { xtype: 'fieldset', title: __('Label (Optional)'), items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Text") + __("Text to label features with. Combo field: You write around like &apos;My label [attribute]&apos; or concatenate two or more attributes like &apos;[attribute1] [attribute2]&apos;.", true) }, { xtype: 'box', html: __("Color") + __("Color to draw text with.", true) }, { xtype: 'box', html: __("Size") + __("Size of the text in pixels. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Position") + __("Position of the label relative to the labeling point.", true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: wmsLayer.fieldsForStoreBrackets, editable: true, triggerAction: "all", name: "labelText", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelText : "" }, new Ext.form.ColorField({ name: "labelColor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelColor : "" }), { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "labelSize", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelSize : "" }, { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Auto', value: 'auto' }, { name: '↖', value: 'ul' }, { name: '↑', value: 'uc' }, { name: '↗', value: 'ur' }, { name: '←', value: 'cl' }, { name: '.', value: 'cc' }, { name: '→', value: 'cr' }, { name: '↙', value: 'll' }, { name: '↓', value: 'lc' }, { name: '↘', value: 'lr' } ] }), triggerAction: "all", name: "labelPosition", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelPosition : "" } ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Angle") + __("Angle, counterclockwise, given in degrees, to draw the label. Combo field: Either select an integer attribute or write an integer.", true) }, { xtype: 'box', html: __("Background") + __("Color to draw a background rectangle (i.e. billboard)", true) }, { xtype: 'box', html: __("Font") + __("Font to use for labeling.", true) }, { xtype: 'box', html: __("Font weight") + __("Font weight.", true) } ] }, { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: true, triggerAction: "all", name: "labelAngle", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelAngle : "" }, new Ext.form.ColorField({ name: "labelBackgroundcolor", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelBackgroundcolor : "" }), { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', triggerAction: "all", name: "labelFont", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelFont : "", store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Arial', value: 'arial' }, { name: 'Courier new', value: 'courier' } ] }) }, { xtype: "combo", editable: false, displayField: 'name', valueField: 'value', mode: 'local', triggerAction: "all", name: "labelFontWeight", allowBlank: true, value: (customIsSet && c) ? classWizards.setting.labelFontWeight : "", store: new Ext.data.JsonStore({ fields: ['name', 'value'], data: [ { name: 'Normal', value: 'normal' }, { name: 'Bold', value: 'bold' }, { name: 'Italic', value: 'italic' }, { name: 'Bold italic', value: 'bolditalic' } ] }) } ] } ] } ] } ] }); }; classWizards.quantile = new Ext.Panel({ labelWidth: 1, frame: false, border: false, //autoHeight: true, height: 772, region: 'center', layout: "border", split: true, items: [ new Ext.Panel({ region: 'center', border: true, layout: "border", defaults: { border: false }, items: [ new Ext.Panel({ region: "center", items: [ new Ext.TabPanel({ resizeTabs: false, activeTab: (function () { var i, pre; if (customIsSet) { pre = classWizards.setting.custom.pre; if (pre === "single") { i = 0; } if (pre === "unique") { i = 1; } if (pre === "interval") { i = 2; } if (pre === "cluster") { i = 3; } return i; } else { return 0; } }()), border: false, defaults: { border: false }, plain: true, items: [ { title: __("Single"), defaults: { border: false }, items: [ { html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/single_class.png\')"></td></tr>' + '</table>' }, { padding: "5px", border: false, items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: "form", id: "singleForm", layout: "form", items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Color") + __("Select color", true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.form.ColorField({ name: "color", allowBlank: false, value: customIsSet ? classWizards.setting.custom.color : null }) ] } ] } ] }, classWizards.getAddForm("single"), { border: false, items: [ { xtype: 'button', text: 'Create single class', handler: function () { var f = Ext.getCmp('singleForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("single"); Ext.Ajax.request({ url: '/controllers/classification/single/' + record._key_ + '/' + values.color.replace("#", ""), method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: __('Failure'), msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] } ] }, { title: __("Unique"), defaults: { border: false }, items: [ { html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/unique_classes.png\')"></td></tr>' + '</table>' }, { padding: "5px", items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Field") + __("Select attribute field.", true) } ] }, { xtype: "form", id: "uniqueForm", layout: "form", items: [ { xtype: 'container', items: [ { xtype: 'container', layout: 'hbox', items: [ { xtype: "combo", store: wmsLayer.fieldsForStore, editable: false, triggerAction: "all", name: "value", width: 100, allowBlank: false, disabled: (record.type === "RASTER") ? true : false, emptyText: __("Field"), value: (customIsSet && classWizards.setting.custom.pre === "unique") ? classWizards.setting.custom.value : null }, { boxLabel: __("Random colors"), xtype: "radio", name: "colorramp", style: { marginLeft: "4px" }, inputValue: "-1", checked: (!customIsSet || (customIsSet && (typeof classWizards.setting.custom.colorramp === "undefined" || classWizards.setting.custom.colorramp === "-1"))) ? true : null } ] }, { xtype: 'box', height: 7 }, { xtype: 'radiogroup', layout: 'hbox', defaults: { xtype: "radio", name: "colorramp", width: 4, style: { margin: "4px" } }, items: [ { boxLabel: '<span class="color-ramp" style="background-color:#a6cee3;"></span>' + '<span class="color-ramp" style="background-color:#1f78b4;"></span>' + '<span class="color-ramp" style="background-color:#b2df8a;"></span>' + '<span class="color-ramp" style="background-color:#33a02c;"></span>' + '<span class="color-ramp" style="background-color:#fb9a99;"></span>' + '<span class="color-ramp" style="background-color:#e31a1c;"></span>' + '<span class="color-ramp" style="background-color:#fdbf6f;"></span>' + '<span class="color-ramp" style="background-color:#ff7f00;"></span>' + '<span class="color-ramp" style="background-color:#cab2d6;"></span>' + '<span class="color-ramp" style="background-color:#6a3d9a;"></span>' + '<span class="color-ramp" style="background-color:#ffff99;"></span>' + '<span class="color-ramp" style="background-color:#b15928;"></span>', inputValue: "0", checked: (customIsSet && classWizards.setting.custom.colorramp === "0") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#e41a1c;"></span>' + '<span class="color-ramp" style="background-color:#377eb8;"></span>' + '<span class="color-ramp" style="background-color:#4daf4a;"></span>' + '<span class="color-ramp" style="background-color:#984ea3;"></span>' + '<span class="color-ramp" style="background-color:#ff7f00;"></span>' + '<span class="color-ramp" style="background-color:#ffff33;"></span>' + '<span class="color-ramp" style="background-color:#a65628;"></span>' + '<span class="color-ramp" style="background-color:#f781bf;"></span>' + '<span class="color-ramp" style="background-color:#999999;"></span>', inputValue: "3", checked: (customIsSet && classWizards.setting.custom.colorramp === "3") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#7fc97f;"></span>' + '<span class="color-ramp" style="background-color:#beaed4;"></span>' + '<span class="color-ramp" style="background-color:#fdc086;"></span>' + '<span class="color-ramp" style="background-color:#ffff99;"></span>' + '<span class="color-ramp" style="background-color:#386cb0;"></span>' + '<span class="color-ramp" style="background-color:#f0027f;"></span>' + '<span class="color-ramp" style="background-color:#bf5b17;"></span>' + '<span class="color-ramp" style="background-color:#666666;"></span>', inputValue: "4", checked: (customIsSet && classWizards.setting.custom.colorramp === "4") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#1b9e77;"></span>' + '<span class="color-ramp" style="background-color:#d95f02;"></span>' + '<span class="color-ramp" style="background-color:#7570b3;"></span>' + '<span class="color-ramp" style="background-color:#e7298a;"></span>' + '<span class="color-ramp" style="background-color:#66a61e;"></span>' + '<span class="color-ramp" style="background-color:#e6ab02;"></span>' + '<span class="color-ramp" style="background-color:#a6761d;"></span>' + '<span class="color-ramp" style="background-color:#666666;"></span>', inputValue: "5", checked: (customIsSet && classWizards.setting.custom.colorramp === "5") ? true : null } ] }, { xtype: 'radiogroup', layout: 'hbox', defaults: { xtype: "radio", name: "colorramp", width: 4, style: { margin: "4px" } }, items: [ { boxLabel: '<span class="color-ramp" style="background-color:#8dd3c7;"></span>' + '<span class="color-ramp" style="background-color:#ffffb3;"></span>' + '<span class="color-ramp" style="background-color:#bebada;"></span>' + '<span class="color-ramp" style="background-color:#fb8072;"></span>' + '<span class="color-ramp" style="background-color:#80b1d3;"></span>' + '<span class="color-ramp" style="background-color:#fdb462;"></span>' + '<span class="color-ramp" style="background-color:#b3de69;"></span>' + '<span class="color-ramp" style="background-color:#fccde5;"></span>' + '<span class="color-ramp" style="background-color:#d9d9d9;"></span>' + '<span class="color-ramp" style="background-color:#bc80bd;"></span>' + '<span class="color-ramp" style="background-color:#ccebc5;"></span>' + '<span class="color-ramp" style="background-color:#ffed6f;"></span>', inputValue: "1", checked: (customIsSet && classWizards.setting.custom.colorramp === "1") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#fbb4ae;"></span>' + '<span class="color-ramp" style="background-color:#b3cde3;"></span>' + '<span class="color-ramp" style="background-color:#ccebc5;"></span>' + '<span class="color-ramp" style="background-color:#decbe4;"></span>' + '<span class="color-ramp" style="background-color:#fed9a6;"></span>' + '<span class="color-ramp" style="background-color:#ffffcc;"></span>' + '<span class="color-ramp" style="background-color:#e5d8bd;"></span>' + '<span class="color-ramp" style="background-color:#fddaec;"></span>' + '<span class="color-ramp" style="background-color:#f2f2f2;"></span>', inputValue: "2", checked: (customIsSet && classWizards.setting.custom.colorramp === "2") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#66c2a5;"></span>' + '<span class="color-ramp" style="background-color:#fc8d62;"></span>' + '<span class="color-ramp" style="background-color:#8da0cb;"></span>' + '<span class="color-ramp" style="background-color:#e78ac3;"></span>' + '<span class="color-ramp" style="background-color:#a6d854;"></span>' + '<span class="color-ramp" style="background-color:#ffd92f;"></span>' + '<span class="color-ramp" style="background-color:#e5c494;"></span>' + '<span class="color-ramp" style="background-color:#b3b3b3;"></span>', inputValue: "8", checked: (customIsSet && classWizards.setting.custom.colorramp === "8") ? true : null }, { boxLabel: '<span class="color-ramp" style="background-color:#b3e2cd;"></span>' + '<span class="color-ramp" style="background-color:#fdcdac;"></span>' + '<span class="color-ramp" style="background-color:#cbd5e8;"></span>' + '<span class="color-ramp" style="background-color:#f4cae4;"></span>' + '<span class="color-ramp" style="background-color:#e6f5c9;"></span>' + '<span class="color-ramp" style="background-color:#fff2ae;"></span>' + '<span class="color-ramp" style="background-color:#f1e2cc;"></span>' + '<span class="color-ramp" style="background-color:#cccccc;"></span>', inputValue: "7", checked: (customIsSet && classWizards.setting.custom.colorramp === "7") ? true : null } ] }, { xtype: 'box', height: 7 }, { xtype: 'box', html: "<span style='font-size: 7pt'>Colors from www.ColorBrewer.org by Cynthia A. Brewer, Penn State.</span>" } ] } ] } ] }, classWizards.getAddForm("unique"), { layout: 'form', border: false, items: [ { xtype: 'button', text: 'Create unique values', disabled: (record.type === "RASTER") ? true : false, handler: function () { var f = Ext.getCmp('uniqueForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("unique"); Ext.Ajax.request({ url: '/controllers/classification/unique/' + record._key_ + '/' + values.value, method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] } ] }, { title: __("Intervals"), defaults: { border: false }, items: [{ html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/interval_classes.png\')"></td></tr>' + '</table>' }, { padding: '5px', items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Type") + __("How should the intervals be calculated", true) }, { xtype: 'box', html: __("Numeric field") + __("Select attribute field. Only numeric is shown.", true) }, { xtype: 'box', html: __("# of colors") + __("How many intervals should be calculated.", true) } ] }, { xtype: "form", id: "intervalForm", layout: "form", items: [ { xtype: 'container', layout: 'hbox', defaults: { width: 95 }, items: [ { xtype: "combo", store: new Ext.data.ArrayStore({ fields: ['type', 'display'], data: (record.type === "RASTER") ? [ ['equal', 'Equal'] ] : [ ['equal', 'Equal'], ['quantile', 'Quantile'] ] }), displayField: 'display', valueField: 'type', editable: false, triggerAction: "all", name: "type", allowBlank: false, mode: 'local', value: customIsSet ? classWizards.setting.custom.type : (record.type === "RASTER") ? 'Equal' : null }, { xtype: "combo", store: wmsLayer.numFieldsForStore, editable: false, triggerAction: "all", name: "value", allowBlank: false, value: (customIsSet && classWizards.setting.custom.pre === "interval") ? classWizards.setting.custom.value : (record.type === "RASTER") ? "pixel" : null }, new Ext.ux.form.SpinnerField({ name: "num", minValue: 1, maxValue: 20, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: false, value: customIsSet ? classWizards.setting.custom.num : null }) ] }, { xtype: 'box', height: 7 }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ { xtype: 'box', html: __("Start color") + __("Select start color in the color ramp.", true) }, { xtype: 'box', html: __("End color") + __("Select end color in the color ramp.", true) } ] }, { xtype: 'container', layout: 'hbox', width: 285, defaults: { width: 95 }, items: [ new Ext.form.ColorField({ name: "start", allowBlank: false, value: (customIsSet) ? classWizards.setting.custom.start : null }), new Ext.form.ColorField({ name: "end", allowBlank: false, value: (customIsSet) ? classWizards.setting.custom.end : null }) ] } ] } ] }, classWizards.getAddForm("interval"), { layout: 'form', border: false, items: [ { xtype: 'button', border: false, text: __("Create intervals"), width: 'auto', handler: function () { var f = Ext.getCmp('intervalForm'); if (f.form.isValid()) { var values = f.form.getValues(), params = classWizards.getAddvalues("interval"); Ext.Ajax.request({ url: '/controllers/classification/' + values.type.toLowerCase() + '/' + record._key_ + '/' + values.value + '/' + values.num + '/' + values.start.replace("#", "") + '/' + values.end.replace("#", "") + '/', method: 'put', params: params, headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: eval('(' + response.responseText + ')').message, buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] }] }, { title: __("Clusters"), defaults: { border: false }, items: [{ html: '<table class="map-thumbs-table">' + '<tr class="x-grid3-row"><td class="map-thumbs" style="background-image:url(\'/assets/images/cluster_classes.png\')"></td></tr>' + '</table>' }, { padding: "5px", items: [ { xtype: 'fieldset', title: __('(Required)'), defaults: { border: false }, items: [ { xtype: "form", id: "clusterForm", layout: "form", items: [ { xtype: 'container', defaults: { width: 150 }, items: [ new Ext.ux.form.SpinnerField({ name: "clusterdistance", minValue: 1, allowDecimals: false, decimalPrecision: 0, incrementValue: 1, accelerate: true, allowBlank: false, emptyText: __("Cluster distance"), disabled: (record.type === "RASTER") ? true : false, value: (customIsSet) ? classWizards.setting.custom.clusterdistance : null }) ] } ] } ] }, { layout: 'form', border: false, items: [ { xtype: 'button', text: 'Create clusters', disabled: (record.type === "RASTER") ? true : false, handler: function () { var f = Ext.getCmp('clusterForm'), values, params; if (f.form.isValid()) { values = f.form.getValues(); Ext.Ajax.request({ url: '/controllers/classification/cluster/' + record._key_ + '/' + values.clusterdistance, method: 'put', params: Ext.util.JSON.encode({ data: { custom: { pre: "cluster", clusterdistance: values.clusterdistance } } }), headers: { 'Content-Type': 'application/json; charset=utf-8' }, success: function (response) { Ext.getCmp("a3").remove(wmsClass.grid); wmsClasses.store.load(); writeFiles(record._key_, map); store.load({ callback: function () { updateClassGrid(); } }); App.setAlert(__(App.STATUS_NOTICE), __(Ext.decode(response.responseText).message)); }, failure: function (response) { Ext.MessageBox.show({ title: 'Failure', msg: __(Ext.decode(response.responseText).message), buttons: Ext.MessageBox.OK, width: 400, height: 300, icon: Ext.MessageBox.ERROR }); } }); } else { var s = ''; Ext.iterate(f.form.getValues(), function (key, value) { s += String.format("{0} = {1}<br />", key, value); }, this); } } } ] } ] }] } ] })] }), legendPanel ] }) ] }); };
Increase max number of colors to 100 in Class Wizard -> Intervals
public/js/admin/classwizards.js
Increase max number of colors to 100 in Class Wizard -> Intervals
<ide><path>ublic/js/admin/classwizards.js <ide> new Ext.ux.form.SpinnerField({ <ide> name: "num", <ide> minValue: 1, <del> maxValue: 20, <add> maxValue: 100, <ide> allowDecimals: false, <ide> decimalPrecision: 0, <ide> incrementValue: 1,
Java
mit
f47d53c9b810d572f93531ba214f9469640aff10
0
abrabete/Pebble_Game
package pebbles; import java.util.LinkedList; import java.util.Random; import java.io.*; import java.util.concurrent.atomic.AtomicInteger; /** * Created by Andrei on 10/20/2014. * * */ class PebbleGame { static class Player implements Runnable { private final int name; private LinkedList<Pebble> pebbles; Random next = new Random(); public Player (int name) { this.name = name; this.pebbles = new LinkedList<Pebble>(); } int getTotalValue() { int total = 0; for (Object pebble : this.pebbles) { Pebble current = (Pebble) pebble; total += current.getWeight(); } return total; } int getPlayerName() { return this.name; } synchronized void discardPebble() { Random random1 = new Random(); int handIndex = random1.nextInt(9); Pebble discarding = this.pebbles.remove(handIndex); Bag parent = this.pebbles.getLast().getParentBag(); if (parent == bagX) { bagA.addPebble(discarding); String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagA"; WriteToFile.write(this.getPlayerName(), message); System.out.println(message); } if (parent == bagY) { bagB.addPebble(discarding); String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagB"; WriteToFile.write(this.getPlayerName(), message); System.out.println(message); } if (parent == bagZ) { bagC.addPebble(discarding); String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagC"; WriteToFile.write(this.getPlayerName(), message); System.out.println(message); } } synchronized void takeInitialPebble(Bag bag) { Random random1 = new Random(); int bagIndex = random1.nextInt(bag.sizeOfBag()-1); this.pebbles.add(bag.removePebble(bagIndex)); } synchronized void takePebble() { String message; int randomBag = next.nextInt(2); if (randomBag == 0){ if (bagX.sizeOfBag() !=0) { takeInitialPebble(bagX); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagY.sizeOfBag() !=0){ takeInitialPebble(bagY); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagZ.sizeOfBag() != 0){ takeInitialPebble(bagZ); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } if (randomBag == 1){ if (bagY.sizeOfBag() !=0) { takeInitialPebble(bagY); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagZ.sizeOfBag() !=0){ takeInitialPebble(bagZ); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagX.sizeOfBag() != 0){ takeInitialPebble(bagX); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } if (randomBag == 2){ if (bagZ.sizeOfBag() !=0) { takeInitialPebble(bagZ); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagX.sizeOfBag() !=0){ takeInitialPebble(bagX); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagY.sizeOfBag() != 0){ takeInitialPebble(bagY); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } } public void run() { WriteToFile.create(name); Bag full; String message; for (int i =0;i< 9;i++) { full = PebbleGame.fullestBag(bagX,bagY,bagZ); takeInitialPebble(full); message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+full.getName(); WriteToFile.write(name,message); System.out.println(message); } while (!PebbleGame.done) { if (bagX.sizeOfBag() == 0 && bagA.sizeOfBag() != 0){ bagX.transferPebbles(bagA); } if (bagY.sizeOfBag() == 0 && bagB.sizeOfBag() != 0){ bagY.transferPebbles(bagB); } if (bagZ.sizeOfBag() == 0 && bagC.sizeOfBag() != 0){ bagZ.transferPebbles(bagC); } takePebble(); if (this.getTotalValue() == 100) { PebbleGame.done = true; endCredits(this.getPlayerName()); } discardPebble(); } } private synchronized void endCredits(int i){ String message; if (this.getTotalValue() == 100) { PebbleGame.done = true; message = "player"+i+" has won"; WriteToFile.write(i,message); System.out.println(message); } for (int j=1;j<=PebbleGame.playersNr.get(); j++) { message = "player"+j+" has lost, as player"+i+" has won."; if (j != i) { WriteToFile.write(j,message); } } } } private static Bag fullest; static Bag bagA = new Bag("A","white"); static Bag bagB = new Bag("B","white"); static Bag bagC = new Bag("C","white"); static Bag bagX = new Bag("X","black"); static Bag bagY = new Bag("Y","black"); static Bag bagZ = new Bag("Z","black"); static boolean done = false; static AtomicInteger playersNr; public static void main(String args[]) throws NotEnoughPebblesException, InvalidPlayersNumberException { fillBag(bagX,args[0]); fillBag(bagY,args[1]); fillBag(bagZ,args[2]); playersNr = new AtomicInteger(Integer.parseInt(args[3])); checkPlayersNumber(playersNr.get()); checkEnoughPebbles(bagX, bagY,bagZ, playersNr.get()); int i; for (i = 1; i <= playersNr.get(); i++) { new Thread(new Player(i)).start(); } WriteToFile.closing(playersNr.get()); } private static void fillBag(Bag bag, String fileName) { try { FileReader fileReader = new FileReader(fileName); BufferedReader in = new BufferedReader(fileReader); String values1 = in.readLine(); String[] xWeights = values1.split(","); for (String xWeight : xWeights) { int weight; weight = Integer.parseInt(xWeight); if (weight <= 0) { System.out.println("Weight value is smaller than 0."); break; } Pebble bagFiller = new Pebble(weight); bagFiller.setParentBag(bag); bag.addPebble(bagFiller); } } catch (FileNotFoundException e) { System.out.println("File not found for Bag: "+bag.getName()); } catch (IOException e) { System.out.println("IO Exception thrown."); } } private static void checkEnoughPebbles(Bag bagx, Bag bagy, Bag bagz, int players) throws NotEnoughPebblesException { int counter; counter = bagx.sizeOfBag()+bagy.sizeOfBag()+bagz.sizeOfBag(); if (counter < ((players*9)+1)) { throw new NotEnoughPebblesException(); } } private static void checkPlayersNumber(int players) throws InvalidPlayersNumberException { if (players < 2) throw new InvalidPlayersNumberException(); } private static Bag fullestBag(Bag bagx, Bag bagy, Bag bagz) { int max = 0; if (max < bagx.sizeOfBag()) { fullest = bagx; max = bagx.sizeOfBag(); } if (max < bagy.sizeOfBag()) { fullest = bagy; max = bagy.sizeOfBag(); } if (max < bagz.sizeOfBag()) { fullest = bagz; } return fullest; } }
src/Pebbles/PebbleGame.java
package pebbles; import java.util.LinkedList; import java.util.Random; import java.io.*; import java.util.concurrent.atomic.AtomicInteger; /** * Created by Andrei on 10/20/2014. * * */ class PebbleGame { static class Player implements Runnable { private final int name; private LinkedList<Pebble> pebbles; private int totalValue; private int totalPebbles; private volatile boolean done = false; Random next = new Random(); public Player (int name) { this.name = name; this.pebbles = new LinkedList<Pebble>(); this.totalValue = 0; this.totalPebbles = 0; } int getTotalValue() { int total = 0; for (Object pebble : this.pebbles) { Pebble current = (Pebble) pebble; total += current.getWeight(); } return total; } int getPlayerName() { return this.name; } int getTotalPebbles() { return this.totalPebbles; } Pebble discardPebble() { this.totalPebbles--; Random random1 = new Random(); int handIndex = random1.nextInt(9); return this.pebbles.remove(handIndex); } void takeInitialPebble(Bag bag) { this.totalPebbles++; Random random1 = new Random(); int bagIndex = random1.nextInt(bag.sizeOfBag()-1); this.pebbles.add(bag.removePebble(bagIndex)); } void takePebble() { String message; int randomBag = next.nextInt(2); if (randomBag == 0){ if (bagX.sizeOfBag() !=0) { takeInitialPebble(bagX); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagY.sizeOfBag() !=0){ takeInitialPebble(bagY); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagZ.sizeOfBag() != 0){ takeInitialPebble(bagZ); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } if (randomBag == 1){ if (bagY.sizeOfBag() !=0) { takeInitialPebble(bagY); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagZ.sizeOfBag() !=0){ takeInitialPebble(bagZ); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagX.sizeOfBag() != 0){ takeInitialPebble(bagX); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } if (randomBag == 2){ if (bagZ.sizeOfBag() !=0) { takeInitialPebble(bagZ); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagX.sizeOfBag() !=0){ takeInitialPebble(bagX); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); WriteToFile.write(name,message); System.out.println(message); } else { if (bagY.sizeOfBag() != 0){ takeInitialPebble(bagY); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); WriteToFile.write(name,message); System.out.println(message); } else { System.out.println("All bags are empty!"); } } } } } public void run() { WriteToFile.create(name); Bag full; String message; for (int i =0;i< 9;i++) { full = PebbleGame.fullestBag(bagX,bagY,bagZ); takeInitialPebble(full); message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+full.getName(); WriteToFile.write(name,message); System.out.println(message); } while (!done) { if (bagX.sizeOfBag() == 0 && bagA.sizeOfBag() != 0){ bagX.transferPebbles(bagA); } if (bagY.sizeOfBag() == 0 && bagB.sizeOfBag() != 0){ bagY.transferPebbles(bagB); } if (bagZ.sizeOfBag() == 0 && bagC.sizeOfBag() != 0){ bagZ.transferPebbles(bagC); } takePebble(); if (totalValue == 100) { done = true; message = "player"+name+" has won"; WriteToFile.write(name,message); System.out.println(message); this.notifyAll(); } } } } private static Bag fullest; static Bag bagA = new Bag("A","white"); static Bag bagB = new Bag("B","white"); static Bag bagC = new Bag("C","white"); static Bag bagX = new Bag("X","black"); static Bag bagY = new Bag("Y","black"); static Bag bagZ = new Bag("Z","black"); public static void main(String args[]) throws NotEnoughPebblesException, InvalidPlayersNumberException { fillBag(bagX,args[0]); fillBag(bagY,args[1]); fillBag(bagZ,args[2]); AtomicInteger playersNr = new AtomicInteger(Integer.parseInt(args[3])); checkPlayersNumber(playersNr.get()); checkEnoughPebbles(bagX, bagY,bagZ, playersNr.get()); int i; for (i = 1; i <= playersNr.get(); i++) { new Thread(new Player(i)).start(); } WriteToFile.closing(playersNr.get()); } private static void fillBag(Bag bag, String fileName) { try { FileReader fileReader = new FileReader(fileName); BufferedReader in = new BufferedReader(fileReader); String values1 = in.readLine(); String[] xWeights = values1.split(","); for (String xWeight : xWeights) { int weight; weight = Integer.parseInt(xWeight); if (weight <= 0) { System.out.println("Weight value is smaller than 0."); break; } Pebble bagFiller = new Pebble(weight); bag.addPebble(bagFiller); } } catch (FileNotFoundException e) { System.out.println("File not found for Bag: "+bag.getName()); } catch (IOException e) { System.out.println("IO Exception thrown."); } } private static void checkEnoughPebbles(Bag bagx, Bag bagy, Bag bagz, int players) throws NotEnoughPebblesException { int counter; counter = bagx.sizeOfBag()+bagy.sizeOfBag()+bagz.sizeOfBag(); if (counter < ((players*9)+1)) { throw new NotEnoughPebblesException(); } } private static void checkPlayersNumber(int players) throws InvalidPlayersNumberException { if (players < 2) throw new InvalidPlayersNumberException(); } private static Bag fullestBag(Bag bagx, Bag bagy, Bag bagz) { int max = 0; if (max < bagx.sizeOfBag()) { fullest = bagx; max = bagx.sizeOfBag(); } if (max < bagy.sizeOfBag()) { fullest = bagy; max = bagy.sizeOfBag(); } if (max < bagz.sizeOfBag()) { fullest = bagz; } return fullest; } }
nearly finished...we think...
src/Pebbles/PebbleGame.java
nearly finished...we think...
<ide><path>rc/Pebbles/PebbleGame.java <ide> <ide> private final int name; <ide> private LinkedList<Pebble> pebbles; <del> private int totalValue; <del> private int totalPebbles; <del> private volatile boolean done = false; <ide> Random next = new Random(); <ide> <ide> public Player (int name) { <ide> this.name = name; <ide> this.pebbles = new LinkedList<Pebble>(); <del> this.totalValue = 0; <del> this.totalPebbles = 0; <del> } <del> <del> <add> <add> } <ide> <ide> int getTotalValue() { <ide> int total = 0; <ide> return this.name; <ide> } <ide> <del> int getTotalPebbles() { <del> return this.totalPebbles; <del> } <del> <del> Pebble discardPebble() { <del> <del> this.totalPebbles--; <add> synchronized void discardPebble() { <add> <ide> Random random1 = new Random(); <ide> int handIndex = random1.nextInt(9); <del> return this.pebbles.remove(handIndex); <del> <del> } <del> <del> void takeInitialPebble(Bag bag) { <del> <del> this.totalPebbles++; <add> Pebble discarding = this.pebbles.remove(handIndex); <add> Bag parent = this.pebbles.getLast().getParentBag(); <add> if (parent == bagX) { <add> bagA.addPebble(discarding); <add> String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagA"; <add> WriteToFile.write(this.getPlayerName(), message); <add> System.out.println(message); <add> } <add> if (parent == bagY) { <add> bagB.addPebble(discarding); <add> String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagB"; <add> WriteToFile.write(this.getPlayerName(), message); <add> System.out.println(message); <add> } <add> if (parent == bagZ) { <add> bagC.addPebble(discarding); <add> String message = "Player"+this.getPlayerName()+" has discarded a"+discarding.getWeight()+" to bagC"; <add> WriteToFile.write(this.getPlayerName(), message); <add> System.out.println(message); <add> } <add> } <add> <add> synchronized void takeInitialPebble(Bag bag) { <add> <add> <ide> Random random1 = new Random(); <ide> int bagIndex = random1.nextInt(bag.sizeOfBag()-1); <ide> this.pebbles.add(bag.removePebble(bagIndex)); <ide> <ide> } <ide> <del> void takePebble() { <add> synchronized void takePebble() { <ide> String message; <ide> int randomBag = next.nextInt(2); <ide> <ide> if (randomBag == 0){ <ide> if (bagX.sizeOfBag() !=0) { <ide> takeInitialPebble(bagX); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagY.sizeOfBag() !=0){ <ide> takeInitialPebble(bagY); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagZ.sizeOfBag() != 0){ <ide> takeInitialPebble(bagZ); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> if (randomBag == 1){ <ide> if (bagY.sizeOfBag() !=0) { <ide> takeInitialPebble(bagY); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagZ.sizeOfBag() !=0){ <ide> takeInitialPebble(bagZ); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagX.sizeOfBag() != 0){ <ide> takeInitialPebble(bagX); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> if (randomBag == 2){ <ide> if (bagZ.sizeOfBag() !=0) { <ide> takeInitialPebble(bagZ); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagZ.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagX.sizeOfBag() !=0){ <ide> takeInitialPebble(bagX); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagX.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> else { <ide> if (bagY.sizeOfBag() != 0){ <ide> takeInitialPebble(bagY); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+bagY.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> for (int i =0;i< 9;i++) { <ide> full = PebbleGame.fullestBag(bagX,bagY,bagZ); <ide> takeInitialPebble(full); <del> message = "player"+name+" has drown a "+this.pebbles.getLast().getWeight()+" from bag"+full.getName(); <add> message = "player"+name+" has drawn a "+this.pebbles.getLast().getWeight()+" from bag"+full.getName(); <ide> WriteToFile.write(name,message); <ide> System.out.println(message); <ide> } <ide> <del> <del> while (!done) { <add> while (!PebbleGame.done) { <ide> if (bagX.sizeOfBag() == 0 && bagA.sizeOfBag() != 0){ <ide> bagX.transferPebbles(bagA); <ide> } <ide> takePebble(); <ide> <ide> <del> if (totalValue == 100) { <del> done = true; <del> message = "player"+name+" has won"; <del> WriteToFile.write(name,message); <del> System.out.println(message); <del> this.notifyAll(); <del> } <del> } <del> <del> <del> <del> <add> if (this.getTotalValue() == 100) { <add> PebbleGame.done = true; <add> endCredits(this.getPlayerName()); <add> } <add> <add> discardPebble(); <add> } <add> <add> } <add> <add> private synchronized void endCredits(int i){ <add> String message; <add> if (this.getTotalValue() == 100) { <add> PebbleGame.done = true; <add> message = "player"+i+" has won"; <add> WriteToFile.write(i,message); <add> System.out.println(message); <add> <add> } <add> for (int j=1;j<=PebbleGame.playersNr.get(); j++) { <add> message = "player"+j+" has lost, as player"+i+" has won."; <add> if (j != i) { <add> WriteToFile.write(j,message); <add> } <add> <add> } <ide> } <ide> } <ide> <ide> private static Bag fullest; <del> <ide> <ide> static Bag bagA = new Bag("A","white"); <ide> static Bag bagB = new Bag("B","white"); <ide> static Bag bagY = new Bag("Y","black"); <ide> static Bag bagZ = new Bag("Z","black"); <ide> <del> <add> static boolean done = false; <add> static AtomicInteger playersNr; <ide> <ide> public static void main(String args[]) throws NotEnoughPebblesException, InvalidPlayersNumberException { <ide> <ide> fillBag(bagX,args[0]); <ide> fillBag(bagY,args[1]); <ide> fillBag(bagZ,args[2]); <del> AtomicInteger playersNr = new AtomicInteger(Integer.parseInt(args[3])); <add> playersNr = new AtomicInteger(Integer.parseInt(args[3])); <ide> checkPlayersNumber(playersNr.get()); <ide> checkEnoughPebbles(bagX, bagY,bagZ, playersNr.get()); <ide> <ide> break; <ide> } <ide> Pebble bagFiller = new Pebble(weight); <add> bagFiller.setParentBag(bag); <ide> bag.addPebble(bagFiller); <ide> } <ide> <ide> return fullest; <ide> } <ide> <del> <ide> }
JavaScript
mit
4023f140ebe5fc20c3c5ead985207077ed92ce52
0
crisbal/Telegram-Bot-Node,crisbal/Telegram-Bot-Node,crisbal/Node-Telegram-Bot,crisbal/Node-Telegram-Bot,blackdev1l/Telegram-Bot-Node,blackdev1l/Telegram-Bot-Node
// This is called on every message. It can reject a message, or transform it, or let it through. export default class MessageProxy { lastMessage = {} spamInterval = 1000 sniff(message, eventName) { // Types that represent "actual" data and not events const message_types = ["text","audio","document","photo","sticker","video","voice","contact","location"]; // Let events through if (message_types.indexOf(eventName) == -1) return Promise.resolve(message); const now = (new Date()).getTime(); const author = message.from.id; var rejected = false; const lastMessage = this.lastMessage[author]; // The difference is in milliseconds. if (lastMessage && ((now - lastMessage) < this.spamInterval)) rejected = true; this.lastMessage[author] = now; if (rejected) return Promise.reject(); else return Promise.resolve(message); } }
src/Proxy.js
// This is called on every message. It can reject a message, or transform it, or let it through. export default class MessageProxy { lastMessage = {} spamInterval = 1000 sniff(message, eventName) { // Types that represent "actual" data and not events const message_types = ["text","audio","document","photo","sticker","video","voice","contact","location"]; // Let events through if (message_types.indexOf(eventName) == -1) return Promise.resolve(message); const now = (new Date()).getTime(); const author = message.chat.username; var rejected = false; const lastMessage = this.lastMessage[author]; // The difference is in milliseconds. if (lastMessage && ((now - lastMessage) < this.spamInterval)) rejected = true; this.lastMessage[author] = now; if (rejected) return Promise.reject(); else return Promise.resolve(message); } }
Fixed a branch mess
src/Proxy.js
Fixed a branch mess
<ide><path>rc/Proxy.js <ide> if (message_types.indexOf(eventName) == -1) return Promise.resolve(message); <ide> <ide> const now = (new Date()).getTime(); <del> const author = message.chat.username; <add> const author = message.from.id; <ide> var rejected = false; <ide> const lastMessage = this.lastMessage[author]; <ide> // The difference is in milliseconds.
JavaScript
mit
119dcbbc5d3e296e9311ffee3b11fc655c2a757c
0
tvaisanen/embeddedGraphWidget,tvaisanen/embeddedGraphWidget,tvaisanen/embeddedGraphWidget
/** * Created by toni on 19.7.2017. */ define([ "../dependencies/cytoscape", "../configuration/configs", "../components/elementStyles", "../utils/gwClient", "../utils/edgeCategories", "../components/ui", "../utils/cyInitUtils" ], function (cytoscape, configs, elementStyles, gwClient, edgeCategories, ui, cyInitUtils) { /** * Wrapper for cytoscape. * @module graphUtils */ // active graph instance var cy; /** * @function * @name elementHasCategoryClass * @description Check if the given element has bee assigned with existing category style classes. * @param {Object} props * @param {Element} props.element Cytoscape element. * @param {Array} props.categories Array of category names. * @return {Boolean} True if element have assigned classes. */ function elementHasCategoryClass(props) { try { var found = props.categories.some(function (c) { return props.element.hasClass(c); }); return found; } catch (e) { console.groupCollapsed("Exception raised by graphingwikiBrowser.elementHasCategoryClass()"); console.warn(e); console.info("Parameters passed:"); console.info("element:"); console.info(element); console.groupEnd(); } } /** @function * @name addClassToEdge * @description Todo: Redundant? Decide what to do with this. * @param {String} edgeId- Id of the edge. * @param {String} classForEdge - Style category for the edge. */ function addClassToEdge(props, edgeId, classToAdd) { /** * Is this really necessary? Seems like * unnecessary complexity... * * */ // todo: refactor to props var categories = configs.tabs.styles.categories; try { // Get element reference to the edge with edgeId. var edge = props.cy.getElementById(props.edgeId); // Check if the edge does not have a category set. var edgeDoesNotHaveAnyCategory = elementHasCategoryClass(edge, categories); /* * If element edgeId has class '_notype' (= edgeDoesNotHaveCategory) * and current class classToAdd is not '_notype'. Remove the '_notype' * and replace it with the classToAdd. If the edge does not have class * defined yet, set class as classToAdd. Even if it is '_notype' * * Get classes from graphingwikiBrowser.props.categoryStyles. * -> assign each appropriate style for edge */ if (classToAdd != '_notype') { // Therefore, the '_notype' class is removed. if (edge.hasClass('_notype')) { edge.removeClass('_notype'); } edge.addClass(props.category); } else if (!edgeDoesNotHaveAnyCategory) { edge.addClass(props.category); } // Add the class for the edge. } catch (e) { console.groupCollapsed("Exception raised by addClassToEdge()"); console.info("Parameters passed:"); console.info(props); console.warn(e); console.groupEnd(); } } /** @function * @name setAndRunLayout * @description Update cytoscape graph layout. * @param {Object} props * @param {Object} props.cy cytoscape instance * @param {String} props.layout layout name. * @return {Boolean} True if no errors. */ function setAndRunLayout(props) { try { var layoutStyle = props.layout || "circle"; var layout = props.cy.makeLayout({name: layoutStyle}); //var layout = cy.makeLayout({name: "cola"}); layout.run(); return true; } catch (e) { console.group("Exception raised by graphUtils.setAndRunLayout()"); console.debug("props:"); console.debug(props); console.warn(e); console.groupEnd(); return false; } } /** @function * @name nodeIdAvailable * @description Check if a node of given id is already defined in the graph. * @param {String} nodeId- Id of node. * @return {Boolean} True if id is available for use, else False. */ function nodeIdAvailable(props, nodeId, cy) { return !props.cy.getElementById(props.nodeId).isNode(); } /** @function * @name edgeExists * @description Check if a node of given id is already defined in the graph. * @param {Objec} props * @param {String} props.cy Cytoscape instance. * @param {String} props.edgeId Id of edge element. * @return {Boolean} True if edge already defined, else False. */ function edgeExists(props) { return props.cy.getElementById(props.edgeId).isEdge(); } /** * @function * @name expandNode * @description Chain of events to trigger when node needs to be expanded * @param {Object} props * @param {String} props.nodeId Id of the node to expand. * @param {Object} props.cy Cytoscape instance. * */ function expandNode(props) { console.log(props); try { var gw = props.gwClient; var nodeId = props.nodeId; cy = props.cy; console.debug("expandNode()"); console.debug(props); //Get data for the clicked node. var nodePromise = gw.getNodeData(nodeId); nodePromise.then(function (response) { return response.json(); }).then(function (json) { /* * node = { * in: Object, * out: Object, * meta: Object * } * */ var node = json.data; console.debug("expandNode().node"); console.debug(node); try { // If node has outgoing edges refresh the categories var nodeHasOutgoingEdges = (node.out != 'undefined'); var newCategoriesOut = []; if (nodeHasOutgoingEdges) { try { newCategoriesOut = Object.keys(node.out); var categoriesToUpdate = props.edgeCategories.get(); props.edgeCategories.update({ newCategories: newCategoriesOut }); } catch (e) { console.groupCollapsed("Exception raised while updating categories in expandNode()"); console.warn(e); console.info("%cNode", "color:red;"); console.info(node); console.groupEnd(); } } // Iterate the outgoing edge categories. try { newCategoriesOut.forEach(function (category) { // get list of nodes where the clicked node is connected t var nodesConnectedTo = node.out[category]; // for each connected node create a new edge createEdgesToNodes({ sourceNodeId: nodeId, nodesToCreateEdges: nodesConnectedTo, category: category, cy: cy, configs: props.configs, elementStyles: props.elementStyles }); }); } catch (e) { console.group("Exception raised by graphUtilsExpandNode()"); console.warn(e); console.groupEnd(); } var newCategoriesIn = Object.keys(node.in); categoriesToUpdate = edgeCategories.get(); edgeCategories.update({ newCategories: newCategoriesIn }); // Iterate the incoming edge categories. newCategoriesIn.forEach(function (category) { var nodesConnectedTo = node.in[category]; createEdgesFromNodes({ targetNodeId: nodeId, nodesFromCreateEdges: nodesConnectedTo, category: category, cy: cy }); }); } catch (e) { console.groupCollapsed("Exception raised by expandNode()"); console.warn(e); console.groupEnd(); } setAndRunLayout(props); } ); } catch (e) { console.group("Exception raised by graphUtils.expandNode()"); console.warn(e); console.groupEnd(); console.groupEnd(); } } /** * @function * @name createEdgesToNodes * @description Create edges from given node to every node of given array. Nodes are created if do not exist. * @param {Object} props * @param {String} props.sourceNodeId source node ID * @param {Array} props.nodesToCreateEdges target node IDs * @param {String} props.category category for edges * @param {Object} props.cy Cytoscape instance */ function createEdgesToNodes(props) { /* * Iterate through the nodesToCreateEdges array and add * edges between the source node and target nodes. * If nodes do not exist, create them and add to cy.elements. */ props.nodesToCreateEdges.forEach(function (targetNodeId) { try { if (targetNodeId === 'undefined') { console.warn("graphUtils.createEdgesToNodes() is trying to create edge to undefined node!"); console.debug(props); } else { createNodesAndEdgeBetween({ sourceNodeId: props.sourceNodeId, targetNodeId: targetNodeId, category: props.category, cy: props.cy, elementStyles: props.elementStyles }); } } catch (e) { console.groupCollapsed("Exception with createEdgesToNodes()"); console.info("Parameters passed:"); console.info("sourceNodeId: " + props.sourceNodeId); console.info("nodesToCreateEdges: " + props.nodesToCreateEdges); console.info("category: " + props.category); console.warn(e); console.groupEnd(); } }); } /** * @function * @name createEdgeId * @description Generate edge ID from source and target node IDs. * @param {Object} props * @param {String} props.sourceNodeId source node ID * @param {Array} props.nodesToCreateEdges target node IDs * @param {String} props.category category for edges * @param {Object} props.cy Cytoscape instance */ function createEdgeId(props) { var sourceType = typeof props.sourceNodeId; var targetType = typeof props.targetNodeId; if (sourceType === 'undefined' || targetType === 'undefined') { console.debug("Exception raised by createEdgeId()"); console.debug("called by: " + arguments.callee.caller.name); throw TypeError('createEdgeId() called with undefined node id'); } else { return props.sourceNodeId + "_to_" + props.targetNodeId; } } /** @function createNewEdge * Description * @param {String} sourceId - Id of the source node. * @param {String} targetId - Id of the target node. * @param {String} classForEdge - Selector for assigning style. * @param {Object} cy - Cytoscape instance. * @return {Object} The new edge element. */ function createNewEdge(props) { try { var edgeId = createEdgeId({ sourceNodeId: props.sourceNodeId, targetNodeID: props.targetNodeId }); // Create new edge. var newEdge = { group: 'edges', data: { id: edgeId, source: props.sourceNodeId, target: props.targetNodeId } }; // If edge is already defined, return the existing one. if (edgeExists({edgeId: edgeId, cy: props.cy})) { return props.cy.getElementById(edgeId); } else { props.cy.add(newEdge); var edge = props.cy.getElementById(edgeId); var categoryExists = elementStyles.categoryExists(props.category); // console.debug(elementStyles); // console.debug(categoryExists); var classesToAdd = elementStyles.getStyle(props.category); if (!classesToAdd) { console.debug('Add generic styles'); classesToAdd = elementStyles.getStyle(); } else { // console.debug('Add ' + props.category + ' styles.'); } // Add the new edge to cy.elements. // console.debug(classesToAdd); classesToAdd.forEach(function (styleClass) { //console.debug('add style: ' + styleClass); edge.addClass(styleClass); }); return edge; } } catch (e) { console.groupCollapsed("Exception raised by createNewEdge()"); console.debug("called by: " + arguments.callee.caller.name); console.info("Parameters passed:"); console.info(props); console.warn(e); console.groupEnd(); } } /** @function createNewNode * Create new node and add it to the given cytoscape instance. * @param {string} id - ID for the node. * @param {Object} cy - Cytoscape instance * */ function createNewNode(id, cy) { if (typeof id === 'undefined') { console.debug("Exception raised by createNewNode()"); throw TypeError("createNewNode() called with undefined id"); } try { var newNode = { group: 'nodes', data: { id: id } }; // after saving page to moin // Can not create element with invalid string ID `` if (nodeIdAvailable({nodeId: id, cy: cy})) { cy.add(newNode); return true; } else { return false; } } catch (e) { console.groupCollapsed("Exception raised by graphingwikiBrowser.createNewNode(id)"); console.warn(e); console.debug("Parameters passed:"); console.debug("id:"); console.debug(id); console.groupEnd(); console.debug('returning false from second catch'); return false; } } /** @function createNodesAndEdgeBetween * Creates edge between two nodes and if the nodes do not * exist, these are also created. * @param {String} sourceNodeId - Id of the source node. * @param {String} targetNodeId - Id of the target node. * @param {String} classForEdge - Style category for the edge. * @param {Object} cy - Cytoscape instance. */ function createNodesAndEdgeBetween(props) { try { // If nodes do not exist, create them. // nodeIdAvailable: true === node do not exist. nodeIdAvailable({nodeId: props.sourceNodeId, cy: props.cy}) ? createNewNode(props.sourceNodeId, props.cy) : null; nodeIdAvailable({nodeId: props.targetNodeId, cy: props.cy}) ? createNewNode(props.targetNodeId, props.cy) : null; // createNewEdge checks if the edge already exists. createNewEdge(props); var edgeId = createEdgeId({ sourceNodeId: props.sourceNodeId, targetNodeId: props.targetNodeId }); /* console.group("Debugging edge creation!"); console.debug("sourceNodeId: " + props.sourceNodeId); console.debug("sourceNodeId: " + props.targetNodeId); if (typeof props.targetNodeId === 'undefined'){ console.log("%cHere's the problem", "color:red;"); console.debug(props); } console.debug(props); console.debug(edgeId); console.groupEnd(); */ addClassToEdge({ edgeId: edgeId, category: props.category, cy: props.cy }); } catch (e) { console.groupCollapsed("Exception with createNodesAndEdgeBetween()"); console.info("Parameters passed:"); console.debug(props); console.warn(e); console.groupEnd(); } } /** @function createEdgesFromNodes * Description * @param {String} sourceNodeId- Id of the source node. * @param {Array} nodesToCreateEdges - Array of nodes?. * @param {String} category - Category for edges. */ function createEdgesFromNodes(props) { /* * Iterate through the nodesFromCreateEdges array and add * edges between the source node and target nodes. * If nodes do not exist, create them and add to cy.elements. */ props.nodesFromCreateEdges.forEach(function (sourceNodeId) { props.sourceNodeId = sourceNodeId; createNodesAndEdgeBetween(props); }); } /** * * @param evt */ function bindExpandNode(evt) { console.debug('debugging bindExpandNodE()'); try { var node = evt.target; var nodeId = node.id(); expandNode({ nodeId: nodeId, cy: cy, gwClient: gwClient, edgeCategories: edgeCategories, elementStyles: elementStyles }); ui.updateTabs({ cy: cy }); } catch (e) { console.group("Exception raised by graphUtils.bindExpandNode()"); console.warn(e); console.debug("props:"); console.debug(evt); console.groupEnd(); } } function testCy(containerElement) { return cytoscape({ container: containerElement, elements: [{group: 'nodes', data: {id: 'personA'}}], style: [ // the stylesheet for the graph { selector: 'node', style: { 'background-color': '#6490af', 'size': '40', 'label': 'data(id)', 'content': 'data(id)', 'text-valign': 'center', 'color': 'white', 'text-outline-width': 1, 'text-outline-color': '#000000', 'background-color': '#9a9a9a' } }, { selector: 'node.highlight', style: { 'background-color': '#c50004', } }, { selector: 'node.hover-on', style: { 'background-color': '#00ff14', } }, { selector: 'edge', style: { 'line-color': '#ccc', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'overlay-padding': 1 } }, { selector: 'edge.mouse-over', style: {label: 'category'} }, // Todo: generate these from config! priority: low {selector: 'edge.line-style-solid', style: {'line-style': 'solid'}}, {selector: 'edge.line-style-dotted', style: {'line-style': 'dotted'}}, {selector: 'edge.line-style-dashed', style: {'line-style': 'dashed'}}, {selector: 'edge.line-width-0', style: {'line-width': 0}}, {selector: 'edge.line-width-1', style: {'line-width': 1}}, {selector: 'edge.line-width-2', style: {'line-width': 2}}, {selector: 'edge.line-width-3', style: {'line-width': 3}}, {selector: 'edge.line-width-4', style: {'line-width': 4}}, {selector: 'edge.line-width-5', style: {'line-width': 5}}, {selector: 'edge.line-width-6', style: {'line-width': 6}}, {selector: 'edge.line-width-7', style: {'line-width': 7}}, {selector: 'edge.line-width-8', style: {'line-width': 8}}, {selector: 'edge.line-width-9', style: {'line-width': 9}}, {selector: 'edge.line-width-10', style: {'line-width': 10}}, {selector: 'edge.line-width-11', style: {'line-width': 11}}, {selector: 'edge.line-width-12', style: {'line-width': 12}}, {selector: 'edge.line-width-13', style: {'line-width': 13}}, {selector: 'edge.line-width-14', style: {'line-width': 14}}, {selector: 'edge.line-width-15', style: {'line-width': 15}}, {selector: 'edge.line-width-16', style: {'line-width': 16}}, {selector: 'edge.line-width-17', style: {'line-width': 17}}, {selector: 'edge.line-width-18', style: {'line-width': 18}}, {selector: 'edge.line-width-19', style: {'line-width': 19}}, {selector: 'edge.line-width-20', style: {'line-width': 20}}, {selector: 'edge.line-width-21', style: {'line-width': 21}}, {selector: 'edge.line-width-22', style: {'line-width': 22}}, {selector: 'edge.line-width-23', style: {'line-width': 23}}, {selector: 'edge.line-width-24', style: {'line-width': 24}}, {selector: 'edge.line-width-25', style: {'line-width': 25}}, {selector: 'edge.line-width-26', style: {'line-width': 26}}, {selector: 'edge.line-width-27', style: {'line-width': 27}}, {selector: 'edge.line-width-28', style: {'line-width': 28}}, {selector: 'edge.line-width-29', style: {'line-width': 29}}, {selector: 'edge.line-width-30', style: {'width': 30}}, {selector: 'edge.arrow-shape-tee', style: {'target-arrow-shape': 'tee'}}, {selector: 'edge.arrow-shape-triangle', style: {'target-arrow-shape': 'triangle'}}, {selector: 'edge.arrow-shape-triangle-tee', style: {'target-arrow-shape': 'triangle-tee'}}, {selector: 'edge.arrow-shape-triangle-cross', style: {'target-arrow-shape': 'triangle-cross'}}, { selector: 'edge.arrow-shape-triangle-backcurve', style: {'target-arrow-shape': 'triangle-backcurve'} }, {selector: 'edge.arrow-shape-square', style: {'target-arrow-shape': 'square'}}, {selector: 'edge.arrow-shape-circle', style: {'target-arrow-shape': 'circle'}}, {selector: 'edge.arrow-shape-diamond', style: {'target-arrow-shape': 'diamond'}}, {selector: 'edge.arrow-shape-none', style: {'target-arrow-shape': 'none'}}, {selector: 'edge.line-color-grey', style: {'line-color': 'grey', 'arrow-color': 'grey'}}, {selector: 'edge.line-color-black', style: {'line-color': 'black', 'arrow-color': 'black'}}, {selector: 'edge.line-color-red', style: {'line-color': 'red', 'arrow-color': 'red'}}, {selector: 'edge.line-color-green', style: {'line-color': 'green', 'arrow-color': 'green'}}, {selector: 'edge.line-color-orange', style: {'line-color': 'orange', 'arrow-color': 'orange'}}, {selector: 'edge.line-color-yellow', style: {'line-color': 'yellow', 'arrow-color': 'yellow'}}, {selector: 'edge.line-color-cyan', style: {'line-color': 'cyan', 'arrow-color': 'cyan'}}, {selector: 'edge.line-color-blue', style: {'line-color': 'blue', 'arrow-color': 'blue'}}, { selector: 'edge.hover-on', style: { 'width': 5, 'line-color': '#cc7500', 'line-style': 'dashed', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', } }, { selector: 'edge.highlight', style: { 'width': 5, 'line-color': '#cc7500', 'line-style': 'dashed', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', } } ] }); } function createNewCy(props) { try { var style = props.style || configs.style; cy = cytoscape({ container: document.getElementById(configs.graphContainerId), elements: props.data.elements, style: props.data.style }); cy.on('tap', 'node', bindExpandNode); return cy; } catch (e) { console.group("Exception raised by graphUtils.createNewCy()"); console.debug("props:"); console.debug(props); console.warn(e); console.groupEnd(); } } /** @function initCytoscape * Description * @param {Object} variable - Desc. * @return {Type} desc. */ function initCytoscape(props) { /* * Return <div id="cy"> * Initialize empty Cytoscape graph * * */ cyInitUtils.init(); _cy = testCy(props.container); _cy.on('tap', 'node', bindExpandNode); // initialize the context menu plugin // cy.contextMenus(initCyContextMenu(cy)); cy = _cy; return cy; } return { createEdgesFromNodes: createEdgesFromNodes, createEdgesToNodes: createEdgesToNodes, createEdgeId: createEdgeId, createNewCy: createNewCy, createNewEdge: createNewEdge, createNewNode: createNewNode, createNodesAndEdgeBetween: createNodesAndEdgeBetween, edgeExists: edgeExists, elementHasCategoryClass: elementHasCategoryClass, expandNode: expandNode, cy: function () { return cy; }, nodeIdAvailable: nodeIdAvailable, initCy: initCytoscape, testCy: testCy } });
proto_v0.04/js/utils/graphUtils.js
/** * Created by toni on 19.7.2017. */ define([ "../dependencies/cytoscape", "../configuration/configs", "../components/elementStyles", "../utils/gwClient", "../utils/edgeCategories", "../components/ui", "../utils/cyInitUtils" ], function (cytoscape, configs, elementStyles, gwClient, edgeCategories, ui, cyInitUtils) { /** * Wrapper for cytoscape. * @module graphUtils */ // active graph instance var cy; /** * @function * @name elementHasCategoryClass * @description Check if the given element has bee assigned with existing category style classes. * @param {Object} props * @param {Element} props.element Cytoscape element. * @param {Array} props.categories Array of category names. * @return {Boolean} True if element have assigned classes. */ function elementHasCategoryClass(props) { try { var found = props.categories.some(function (c) { return props.element.hasClass(c); }); return found; } catch (e) { console.groupCollapsed("Exception raised by graphingwikiBrowser.elementHasCategoryClass()"); console.warn(e); console.info("Parameters passed:"); console.info("element:"); console.info(element); console.groupEnd(); } } /** @function * @name addClassToEdge * @description Todo: Redundant? Decide what to do with this. * @param {String} edgeId- Id of the edge. * @param {String} classForEdge - Style category for the edge. */ function addClassToEdge(props, edgeId, classToAdd) { /** * Is this really necessary? Seems like * unnecessary complexity... * * */ // todo: refactor to props var categories = configs.tabs.styles.categories; try { // Get element reference to the edge with edgeId. var edge = props.cy.getElementById(props.edgeId); // Check if the edge does not have a category set. var edgeDoesNotHaveAnyCategory = elementHasCategoryClass(edge, categories); /* * If element edgeId has class '_notype' (= edgeDoesNotHaveCategory) * and current class classToAdd is not '_notype'. Remove the '_notype' * and replace it with the classToAdd. If the edge does not have class * defined yet, set class as classToAdd. Even if it is '_notype' * * Get classes from graphingwikiBrowser.props.categoryStyles. * -> assign each appropriate style for edge */ if (classToAdd != '_notype') { // Therefore, the '_notype' class is removed. if (edge.hasClass('_notype')) { edge.removeClass('_notype'); } edge.addClass(props.category); } else if (!edgeDoesNotHaveAnyCategory) { edge.addClass(props.category); } // Add the class for the edge. } catch (e) { console.groupCollapsed("Exception raised by addClassToEdge()"); console.info("Parameters passed:"); console.info(props); console.warn(e); console.groupEnd(); } } /** @function * @name setAndRunLayout * @description Update cytoscape graph layout. * @param {Object} props * @param {Object} props.cy cytoscape instance * @param {String} props.layout layout name. * @return {Boolean} True if no errors. */ function setAndRunLayout(props) { try { var layoutStyle = props.layout || "circle"; var layout = props.cy.makeLayout({name: layoutStyle}); //var layout = cy.makeLayout({name: "cola"}); layout.run(); return true; } catch (e) { console.group("Exception raised by graphUtils.setAndRunLayout()"); console.debug("props:"); console.debug(props); console.warn(e); console.groupEnd(); return false; } } /** @function * @name nodeIdAvailable * @description Check if a node of given id is already defined in the graph. * @param {String} nodeId- Id of node. * @return {Boolean} True if id is available for use, else False. */ function nodeIdAvailable(props, nodeId, cy) { return !props.cy.getElementById(props.nodeId).isNode(); } /** @function * @name edgeExists * @description Check if a node of given id is already defined in the graph. * @param {Objec} props * @param {String} props.cy Cytoscape instance. * @param {String} props.edgeId Id of edge element. * @return {Boolean} True if edge already defined, else False. */ function edgeExists(props) { return props.cy.getElementById(props.edgeId).isEdge(); } /** * @function * @name expandNode * @description Chain of events to trigger when node needs to be expanded * @param {Object} props * @param {String} props.nodeId Id of the node to expand. * @param {Object} props.cy Cytoscape instance. * */ function expandNode(props) { console.log(props); try { var gw = props.gwClient; var nodeId = props.nodeId; cy = props.cy; console.debug("expandNode()"); console.debug(props); //Get data for the clicked node. var nodePromise = gw.getNodeData(nodeId); nodePromise.then(function (response) { return response.json(); }).then(function (json) { /* * node = { * in: Object, * out: Object, * meta: Object * } * */ var node = json.data; console.debug("expandNode().node"); console.debug(node); try { // If node has outgoing edges refresh the categories var nodeHasOutgoingEdges = (node.out != 'undefined'); var newCategoriesOut = []; if (nodeHasOutgoingEdges) { try { newCategoriesOut = Object.keys(node.out); var categoriesToUpdate = props.edgeCategories.get(); props.edgeCategories.update({ newCategories: newCategoriesOut }); } catch (e) { console.groupCollapsed("Exception raised while updating categories in expandNode()"); console.warn(e); console.info("%cNode", "color:red;"); console.info(node); console.groupEnd(); } } // Iterate the outgoing edge categories. try { newCategoriesOut.forEach(function (category) { // get list of nodes where the clicked node is connected t var nodesConnectedTo = node.out[category]; // for each connected node create a new edge createEdgesToNodes({ sourceNodeId: nodeId, nodesToCreateEdges: nodesConnectedTo, category: category, cy: cy, configs: props.configs, elementStyles: props.elementStyles }); }); } catch (e) { console.group("Exception raised by graphUtilsExpandNode()"); console.warn(e); console.groupEnd(); } var newCategoriesIn = Object.keys(node.in); categoriesToUpdate = edgeCategories.get(); edgeCategories.update({ newCategories: newCategoriesIn }); // Iterate the incoming edge categories. newCategoriesIn.forEach(function (category) { var nodesConnectedTo = node.in[category]; createEdgesFromNodes({ targetNodeId: nodeId, nodesFromCreateEdges: nodesConnectedTo, category: category, cy: cy }); }); } catch (e) { console.groupCollapsed("Exception raised by expandNode()"); console.warn(e); console.groupEnd(); } setAndRunLayout(props); } ); } catch (e) { console.group("Exception raised by graphUtils.expandNode()"); console.warn(e); console.groupEnd(); console.groupEnd(); } } /** * @function * @name createEdgesToNodes * @description Create edges from given node to every node of given array. Nodes are created if do not exist. * @param {Object} props * @param {String} props.sourceNodeId source node ID * @param {Array} props.nodesToCreateEdges target node IDs * @param {String} props.category category for edges * @param {Object} props.cy Cytoscape instance */ function createEdgesToNodes(props) { /* * Iterate through the nodesToCreateEdges array and add * edges between the source node and target nodes. * If nodes do not exist, create them and add to cy.elements. */ props.nodesToCreateEdges.forEach(function (targetNodeId) { try { if (targetNodeId === 'undefined') { console.warn("graphUtils.createEdgesToNodes() is trying to create edge to undefined node!"); console.debug(props); } else { createNodesAndEdgeBetween({ sourceNodeId: props.sourceNodeId, targetNodeId: targetNodeId, category: props.category, cy: props.cy, elementStyles: props.elementStyles }); } } catch (e) { console.groupCollapsed("Exception with createEdgesToNodes()"); console.info("Parameters passed:"); console.info("sourceNodeId: " + props.sourceNodeId); console.info("nodesToCreateEdges: " + props.nodesToCreateEdges); console.info("category: " + props.category); console.warn(e); console.groupEnd(); } }); } /** * @function * @name createEdgeId * @description Generate edge ID from source and target node IDs. * @param {Object} props * @param {String} props.sourceNodeId source node ID * @param {Array} props.nodesToCreateEdges target node IDs * @param {String} props.category category for edges * @param {Object} props.cy Cytoscape instance */ function createEdgeId(props) { var sourceType = typeof props.sourceNodeId; var targetType = typeof props.targetNodeId; if (sourceType === 'undefined' || targetType === 'undefined') { console.debug("Exception raised by createEdgeId()"); console.debug("called by: " + arguments.callee.caller.name); throw TypeError('createEdgeId() called with undefined node id'); } else { return props.sourceNodeId + "_to_" + props.targetNodeId; } } /** @function createNewEdge * Description * @param {String} sourceId - Id of the source node. * @param {String} targetId - Id of the target node. * @param {String} classForEdge - Selector for assigning style. * @param {Object} cy - Cytoscape instance. * @return {Object} The new edge element. */ function createNewEdge(props) { try { var edgeId = createEdgeId({ sourceNodeId: props.sourceNodeId, targetNodeID: props.targetNodeId }); // Create new edge. var newEdge = { group: 'edges', data: { id: edgeId, source: props.sourceNodeId, target: props.targetNodeId } }; // If edge is already defined, return the existing one. if (edgeExists({edgeId: edgeId, cy: props.cy})) { return props.cy.getElementById(edgeId); } else { props.cy.add(newEdge); var edge = props.cy.getElementById(edgeId); var categoryExists = elementStyles.categoryExists(props.category); // console.debug(elementStyles); // console.debug(categoryExists); var classesToAdd = elementStyles.getStyle(props.category); if (!classesToAdd) { console.debug('Add generic styles'); classesToAdd = elementStyles.getStyle(); } else { // console.debug('Add ' + props.category + ' styles.'); } // Add the new edge to cy.elements. // console.debug(classesToAdd); classesToAdd.forEach(function (styleClass) { //console.debug('add style: ' + styleClass); edge.addClass(styleClass); }); return edge; } } catch (e) { console.groupCollapsed("Exception raised by createNewEdge()"); console.debug("called by: " + arguments.callee.caller.name); console.info("Parameters passed:"); console.info(props); console.warn(e); console.groupEnd(); } } /** @function createNewNode * Create new node and add it to the given cytoscape instance. * @param {string} id - ID for the node. * @param {Object} cy - Cytoscape instance * */ function createNewNode(id, cy) { if (typeof id === 'undefined') { console.debug("Exception raised by createNewNode()"); throw TypeError("createNewNode() called with undefined id"); } try { var newNode = { group: 'nodes', data: { id: id } }; // after saving page to moin // Can not create element with invalid string ID `` if (nodeIdAvailable({nodeId: id, cy: cy})) { cy.add(newNode); return true; } else { return false; } } catch (e) { console.groupCollapsed("Exception raised by graphingwikiBrowser.createNewNode(id)"); console.warn(e); console.debug("Parameters passed:"); console.debug("id:"); console.debug(id); console.groupEnd(); console.debug('returning false from second catch'); return false; } } /** @function createNodesAndEdgeBetween * Creates edge between two nodes and if the nodes do not * exist, these are also created. * @param {String} sourceNodeId - Id of the source node. * @param {String} targetNodeId - Id of the target node. * @param {String} classForEdge - Style category for the edge. * @param {Object} cy - Cytoscape instance. */ function createNodesAndEdgeBetween(props) { try { // If nodes do not exist, create them. // nodeIdAvailable: true === node do not exist. nodeIdAvailable({nodeId: props.sourceNodeId, cy: props.cy}) ? createNewNode(props.sourceNodeId, props.cy) : null; nodeIdAvailable({nodeId: props.targetNodeId, cy: props.cy}) ? createNewNode(props.targetNodeId, props.cy) : null; // createNewEdge checks if the edge already exists. createNewEdge(props); var edgeId = createEdgeId({ sourceNodeId: props.sourceNodeId, targetNodeId: props.targetNodeId }); /* console.group("Debugging edge creation!"); console.debug("sourceNodeId: " + props.sourceNodeId); console.debug("sourceNodeId: " + props.targetNodeId); if (typeof props.targetNodeId === 'undefined'){ console.log("%cHere's the problem", "color:red;"); console.debug(props); } console.debug(props); console.debug(edgeId); console.groupEnd(); */ addClassToEdge({ edgeId: edgeId, category: props.category, cy: props.cy }); } catch (e) { console.groupCollapsed("Exception with createNodesAndEdgeBetween()"); console.info("Parameters passed:"); console.debug(props); console.warn(e); console.groupEnd(); } } /** @function createEdgesFromNodes * Description * @param {String} sourceNodeId- Id of the source node. * @param {Array} nodesToCreateEdges - Array of nodes?. * @param {String} category - Category for edges. */ function createEdgesFromNodes(props) { /* * Iterate through the nodesFromCreateEdges array and add * edges between the source node and target nodes. * If nodes do not exist, create them and add to cy.elements. */ props.nodesFromCreateEdges.forEach(function (sourceNodeId) { props.sourceNodeId = sourceNodeId; createNodesAndEdgeBetween(props); }); } /** * * @param evt */ function bindExpandNode(evt) { console.debug('debugging bindExpandNodE()'); try { var node = evt.target; var nodeId = node.id(); expandNode({ nodeId: nodeId, cy: cy, gwClient: gwClient, edgeCategories: edgeCategories, elementStyles: elementStyles }); ui.updateTabs({ cy: cy }); } catch (e) { console.group("Exception raised by graphUtils.bindExpandNode()"); console.warn(e); console.debug("props:"); console.debug(evt); console.groupEnd(); } } function testCy(containerElement) { return cytoscape({ container: containerElement, elements: [{group: 'nodes', data: {id: 'personA'}}], style: [ // the stylesheet for the graph { selector: 'node', style: { 'background-color': '#6490af', 'size': '40', 'label': 'data(id)', 'content': 'data(id)', 'text-valign': 'center', 'color': 'white', 'text-outline-width': 1, 'text-outline-color': '#000000', 'background-color': '#9a9a9a' } }, { selector: 'node.highlight', style: { 'background-color': '#c50004', } }, { selector: 'node.hover-on', style: { 'background-color': '#00ff14', } }, { selector: 'edge', style: { 'line-color': '#ccc', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'overlay-padding': 1 } }, { selector: 'edge.mouse-over', style: {label: 'category'} }, // Todo: generate these from config! priority: low {selector: 'edge.line-style-solid', style: {'line-style': 'solid'}}, {selector: 'edge.line-style-dotted', style: {'line-style': 'dotted'}}, {selector: 'edge.line-style-dashed', style: {'line-style': 'dashed'}}, {selector: 'edge.line-width-0', style: {'line-width': 0}}, {selector: 'edge.line-width-1', style: {'line-width': 1}}, {selector: 'edge.line-width-2', style: {'line-width': 2}}, {selector: 'edge.line-width-3', style: {'line-width': 3}}, {selector: 'edge.line-width-4', style: {'line-width': 4}}, {selector: 'edge.line-width-5', style: {'line-width': 5}}, {selector: 'edge.line-width-6', style: {'line-width': 6}}, {selector: 'edge.line-width-7', style: {'line-width': 7}}, {selector: 'edge.line-width-8', style: {'line-width': 8}}, {selector: 'edge.line-width-9', style: {'line-width': 9}}, {selector: 'edge.line-width-10', style: {'line-width': 10}}, {selector: 'edge.line-width-11', style: {'line-width': 11}}, {selector: 'edge.line-width-12', style: {'line-width': 12}}, {selector: 'edge.line-width-13', style: {'line-width': 13}}, {selector: 'edge.line-width-14', style: {'line-width': 14}}, {selector: 'edge.line-width-15', style: {'line-width': 15}}, {selector: 'edge.line-width-16', style: {'line-width': 16}}, {selector: 'edge.line-width-17', style: {'line-width': 17}}, {selector: 'edge.line-width-18', style: {'line-width': 18}}, {selector: 'edge.line-width-19', style: {'line-width': 19}}, {selector: 'edge.line-width-20', style: {'line-width': 20}}, {selector: 'edge.line-width-21', style: {'line-width': 21}}, {selector: 'edge.line-width-22', style: {'line-width': 22}}, {selector: 'edge.line-width-23', style: {'line-width': 23}}, {selector: 'edge.line-width-24', style: {'line-width': 24}}, {selector: 'edge.line-width-25', style: {'line-width': 25}}, {selector: 'edge.line-width-26', style: {'line-width': 26}}, {selector: 'edge.line-width-27', style: {'line-width': 27}}, {selector: 'edge.line-width-28', style: {'line-width': 28}}, {selector: 'edge.line-width-29', style: {'line-width': 29}}, {selector: 'edge.line-width-30', style: {'width': 30}}, {selector: 'edge.arrow-shape-tee', style: {'target-arrow-shape': 'tee'}}, {selector: 'edge.arrow-shape-triangle', style: {'target-arrow-shape': 'triangle'}}, {selector: 'edge.arrow-shape-triangle-tee', style: {'target-arrow-shape': 'triangle-tee'}}, {selector: 'edge.arrow-shape-triangle-cross', style: {'target-arrow-shape': 'triangle-cross'}}, { selector: 'edge.arrow-shape-triangle-backcurve', style: {'target-arrow-shape': 'triangle-backcurve'} }, {selector: 'edge.arrow-shape-square', style: {'target-arrow-shape': 'square'}}, {selector: 'edge.arrow-shape-circle', style: {'target-arrow-shape': 'circle'}}, {selector: 'edge.arrow-shape-diamond', style: {'target-arrow-shape': 'diamond'}}, {selector: 'edge.arrow-shape-none', style: {'target-arrow-shape': 'none'}}, {selector: 'edge.line-color-grey', style: {'line-color': 'grey', 'arrow-color': 'grey'}}, {selector: 'edge.line-color-black', style: {'line-color': 'black', 'arrow-color': 'black'}}, {selector: 'edge.line-color-red', style: {'line-color': 'red', 'arrow-color': 'red'}}, {selector: 'edge.line-color-green', style: {'line-color': 'green', 'arrow-color': 'green'}}, {selector: 'edge.line-color-orange', style: {'line-color': 'orange', 'arrow-color': 'orange'}}, {selector: 'edge.line-color-yellow', style: {'line-color': 'yellow', 'arrow-color': 'yellow'}}, {selector: 'edge.line-color-cyan', style: {'line-color': 'cyan', 'arrow-color': 'cyan'}}, {selector: 'edge.line-color-blue', style: {'line-color': 'blue', 'arrow-color': 'blue'}}, { selector: 'edge.hover-on', style: { 'width': 5, 'line-color': '#cc7500', 'line-style': 'dashed', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', } }, { selector: 'edge.highlight', style: { 'width': 5, 'line-color': '#cc7500', 'line-style': 'dashed', 'target-arrow-color': '#000000', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', } } ] }); } function createNewCy(props) { try { var style = props.style || configs.style; cy = cytoscape({ container: document.getElementById(configs.graphContainerId), elements: props.data.elements, style: props.data.style }); console.debug(cy); console.debug(props); return cy; } catch (e) { console.group("Exception raised by graphUtils.createNewCy()"); console.debug("props:"); console.debug(props); console.warn(e); console.groupEnd(); } } /** @function initCytoscape * Description * @param {Object} variable - Desc. * @return {Type} desc. */ function initCytoscape(props) { /* * Return <div id="cy"> * Initialize empty Cytoscape graph * * */ cyInitUtils.init(); _cy = testCy(props.container); _cy.on('tap', 'node', bindExpandNode); // initialize the context menu plugin // cy.contextMenus(initCyContextMenu(cy)); cy = _cy; return cy; } return { createEdgesFromNodes: createEdgesFromNodes, createEdgesToNodes: createEdgesToNodes, createEdgeId: createEdgeId, createNewCy: createNewCy, createNewEdge: createNewEdge, createNewNode: createNewNode, createNodesAndEdgeBetween: createNodesAndEdgeBetween, edgeExists: edgeExists, elementHasCategoryClass: elementHasCategoryClass, expandNode: expandNode, cy: function () { return cy; }, nodeIdAvailable: nodeIdAvailable, initCy: initCytoscape, testCy: testCy } });
bind expand node to new graph
proto_v0.04/js/utils/graphUtils.js
bind expand node to new graph
<ide><path>roto_v0.04/js/utils/graphUtils.js <ide> elements: props.data.elements, <ide> style: props.data.style <ide> }); <del> console.debug(cy); <del> console.debug(props); <add> <add> cy.on('tap', 'node', bindExpandNode); <ide> return cy; <ide> } catch (e) { <ide> console.group("Exception raised by graphUtils.createNewCy()");
Java
apache-2.0
efd805fdb709cfcd11af7b95930b2f838fa65ec7
0
lingfliu/dv_omnicontrol_android,lingfliu/dv_omnicontrol_android
package cn.diaovision.omnicontrol.core.message.conference; import java.io.Serializable; import cn.diaovision.omnicontrol.util.ByteUtils; /** * Created by liulingfeng on 2017/4/13. */ public class ResMessage implements BaseMessage, Serializable{ public final static int CONF_ALL = 1; public final static int CONF = 2; public final static int TERM_ALL = 3; public final static int TERM = 4; public final static int DEL_TERM = 5; public final static int MIX_AUDIO = 6; public final static int MIX_VIDEO = 7; public final static int RELEASE_CHAIR = 8; public final static int ASSIGN_CHAIR = 9; public final static int CONF_MODE_CHAIR = 10; public final static int CONF_MODE_VOICE = 11; public final static int DEL_CONF = 12; public final static int CONF_CONFIG = 17; public final static int ADDRBOOK = 19; public final static int CREATE_CONF = 20; public final static int INVITE_TERM = 31; public final static int USER = 32; public final static int USERLIST = 33; public final static int ADD_CONF = 34; public final static int ADD_TERM = 35; public final static int SPEAKER = 36; //发言申请 public final static int CHAIRUSER = 0x25; //发言申请 //定义发给WEB页面的错误字 public final static int ERROR_WEB_CONF_ID = 0x1000; //会议ID错误 public final static int ERROR_WEB_ACCESS = 0x1003; //权限 public final static int ERROR_WEB_LOGIN = 0x1004; //登录 public final static int ERROR_WEB_CONF_NUM = 0x1006; //会议超过最大数 public final static int ERROR_WEB_TERM_NUM = 0x1007; //终端超过最大数 public final static int ERROR_WEB_CONF_NAME = 0x1008; //会议重名 public final static int ERROR_WEB_TERM_NAME = 0x1009; //终端重名 public final static int ERROR_WEB_USER_NAME = 0x100a; //该用户存在 public final static int ERROR_WEB_USER_NO = 0x100b;//没有找到此用户 public final static int ERROR_WEB_CONF_TIME = 0x100c; //预约会议时间错误 public final static int ERROR_WEB_CONF_MIX = 0x100d; //只能有一个媒体混合的会议 public final static int ERROR_WEB_DELDEF = 0x100e; //不能删除默认会议 public final static int ERROR_WEB_CONF_STR = 0x100f; //流媒体端口冲突 public final static int ERROR_WEB_TERM_ADDR = 0x1010; //终端地址冲突 public final static int ERROR_WEB_TERM_NOTFOUND = 0x1011; //终端没有找到 public final static int ERROR_WEB_INVALID_PASSWORD = 0x1012; //密码不对 // 响应包含的信息 0 == NULL 1 == ConfInfo 2== TermInfo // 3 ==ConfData 4==TermData // 5 == UserList public final static int INFO_CONFINFO = 1; public final static int INFO_TERMINFO = 2; public final static int INFO_CONFDATA = 3; public final static int INFO_TERMDATA = 4; public final static int INFO_USERLIST = 5; public final static int STATUS_SUCCESS = 1; public final static int STATUS_FAIL = 0; //1.所有会议信息响应;2.指定会议响应; //3.会议中所有终端信息响应; 4.指定终端信息响应; //5.删除终端响应; 6.混音响应; 7.多画面响应; 8.释放主席响应; //9.指定主席响应 //10.设置会议方式--主席方式; 11.设置会议方式--语音激励 //12.删除会议响应 //30.创建会议响应 31.邀请终端响应 //32.用户登录响应 33.获取用户列表响应 //34.添加会议响应 35.添加终端响应 public byte type; public byte status; //响应状态 1 == 成功 0 == 失败 public int error; //错误字(包含失败的原因) 在添加会议成功时此位代表会议ID public byte infoType; public BaseMessage infoMsg; @Override public byte[] toBytes() { byte[] bytes = new byte[5+infoMsg.calcMessageLength()]; bytes[0] = type; System.arraycopy(ByteUtils.int2bytes(error, 2), 0, bytes, 2, 2); bytes[4] = infoType; return bytes; } @Override public int calcMessageLength() { return 5+infoMsg.calcMessageLength(); } }
app/src/main/java/cn/diaovision/omnicontrol/core/message/conference/ResMessage.java
package cn.diaovision.omnicontrol.core.message.conference; import java.io.Serializable; import cn.diaovision.omnicontrol.util.ByteUtils; /** * Created by liulingfeng on 2017/4/13. */ public class ResMessage implements BaseMessage, Serializable{ public final static int CONF_ALL = 1; public final static int CONF = 2; public final static int TERM_ALL = 3; public final static int TERM = 4; public final static int DEL_TERM = 5; public final static int MIX_AUDIO = 6; public final static int MIX_VIDEO = 7; public final static int RELEASE_CHAIR = 8; public final static int ASSIGN_CHAIR = 9; public final static int CONF_MODE_CHAIR = 10; public final static int CONF_MODE_VOICE = 11; public final static int DEL_CONF = 12; public final static int CONF_CONFIG = 17; public final static int ADDRBOOK = 19; public final static int CREATE_CONF = 20; public final static int INVITE_ATTEND = 31; public final static int USER = 32; public final static int USERLIST = 33; public final static int ADD_CONF = 34; public final static int ADD_ATTEND = 35; public final static int SPEAKER = 36; //发言申请 public final static int CHAIRUSER = 0x25; //发言申请 //定义发给WEB页面的错误字 public final static int ERROR_WEB_CONF_ID = 0x1000; //会议ID错误 public final static int ERROR_WEB_ACCESS = 0x1003; //权限 public final static int ERROR_WEB_LOGIN = 0x1004; //登录 public final static int ERROR_WEB_CONF_NUM = 0x1006; //会议超过最大数 public final static int ERROR_WEB_TERM_NUM = 0x1007; //终端超过最大数 public final static int ERROR_WEB_CONF_NAME = 0x1008; //会议重名 public final static int ERROR_WEB_TERM_NAME = 0x1009; //终端重名 public final static int ERROR_WEB_USER_NAME = 0x100a; //该用户存在 public final static int ERROR_WEB_USER_NO = 0x100b;//没有找到此用户 public final static int ERROR_WEB_CONF_TIME = 0x100c; //预约会议时间错误 public final static int ERROR_WEB_CONF_MIX = 0x100d; //只能有一个媒体混合的会议 public final static int ERROR_WEB_DELDEF = 0x100e; //不能删除默认会议 public final static int ERROR_WEB_CONF_STR = 0x100f; //流媒体端口冲突 public final static int ERROR_WEB_TERM_ADDR = 0x1010; //终端地址冲突 public final static int ERROR_WEB_TERM_NOTFOUND = 0x1011; //终端没有找到 public final static int ERROR_WEB_INVALID_PASSWORD = 0x1012; //密码不对 //1.所有会议信息响应;2.指定会议响应; //3.会议中所有终端信息响应; 4.指定终端信息响应; //5.删除终端响应; 6.混音响应; 7.多画面响应; 8.释放主席响应; //9.指定主席响应 //10.设置会议方式--主席方式; 11.设置会议方式--语音激励 //12.删除会议响应 //30.创建会议响应 31.邀请终端响应 //32.用户登录响应 33.获取用户列表响应 //34.添加会议响应 35.添加终端响应 public byte type; public byte status; //响应状态 1 == 成功 0 == 失败 public int error; //错误字(包含失败的原因) 在添加会议成功时此位代表会议ID // 响应包含的信息 0 == NULL 1 == ConfInfo 2== TermInfo // 3 ==ConfData 4==TermData // 5 == UserList public final static int INFO_CONFINFO = 1; public final static int INFO_TERMINFO = 2; public final static int INFO_CONFDATA = 3; public final static int INFO_TERMDATA = 4; public final static int INFO_USERLIST = 5; byte infoType; BaseMessage infoMsg; @Override public byte[] toBytes() { byte[] bytes = new byte[5+infoMsg.calcMessageLength()]; bytes[0] = type; System.arraycopy(ByteUtils.int2bytes(error, 2), 0, bytes, 2, 2); bytes[4] = infoType; return bytes; } @Override public int calcMessageLength() { return 5+infoMsg.calcMessageLength(); } }
added getters / setters
app/src/main/java/cn/diaovision/omnicontrol/core/message/conference/ResMessage.java
added getters / setters
<ide><path>pp/src/main/java/cn/diaovision/omnicontrol/core/message/conference/ResMessage.java <ide> public final static int CONF_CONFIG = 17; <ide> public final static int ADDRBOOK = 19; <ide> public final static int CREATE_CONF = 20; <del> public final static int INVITE_ATTEND = 31; <add> public final static int INVITE_TERM = 31; <ide> public final static int USER = 32; <ide> public final static int USERLIST = 33; <ide> public final static int ADD_CONF = 34; <del> public final static int ADD_ATTEND = 35; <add> public final static int ADD_TERM = 35; <ide> public final static int SPEAKER = 36; //发言申请 <ide> public final static int CHAIRUSER = 0x25; //发言申请 <ide> <ide> public final static int ERROR_WEB_TERM_NOTFOUND = 0x1011; //终端没有找到 <ide> public final static int ERROR_WEB_INVALID_PASSWORD = 0x1012; //密码不对 <ide> <add> // 响应包含的信息 0 == NULL 1 == ConfInfo 2== TermInfo <add> // 3 ==ConfData 4==TermData <add> // 5 == UserList <add> public final static int INFO_CONFINFO = 1; <add> public final static int INFO_TERMINFO = 2; <add> public final static int INFO_CONFDATA = 3; <add> public final static int INFO_TERMDATA = 4; <add> public final static int INFO_USERLIST = 5; <add> <add> public final static int STATUS_SUCCESS = 1; <add> public final static int STATUS_FAIL = 0; <add> <ide> //1.所有会议信息响应;2.指定会议响应; <ide> //3.会议中所有终端信息响应; 4.指定终端信息响应; <ide> //5.删除终端响应; 6.混音响应; 7.多画面响应; 8.释放主席响应; <ide> public byte status; //响应状态 1 == 成功 0 == 失败 <ide> public int error; //错误字(包含失败的原因) 在添加会议成功时此位代表会议ID <ide> <del> // 响应包含的信息 0 == NULL 1 == ConfInfo 2== TermInfo <del> // 3 ==ConfData 4==TermData <del> // 5 == UserList <del> public final static int INFO_CONFINFO = 1; <del> public final static int INFO_TERMINFO = 2; <del> public final static int INFO_CONFDATA = 3; <del> public final static int INFO_TERMDATA = 4; <del> public final static int INFO_USERLIST = 5; <del> byte infoType; <add> public byte infoType; <ide> <del> BaseMessage infoMsg; <add> public BaseMessage infoMsg; <add> <add> <ide> <ide> @Override <ide> public byte[] toBytes() { <ide> public int calcMessageLength() { <ide> return 5+infoMsg.calcMessageLength(); <ide> } <add> <ide> } <ide>
Java
apache-2.0
214a1202f96a99586891dfa845ff22812ab5aa3b
0
bbottema/java-reflection
package org.bbottema.javareflection.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * A wrapper class that keeps a property ({@link Field}) and its setter/getter method(s) in one place. */ @Value @SuppressFBWarnings(justification = "Generated code") public class FieldWrapper { @NotNull private final Field field; @Nullable private final Method getter; @Nullable private final Method setter; }
src/main/java/org/bbottema/javareflection/model/FieldWrapper.java
package org.bbottema.javareflection.model; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * A wrapper class that keeps a property ({@link Field}) and its setter/getter method(s) in one place. */ public class FieldWrapper { @NotNull private final Field field; @Nullable private final Method getter; @Nullable private final Method setter; /** * Initializes the wrapper with field, getter and setter, all optional. * * @param field A {@link Field}. * @param getter A getter {@link Method} for the field. * @param setter A setter {@link Method} for the field. */ public FieldWrapper(@NotNull Field field, @Nullable Method getter, @Nullable Method setter) { this.field = field; this.getter = getter; this.setter = setter; } /** * @return {@link #field}. */ @NotNull public Field getField() { return field; } /** * @return {@link #getter}. */ @Nullable public Method getGetter() { return getter; } /** * @return {@link #setter}. */ @Nullable public Method getSetter() { return setter; } }
Lombokify
src/main/java/org/bbottema/javareflection/model/FieldWrapper.java
Lombokify
<ide><path>rc/main/java/org/bbottema/javareflection/model/FieldWrapper.java <ide> package org.bbottema.javareflection.model; <ide> <add>import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; <add>import lombok.Value; <ide> import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.annotations.Nullable; <ide> <ide> /** <ide> * A wrapper class that keeps a property ({@link Field}) and its setter/getter method(s) in one place. <ide> */ <add>@Value <add>@SuppressFBWarnings(justification = "Generated code") <ide> public class FieldWrapper { <ide> <ide> @NotNull <ide> private final Method getter; <ide> @Nullable <ide> private final Method setter; <del> <del> /** <del> * Initializes the wrapper with field, getter and setter, all optional. <del> * <del> * @param field A {@link Field}. <del> * @param getter A getter {@link Method} for the field. <del> * @param setter A setter {@link Method} for the field. <del> */ <del> public FieldWrapper(@NotNull Field field, @Nullable Method getter, @Nullable Method setter) { <del> this.field = field; <del> this.getter = getter; <del> this.setter = setter; <del> } <del> <del> /** <del> * @return {@link #field}. <del> */ <del> @NotNull <del> public Field getField() { <del> return field; <del> } <del> <del> /** <del> * @return {@link #getter}. <del> */ <del> @Nullable <del> public Method getGetter() { <del> return getter; <del> } <del> <del> /** <del> * @return {@link #setter}. <del> */ <del> @Nullable <del> public Method getSetter() { <del> return setter; <del> } <ide> }
Java
apache-2.0
c318864a4547e347b71ef6e6f96aab41b9bed92e
0
tempbottle/exit-web-framework,hb0504511129/exit-web-framework,tempbottle/exit-web-framework,hb0504511129/exit-web-framework,hb0504511129/exit-web-framework
package org.exitsoft.orm.core.hibernate.property; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.exitsoft.common.utils.ServletUtils; import org.exitsoft.orm.core.PropertyFilter; import org.exitsoft.orm.core.PropertyType; import org.exitsoft.orm.core.hibernate.property.impl.restriction.BetweenRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.EqRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.GeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.GtRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.InRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LikeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LlikeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LtRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.NeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.NinRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.RlikeRestriction; import org.hibernate.criterion.Criterion; /** * Hibernate属性过滤器约束持有者,帮助HibernateDao对buildCriterion方法创建相对的Criterion对象给Hibernate查询 * * @author vincent * */ public class PropertyFilterRestrictionHolder { private static Map<String, PropertyCriterionBuilder> criterionMap = new HashMap<String, PropertyCriterionBuilder>(); static { PropertyCriterionBuilder eqRestriction = new EqRestriction(); PropertyCriterionBuilder neRestriction = new NeRestriction(); PropertyCriterionBuilder geRestriction = new GeRestriction(); PropertyCriterionBuilder gtRestriction = new GtRestriction(); PropertyCriterionBuilder inRestriction = new InRestriction(); PropertyCriterionBuilder lLikeRestriction = new LlikeRestriction(); PropertyCriterionBuilder leRestriction = new LeRestriction(); PropertyCriterionBuilder likeRestriction = new LikeRestriction(); PropertyCriterionBuilder ltRestriction = new LtRestriction(); PropertyCriterionBuilder notInRestriction = new NinRestriction(); PropertyCriterionBuilder rLikeRestriction = new RlikeRestriction(); PropertyCriterionBuilder betweenRestriction = new BetweenRestriction(); criterionMap.put(eqRestriction.getRestrictionName(), eqRestriction); criterionMap.put(neRestriction.getRestrictionName(), neRestriction); criterionMap.put(geRestriction.getRestrictionName(), geRestriction); criterionMap.put(inRestriction.getRestrictionName(), inRestriction); criterionMap.put(gtRestriction.getRestrictionName(), gtRestriction); criterionMap.put(lLikeRestriction.getRestrictionName(), lLikeRestriction); criterionMap.put(leRestriction.getRestrictionName(), leRestriction); criterionMap.put(likeRestriction.getRestrictionName(), likeRestriction); criterionMap.put(ltRestriction.getRestrictionName(), ltRestriction); criterionMap.put(rLikeRestriction.getRestrictionName(), rLikeRestriction); criterionMap.put(notInRestriction.getRestrictionName(), notInRestriction); criterionMap.put(betweenRestriction.getRestrictionName(), betweenRestriction); } /** * 通过{@link PropertyFilter} 创建Hibernate约束标准 * * @param filter 属性过滤器 * * @return {@link Criterion} */ public static Criterion getCriterion(PropertyFilter filter) { PropertyCriterionBuilder criterionBuilder = criterionMap.get(filter.getRestrictionName()); return criterionBuilder.build(filter); } /** * 创建Hibernate约束标准 * * @param propertyName 属性名称 * @param value 值 * @param restrictionName 约束名称 * * @return {@link Criterion} */ public static Criterion getCriterion(String propertyName,Object value,String restrictionName) { PropertyCriterionBuilder restriction = criterionMap.get(restrictionName); return restriction.build(propertyName, value); } /** * 通过表达式和对比值创建条件过滤器集合,要求表达式与值必须相等 * <p> * 如: * </p> * <code> * PropertyFilerRestriction.createrPropertyFilter(new String[]{"EQ_S_propertyName1","NE_I_propertyName2"},new String[]{"vincent","vincent_OR_admin"}) * </code> * <p> * 对比值长度与表达式长度必须相等 * </p> * * @param expressions 表达式 * @param matchValues 对比值 * * @return List */ public static List<PropertyFilter> createPropertyFilter(String[] expressions,String[] matchValues) { if (ArrayUtils.isEmpty(expressions) && ArrayUtils.isEmpty(matchValues)) { return Collections.emptyList(); } if (expressions.length != matchValues.length) { throw new IllegalAccessError("expressions中的值与matchValues不匹配,matchValues的长度为:" + matchValues.length + "而expressions的长度为:" + expressions.length); } List<PropertyFilter> filters = new ArrayList<PropertyFilter>(); for (int i = 0; i < expressions.length; i++) { filters.add(createPropertyFilter(expressions[i], matchValues[i])); } return filters; } /** * 通过表达式和对比值创建条件过滤器 * <p> * 如: * </p> * <code> * PropertyFilerRestriction.createrPropertyFilter("EQ_S_propertyName","vincent") * </code> * * @param expressions 表达式 * @param matchValues 对比值 * * @return {@link PropertyFilter} */ public static PropertyFilter createPropertyFilter(String expression,String matchValue) { String restrictionsName = StringUtils.substringBefore(expression, "_"); if (!criterionMap.containsKey(restrictionsName)) { throw new IllegalAccessError("[" + expression + "]表达式找不到相应的约束名称,获取的值为:" + restrictionsName); } String classType = StringUtils.substringBetween(expression, "_"); PropertyType propertyType = null; try { propertyType = PropertyType.valueOf(classType); } catch (Exception e) { throw new IllegalAccessError("[" + expression + "]表达式找不到相应的属性类型,获取的值为:" + classType); } String[] propertyNames = null; if (StringUtils.contains(expression,"_OR_")) { String temp = StringUtils.substringAfter(expression, restrictionsName + "_" + classType + "_"); propertyNames = StringUtils.splitByWholeSeparator(temp, "_OR_"); } else { propertyNames = new String[1]; propertyNames[0] = StringUtils.substringAfterLast(expression, "_"); } return new PropertyFilter(restrictionsName, propertyType, propertyNames,matchValue); } /** * 获取Criterion的Map * * @return Map */ public static Map<String, PropertyCriterionBuilder> getCriterionMap() { return criterionMap; } /** * 设置Criterion的Map * * @return Map */ public static void setCriterionMap(Map<String, PropertyCriterionBuilder> map) { criterionMap.putAll(map); } /** * 从HttpRequest参数中创建PropertyFilter列表, 默认Filter属性名前缀为filter. * 当参数存在{filter_EQ_S_property1:value,filter_EQ_S_property2:''}该形式的时候,将不会创建filter_EQ_S_property2等于""值的实例 * 参考{@link PropertyFilterRestrictionHolder#buildPropertyFilter(HttpServletRequest, String, boolean)} * * @param request HttpServletRequest */ public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request) { return buildFromHttpRequest(request, "filter"); } /** * 从HttpRequest参数中创建PropertyFilter列表,当参数存在{filter_EQ_S_property1:value,filter_EQ_S_property2:''} * 该形式的时候,将不会创建filter_EQ_S_property2等于""值的实例 * 参考{@link PropertyFilterRestrictionHolder#buildPropertyFilter(HttpServletRequest, String, boolean)} * * @param request HttpServletRequest * @param filterPrefix 用于识别是propertyfilter参数的前准 * * @return List */ public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request,String filterPrefix) { return buildPropertyFilter(request, "filter",false); } /** * 从HttpRequest参数中创建PropertyFilter列表,例子: * * <pre> * 当页面提交的参数为:{filter_EQ_S_property1:value,filter_EQ_S_property2:''} * List filters =buildPropertyFilter(request,"filter",false); * 当前filters:EQ_S_proerpty1="value",EQ_S_proerpty1="" * * 当页面提交的参数为:{filter_EQ_S_property1:value,filter_EQ_S_property2:''} * List filters =buildPropertyFilter(request,"filter",true); * 当前filters:EQ_S_proerpty1="value" * </pre> * * @param request HttpServletRequest * @param filterPrefix 用于识别是propertyfilter参数的前准 * @param ignoreEmptyValue true表示当存在""值时忽略该PropertyFilter * * @return List */ public static List<PropertyFilter> buildPropertyFilter(HttpServletRequest request,String filterPrefix,boolean ignoreEmptyValue) { // 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map. Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix + "_"); return buildPropertyFilter(filterParamMap,ignoreEmptyValue); } /** * 从Map中创建PropertyFilter列表,如: * * <pre> * Map o = new HashMap(); * o.put("EQ_S_property1","value"); * o.put("EQ_S_property2",""); * List filters = buildPropertyFilter(o,false); * 当前filters:EQ_S_proerpty1="value",EQ_S_proerpty1="" * * Map o = new HashMap(); * o.put("EQ_S_property1","value"); * o.put("EQ_S_property2",""); * List filters = buildPropertyFilter(o,true); * 当前filters:EQ_S_proerpty1="value" * </pre> * * * @param filters 过滤器信息 * @param ignoreEmptyValue true表示当存在 null或者""值时忽略该PropertyFilter * */ public static List<PropertyFilter> buildPropertyFilter(Map<String, Object> filters,boolean ignoreEmptyValue) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); // 分析参数Map,构造PropertyFilter列表 for (Map.Entry<String, Object> entry : filters.entrySet()) { String expression = entry.getKey(); Object value = entry.getValue(); //如果ignoreEmptyValue为true忽略null或""的值 if (ignoreEmptyValue && (value == null || value.toString().equals(""))) { continue; } //如果ignoreEmptyValue为true忽略null或""的值 PropertyFilter filter = createPropertyFilter(expression, value.toString()); filterList.add(filter); } return filterList; } }
exit-orm/src/main/java/org/exitsoft/orm/core/hibernate/property/PropertyFilterRestrictionHolder.java
package org.exitsoft.orm.core.hibernate.property; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.exitsoft.common.utils.ServletUtils; import org.exitsoft.orm.core.PropertyFilter; import org.exitsoft.orm.core.PropertyType; import org.exitsoft.orm.core.hibernate.property.impl.restriction.BetweenRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.EqRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.GeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.GtRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.InRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LikeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LlikeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.LtRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.NeRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.NinRestriction; import org.exitsoft.orm.core.hibernate.property.impl.restriction.RlikeRestriction; import org.hibernate.criterion.Criterion; /** * Hibernate属性过滤器约束持有者,帮助HibernateDao对buildCriterion方法创建相对的Criterion对象给Hibernate查询 * * @author vincent * */ public class PropertyFilterRestrictionHolder { private static Map<String, PropertyCriterionBuilder> criterionMap = new HashMap<String, PropertyCriterionBuilder>(); static { PropertyCriterionBuilder eqRestriction = new EqRestriction(); PropertyCriterionBuilder neRestriction = new NeRestriction(); PropertyCriterionBuilder geRestriction = new GeRestriction(); PropertyCriterionBuilder gtRestriction = new GtRestriction(); PropertyCriterionBuilder inRestriction = new InRestriction(); PropertyCriterionBuilder lLikeRestriction = new LlikeRestriction(); PropertyCriterionBuilder leRestriction = new LeRestriction(); PropertyCriterionBuilder likeRestriction = new LikeRestriction(); PropertyCriterionBuilder ltRestriction = new LtRestriction(); PropertyCriterionBuilder notInRestriction = new NinRestriction(); PropertyCriterionBuilder rLikeRestriction = new RlikeRestriction(); PropertyCriterionBuilder betweenRestriction = new BetweenRestriction(); criterionMap.put(eqRestriction.getRestrictionName(), eqRestriction); criterionMap.put(neRestriction.getRestrictionName(), neRestriction); criterionMap.put(geRestriction.getRestrictionName(), geRestriction); criterionMap.put(inRestriction.getRestrictionName(), inRestriction); criterionMap.put(gtRestriction.getRestrictionName(), gtRestriction); criterionMap.put(lLikeRestriction.getRestrictionName(), lLikeRestriction); criterionMap.put(leRestriction.getRestrictionName(), leRestriction); criterionMap.put(likeRestriction.getRestrictionName(), likeRestriction); criterionMap.put(ltRestriction.getRestrictionName(), ltRestriction); criterionMap.put(rLikeRestriction.getRestrictionName(), rLikeRestriction); criterionMap.put(notInRestriction.getRestrictionName(), notInRestriction); criterionMap.put(betweenRestriction.getRestrictionName(), betweenRestriction); } /** * 通过{@link PropertyFilter} 创建Hibernate约束标准 * * @param filter 属性过滤器 * * @return {@link Criterion} */ public static Criterion getCriterion(PropertyFilter filter) { PropertyCriterionBuilder criterionBuilder = criterionMap.get(filter.getRestrictionName()); return criterionBuilder.build(filter); } /** * 创建Hibernate约束标准 * * @param propertyName 属性名称 * @param value 值 * @param restrictionName 约束名称 * * @return {@link Criterion} */ public static Criterion getCriterion(String propertyName,Object value,String restrictionName) { PropertyCriterionBuilder restriction = criterionMap.get(restrictionName); return restriction.build(propertyName, value); } /** * 通过表达式和对比值创建条件过滤器集合,要求表达式与值必须相等 * <p> * 如: * </p> * <code> * PropertyFilerRestriction.createrPropertyFilter(new String[]{"EQ_S_propertyName1","NE_I_propertyName2"},new String[]{"vincent","vincent_OR_admin"}) * </code> * <p> * 对比值长度与表达式长度必须相等 * </p> * * @param expressions 表达式 * @param matchValues 对比值 * * @return List */ public static List<PropertyFilter> createPropertyFilter(String[] expressions,String[] matchValues) { if (ArrayUtils.isEmpty(expressions) && ArrayUtils.isEmpty(matchValues)) { return Collections.emptyList(); } if (expressions.length != matchValues.length) { throw new IllegalAccessError("expressions中的值与matchValues不匹配,matchValues的长度为:" + matchValues.length + "而expressions的长度为:" + expressions.length); } List<PropertyFilter> filters = new ArrayList<PropertyFilter>(); for (int i = 0; i < expressions.length; i++) { filters.add(createPropertyFilter(expressions[i], matchValues[i])); } return filters; } /** * 通过表达式和对比值创建条件过滤器 * <p> * 如: * </p> * <code> * PropertyFilerRestriction.createrPropertyFilter("EQ_S_propertyName","vincent") * </code> * * @param expressions 表达式 * @param matchValues 对比值 * * @return {@link PropertyFilter} */ public static PropertyFilter createPropertyFilter(String expression,String matchValue) { String restrictionsName = StringUtils.substringBefore(expression, "_"); if (!criterionMap.containsKey(restrictionsName)) { throw new IllegalAccessError("[" + expression + "]表达式找不到相应的约束名称,获取的值为:" + restrictionsName); } String classType = StringUtils.substringBetween(expression, "_"); PropertyType propertyType = null; try { propertyType = PropertyType.valueOf(classType); } catch (Exception e) { throw new IllegalAccessError("[" + expression + "]表达式找不到相应的属性类型,获取的值为:" + classType); } String[] propertyNames = null; if (StringUtils.contains(expression,"_OR_")) { String temp = StringUtils.substringAfter(expression, restrictionsName + "_" + classType + "_"); propertyNames = StringUtils.splitByWholeSeparator(temp, "_OR_"); } else { propertyNames = new String[1]; propertyNames[0] = StringUtils.substringAfterLast(expression, "_"); } return new PropertyFilter(restrictionsName, propertyType, propertyNames,matchValue); } /** * 获取Criterion的Map * * @return Map */ public static Map<String, PropertyCriterionBuilder> getCriterionMap() { return criterionMap; } /** * 设置Criterion的Map * * @return Map */ public static void setCriterionMap(Map<String, PropertyCriterionBuilder> map) { criterionMap.putAll(map); } /** * 从HttpRequest中创建PropertyFilter列表, 默认Filter属性名前缀为filter. * * @see #buildFromHttpRequest(HttpServletRequest, String) */ public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request) { return buildFromHttpRequest(request, "filter"); } public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request,String filterPrefix) { return buildPropertyFilter(request, "filter",false); } /** * 从HttpRequest中创建PropertyFilter列表 * */ public static List<PropertyFilter> buildPropertyFilter(HttpServletRequest request,String filterPrefix,boolean ignoreEmptyValue) { // 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map. Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix + "_"); return buildPropertyFilter(filterParamMap,ignoreEmptyValue); } /** * 从Map中创建PropertyFilter列表 * */ public static List<PropertyFilter> buildPropertyFilter(Map<String, Object> filters,boolean ignoreEmptyValue) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); // 分析参数Map,构造PropertyFilter列表 for (Map.Entry<String, Object> entry : filters.entrySet()) { String expression = entry.getKey(); Object value = entry.getValue(); //如果ignoreEmptyValue为true忽略null或""的值 if (ignoreEmptyValue && (value == null || value.toString().equals(""))) { continue; } PropertyFilter filter = createPropertyFilter(expression, value.toString()); filterList.add(filter); } return filterList; } }
#6 添加buildPropertyFilter忽略空值的方法和明细的注释
exit-orm/src/main/java/org/exitsoft/orm/core/hibernate/property/PropertyFilterRestrictionHolder.java
#6 添加buildPropertyFilter忽略空值的方法和明细的注释
<ide><path>xit-orm/src/main/java/org/exitsoft/orm/core/hibernate/property/PropertyFilterRestrictionHolder.java <ide> } <ide> <ide> /** <del> * 从HttpRequest中创建PropertyFilter列表, 默认Filter属性名前缀为filter. <del> * <del> * @see #buildFromHttpRequest(HttpServletRequest, String) <add> * 从HttpRequest参数中创建PropertyFilter列表, 默认Filter属性名前缀为filter. <add> * 当参数存在{filter_EQ_S_property1:value,filter_EQ_S_property2:''}该形式的时候,将不会创建filter_EQ_S_property2等于""值的实例 <add> * 参考{@link PropertyFilterRestrictionHolder#buildPropertyFilter(HttpServletRequest, String, boolean)} <add> * <add> * @param request HttpServletRequest <ide> */ <ide> public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request) { <ide> return buildFromHttpRequest(request, "filter"); <ide> } <ide> <add> /** <add> * 从HttpRequest参数中创建PropertyFilter列表,当参数存在{filter_EQ_S_property1:value,filter_EQ_S_property2:''} <add> * 该形式的时候,将不会创建filter_EQ_S_property2等于""值的实例 <add> * 参考{@link PropertyFilterRestrictionHolder#buildPropertyFilter(HttpServletRequest, String, boolean)} <add> * <add> * @param request HttpServletRequest <add> * @param filterPrefix 用于识别是propertyfilter参数的前准 <add> * <add> * @return List <add> */ <ide> public static List<PropertyFilter> buildFromHttpRequest(HttpServletRequest request,String filterPrefix) { <ide> return buildPropertyFilter(request, "filter",false); <ide> } <ide> <ide> /** <del> * 从HttpRequest中创建PropertyFilter列表 <del> * <add> * 从HttpRequest参数中创建PropertyFilter列表,例子: <add> * <add> * <pre> <add> * 当页面提交的参数为:{filter_EQ_S_property1:value,filter_EQ_S_property2:''} <add> * List filters =buildPropertyFilter(request,"filter",false); <add> * 当前filters:EQ_S_proerpty1="value",EQ_S_proerpty1="" <add> * <add> * 当页面提交的参数为:{filter_EQ_S_property1:value,filter_EQ_S_property2:''} <add> * List filters =buildPropertyFilter(request,"filter",true); <add> * 当前filters:EQ_S_proerpty1="value" <add> * </pre> <add> * <add> * @param request HttpServletRequest <add> * @param filterPrefix 用于识别是propertyfilter参数的前准 <add> * @param ignoreEmptyValue true表示当存在""值时忽略该PropertyFilter <add> * <add> * @return List <ide> */ <ide> public static List<PropertyFilter> buildPropertyFilter(HttpServletRequest request,String filterPrefix,boolean ignoreEmptyValue) { <ide> <ide> } <ide> <ide> /** <del> * 从Map中创建PropertyFilter列表 <add> * 从Map中创建PropertyFilter列表,如: <add> * <add> * <pre> <add> * Map o = new HashMap(); <add> * o.put("EQ_S_property1","value"); <add> * o.put("EQ_S_property2",""); <add> * List filters = buildPropertyFilter(o,false); <add> * 当前filters:EQ_S_proerpty1="value",EQ_S_proerpty1="" <add> * <add> * Map o = new HashMap(); <add> * o.put("EQ_S_property1","value"); <add> * o.put("EQ_S_property2",""); <add> * List filters = buildPropertyFilter(o,true); <add> * 当前filters:EQ_S_proerpty1="value" <add> * </pre> <add> * <add> * <add> * @param filters 过滤器信息 <add> * @param ignoreEmptyValue true表示当存在 null或者""值时忽略该PropertyFilter <ide> * <ide> */ <ide> public static List<PropertyFilter> buildPropertyFilter(Map<String, Object> filters,boolean ignoreEmptyValue) { <ide> if (ignoreEmptyValue && (value == null || value.toString().equals(""))) { <ide> continue; <ide> } <del> <add> //如果ignoreEmptyValue为true忽略null或""的值 <ide> PropertyFilter filter = createPropertyFilter(expression, value.toString()); <ide> filterList.add(filter); <ide>
Java
mit
9802aa932eb67e3daf9bdb070bec22562173202d
0
hsobol/PRODSUP-001,hsobol/PRODSUP-001
src/test/dto/docs/example/Order.java
/** * */ package uk.co.jemos.podam.test.dto.docs.example; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import uk.co.jemos.podam.common.PodamCollection; /** * @author mtedone * */ public class Order implements Serializable { private static final long serialVersionUID = 1L; private int id; private Calendar createDate; private double totalAmount; @PodamCollection(nbrElements = 5) private List<OrderItem> orderItems = new ArrayList<OrderItem>(); /** * @return the id */ public int getId() { return id; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @return the createDate */ public Calendar getCreateDate() { return createDate; } /** * @param createDate * the createDate to set */ public void setCreateDate(Calendar createDate) { this.createDate = createDate; } /** * @return the totalAmount */ public double getTotalAmount() { return totalAmount; } /** * @param totalAmount * the totalAmount to set */ public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; } /** * @return the orderItems */ public List<OrderItem> getOrderItems() { return orderItems; } /** * @param orderItems * the orderItems to set */ public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } /** * Constructs a <code>String</code> with all attributes in name = value * format. * * @return a <code>String</code> representation of this object. */ @Override public String toString() { final String TAB = " "; StringBuilder retValue = new StringBuilder(); retValue.append("Order ( ").append("id = ").append(id).append(TAB) .append("createDate = ").append(createDate.getTime()) .append(TAB).append("totalAmount = ").append(totalAmount) .append(TAB).append("orderItems = ").append(orderItems) .append(TAB).append(" )"); return retValue.toString(); } }
Delete Order.java
src/test/dto/docs/example/Order.java
Delete Order.java
<ide><path>rc/test/dto/docs/example/Order.java <del>/** <del> * <del> */ <del>package uk.co.jemos.podam.test.dto.docs.example; <del> <del>import java.io.Serializable; <del>import java.util.ArrayList; <del>import java.util.Calendar; <del>import java.util.List; <del> <del>import uk.co.jemos.podam.common.PodamCollection; <del> <del>/** <del> * @author mtedone <del> * <del> */ <del>public class Order implements Serializable { <del> <del> private static final long serialVersionUID = 1L; <del> <del> private int id; <del> <del> private Calendar createDate; <del> <del> private double totalAmount; <del> <del> @PodamCollection(nbrElements = 5) <del> private List<OrderItem> orderItems = new ArrayList<OrderItem>(); <del> <del> /** <del> * @return the id <del> */ <del> public int getId() { <del> return id; <del> } <del> <del> /** <del> * @param id <del> * the id to set <del> */ <del> public void setId(int id) { <del> this.id = id; <del> } <del> <del> /** <del> * @return the createDate <del> */ <del> public Calendar getCreateDate() { <del> return createDate; <del> } <del> <del> /** <del> * @param createDate <del> * the createDate to set <del> */ <del> public void setCreateDate(Calendar createDate) { <del> this.createDate = createDate; <del> } <del> <del> /** <del> * @return the totalAmount <del> */ <del> public double getTotalAmount() { <del> return totalAmount; <del> } <del> <del> /** <del> * @param totalAmount <del> * the totalAmount to set <del> */ <del> public void setTotalAmount(double totalAmount) { <del> this.totalAmount = totalAmount; <del> } <del> <del> /** <del> * @return the orderItems <del> */ <del> public List<OrderItem> getOrderItems() { <del> return orderItems; <del> } <del> <del> /** <del> * @param orderItems <del> * the orderItems to set <del> */ <del> public void setOrderItems(List<OrderItem> orderItems) { <del> this.orderItems = orderItems; <del> } <del> <del> /** <del> * Constructs a <code>String</code> with all attributes in name = value <del> * format. <del> * <del> * @return a <code>String</code> representation of this object. <del> */ <del> @Override <del> public String toString() { <del> final String TAB = " "; <del> <del> StringBuilder retValue = new StringBuilder(); <del> <del> retValue.append("Order ( ").append("id = ").append(id).append(TAB) <del> .append("createDate = ").append(createDate.getTime()) <del> .append(TAB).append("totalAmount = ").append(totalAmount) <del> .append(TAB).append("orderItems = ").append(orderItems) <del> .append(TAB).append(" )"); <del> <del> return retValue.toString(); <del> } <del> <del>}
JavaScript
mit
29a25b04b4ca9c842846c407917e4ce65f223ab7
0
vejmelkam/wrfxweb,vejmelkam/wrfxweb
export class TimeSeriesChart extends HTMLElement { constructor() { super(); this.innerHTML = ` <link rel="stylesheet" href="css/timeSeriesChart.css"/> <div id="timeSeriesChartContainer"> <span id="closeTimeSeriesChart">x</span> <canvas id="timeSeriesChart" width="400px" height ="400px"></canvas> </div> `; this.ctx = null; } connectedCallback() { const timeSeriesChart = this.querySelector('#timeSeriesChartContainer'); L.DomEvent.disableScrollPropagation(timeSeriesChart); L.DomEvent.disableClickPropagation(timeSeriesChart); this.ctx = this.querySelector('#timeSeriesChart').getContext('2d'); this.querySelector('#closeTimeSeriesChart').onclick = () => timeSeriesChart.style.display = 'none'; } populateChart(data, label) { new Chart(this.ctx, { type: 'line', data: { labels: Object.keys(data), datasets: [{ label: label + " values", fill: false, data: Object.entries(data).map(entry => entry[1]), borderColor: "red", backgroundColor: "red", lineTension: 0, borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, } }); this.querySelector('#timeSeriesChartContainer').style.display = 'block'; } } window.customElements.define('timeseries-chart', TimeSeriesChart);
fdds/js/components/timeSeriesChart.js
export class TimeSeriesChart extends HTMLElement { constructor() { super(); this.innerHTML = ` <link rel="stylesheet" href="css/timeSeriesChart.css"/> <div id="timeSeriesChartContainer"> <span id="closeTimeSeriesChart">x</span> <canvas id="timeSeriesChart" width="400px" height ="400px"></canvas> </div> `; this.ctx = null; } connectedCallback() { const timeSeriesChart = this.querySelector('#timeSeriesChartContainer'); L.DomEvent.disableScrollPropagation(timeSeriesChart); L.DomEvent.disableClickPropagation(timeSeriesChart); this.ctx = this.querySelector('#timeSeriesChart').getContext('2d'); this.querySelector('#closeTimeSeriesChart').onclick = () => timeSeriesChart.style.display = 'none'; } populateChart(data, label) { new Chart(this.ctx, { type: 'line', data: { labels: Object.keys(data), datasets: [{ label: label + " values", fill: false, data: Object.entries(this.data).map(entry => entry[1]), borderColor: "red", backgroundColor: "red", lineTension: 0, borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, } }); this.querySelector('#timeSeriesChartContainer').style.display = 'block'; } } window.customElements.define('timeseries-chart', TimeSeriesChart);
Fixed null object passed to timeSeriesChart
fdds/js/components/timeSeriesChart.js
Fixed null object passed to timeSeriesChart
<ide><path>dds/js/components/timeSeriesChart.js <ide> datasets: [{ <ide> label: label + " values", <ide> fill: false, <del> data: Object.entries(this.data).map(entry => entry[1]), <add> data: Object.entries(data).map(entry => entry[1]), <ide> borderColor: "red", <ide> backgroundColor: "red", <ide> lineTension: 0,
Java
apache-2.0
0dd804e0ef63ce05e8061c39ef164a07df6968ca
0
wmedvede/guvnor,mbiarnes/guvnor,porcelli-forks/guvnor,droolsjbpm/guvnor,droolsjbpm/guvnor,hxf0801/guvnor,kiereleaseuser/guvnor,psiroky/guvnor,cristianonicolai/guvnor,mbiarnes/guvnor,droolsjbpm/guvnor,psiroky/guvnor,etirelli/guvnor,porcelli-forks/guvnor,adrielparedes/guvnor,baldimir/guvnor,mswiderski/guvnor,yurloc/guvnor,etirelli/guvnor,nmirasch/guvnor,baldimir/guvnor,cristianonicolai/guvnor,hxf0801/guvnor,baldimir/guvnor,adrielparedes/guvnor,porcelli-forks/guvnor,kiereleaseuser/guvnor,cristianonicolai/guvnor,nmirasch/guvnor,adrielparedes/guvnor,mbiarnes/guvnor,etirelli/guvnor,wmedvede/guvnor,nmirasch/guvnor,psiroky/guvnor,kiereleaseuser/guvnor,hxf0801/guvnor,yurloc/guvnor,wmedvede/guvnor
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.gwtutil; import com.google.gwt.core.client.GWT; import com.google.gwt.core.ext.Generator; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.event.shared.EventBus; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; import com.google.gwt.user.rebind.SourceWriter; import org.drools.guvnor.client.common.DefaultContentUploadEditor; import org.drools.guvnor.client.explorer.ClientFactory; import org.drools.guvnor.client.messages.Constants; import org.drools.guvnor.client.packages.AbstractModuleEditor; import org.drools.guvnor.client.perspectives.Perspective; import org.drools.guvnor.client.perspectives.author.AuthorPerspective; import org.drools.guvnor.client.resources.Images; import org.drools.guvnor.client.rpc.PackageConfigData; import org.drools.guvnor.client.rpc.RuleAsset; import org.drools.guvnor.client.ruleeditor.RuleViewer; import org.drools.guvnor.server.util.AssetEditorConfiguration; import org.drools.guvnor.server.util.AssetEditorConfigurationParser; import org.drools.guvnor.server.util.ModuleEditorConfiguration; import org.drools.guvnor.server.util.PerspectiveConfigurationParser; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This generates {@link PerspectiveFactory} class during GWT compile time as we can not use * Java reflection on GWT client side. */ public class PerspectiveFactoryGenerator extends Generator { public String generate( TreeLogger logger, GeneratorContext context, String requestedClass ) throws UnableToCompleteException { TypeOracle typeOracle = context.getTypeOracle(); JClassType objectType = typeOracle.findType( requestedClass ); if ( objectType == null ) { logger.log( TreeLogger.ERROR, "Could not find type: " + requestedClass ); throw new UnableToCompleteException(); } String implTypeName = objectType.getSimpleSourceName() + "Impl"; String implPackageName = objectType.getPackage().getName(); ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( implPackageName, implTypeName ); composerFactory.addImport( Map.class.getCanonicalName() ); composerFactory.addImport( List.class.getCanonicalName() ); composerFactory.addImport( Constants.class.getCanonicalName() ); composerFactory.addImport( Images.class.getCanonicalName() ); composerFactory.addImport( ImageResource.class.getCanonicalName() ); composerFactory.addImport( RuleAsset.class.getCanonicalName() ); composerFactory.addImport( RuleViewer.class.getCanonicalName() ); composerFactory.addImport( DefaultContentUploadEditor.class.getCanonicalName() ); composerFactory.addImport( Widget.class.getCanonicalName() ); composerFactory.addImport( GWT.class.getCanonicalName() ); composerFactory.addImport( ClientFactory.class.getCanonicalName() ); composerFactory.addImport( EventBus.class.getCanonicalName() ); composerFactory.addImport( PackageConfigData.class.getCanonicalName() ); composerFactory.addImport( Command.class.getCanonicalName() ); composerFactory.addImport( AbstractModuleEditor.class.getCanonicalName() ); composerFactory.addImplementedInterface( objectType .getQualifiedSourceName() ); PrintWriter printWriter = context.tryCreate( logger, implPackageName, implTypeName ); if ( printWriter != null ) { SourceWriter sourceWriter = composerFactory.createSourceWriter( context, printWriter ); Map<String, List<ModuleEditorConfiguration>> registeredEditors = loadModuleEditorMetaData(); generateAttributes( sourceWriter ); generateGetRegisteredAssetEditorFormatsMethod( sourceWriter, registeredEditors ); generateGetRegisteredModuleEditorFormatsMethod( sourceWriter, registeredEditors ); generateGetRegisteredPerspectiveTypesMethod( sourceWriter, registeredEditors ); generateGetModuleEditorMethod( sourceWriter, registeredEditors ); generateGetPerspectiveMethod( sourceWriter, registeredEditors ); sourceWriter.commit( logger ); } return implPackageName + "." + implTypeName; } private void generateAttributes( SourceWriter sourceWriter ) { sourceWriter.indent(); sourceWriter.println( "private static Images images = GWT.create(Images.class);" ); sourceWriter.println( "private static Constants constants = GWT.create(Constants.class);" ); } private void generateGetRegisteredAssetEditorFormatsMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredAssetEditorFormats(String moduleType) {" ); sourceWriter.indent(); sourceWriter.println( "String formats = \"\";" ); for(List<ModuleEditorConfiguration> moduleEditors : registeredEditors.values()) { for (ModuleEditorConfiguration moduleEditorConfiguration : moduleEditors) { sourceWriter.println("if(\"" + moduleEditorConfiguration.getFormat() + "\".equals(moduleType)) {"); sourceWriter.indent(); sourceWriter.println( "formats = \"" + moduleEditorConfiguration.getAssetEditorFormats() + "\";"); sourceWriter.outdent(); sourceWriter.println( "}"); } } sourceWriter.println( "String[] results = formats.split(\",\");"); sourceWriter.println( "return results;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } private void generateGetRegisteredModuleEditorFormatsMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredModuleEditorFormats(String perspectiveType) {" ); sourceWriter.indent(); for(String perspectiveType : registeredEditors.keySet()) { List<ModuleEditorConfiguration> moduleEditors = registeredEditors.get(perspectiveType); sourceWriter.println( "if(\"" + perspectiveType + "\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "String[] formats = new String[] {" ); int i = 0; for (ModuleEditorConfiguration a : moduleEditors) { String format = a.getFormat(); sourceWriter.print( "\"" + format + "\"" ); if ( i < moduleEditors.size() - 1 ) { sourceWriter.print( ", " ); } i++; } sourceWriter.println( "};"); sourceWriter.println( "return formats;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } sourceWriter.println( "return null;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } //TODO: Generate from configuration file. private void generateGetRegisteredPerspectiveTypesMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredPerspectiveTypes() {" ); sourceWriter.indent(); //sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\", \"soaservice\"};" ); sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\"};" ); sourceWriter.println( "return " + getRegisteredPerspectiveTypes() + ";"); sourceWriter.outdent(); sourceWriter.println( "}" ); } private void generateGetModuleEditorMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public AbstractModuleEditor getModuleEditor(PackageConfigData module, ClientFactory clientFactory, EventBus eventBus, boolean isHistoryReadOnly, Command refreshCommand) {" ); sourceWriter.indent(); for (List<ModuleEditorConfiguration> moduleEditorConfigurations : registeredEditors.values()) { for (ModuleEditorConfiguration moduleEditorConfiguration : moduleEditorConfigurations) { String format = moduleEditorConfiguration.getFormat(); String editorClassName = moduleEditorConfiguration.getEditorClass(); sourceWriter.println("if(module.getFormat().equals(\"" + format + "\")) {"); sourceWriter.indent(); sourceWriter.println("return new " + editorClassName + "(module, clientFactory, eventBus, isHistoryReadOnly, refreshCommand);"); sourceWriter.outdent(); sourceWriter.println("}"); } } sourceWriter.println("return null;"); sourceWriter.outdent(); sourceWriter.println( "}" ); } //TODO: Generate from configuration file. private void generateGetPerspectiveMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public Perspective getPerspective(String perspectiveType) {" ); sourceWriter.indent(); sourceWriter.println( "if(\"author\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.author.AuthorPerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "if(\"soaservice\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.soa.SOAPerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "if(\"runtime\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.runtime.RunTimePerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "return null;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } public static Map<String, List<ModuleEditorConfiguration>> loadModuleEditorMetaData() { Map<String, List<ModuleEditorConfiguration>> moduleEditorConfigurations = new HashMap<String, List<ModuleEditorConfiguration>>(); String[] registeredPerspectiveTypes = getRegisteredPerspectiveTypes(); for(String perspectiveType : registeredPerspectiveTypes) { Perspective p = getPerspective(perspectiveType); InputStream in = p.getClass().getResourceAsStream("perspective.xml"); //REVISIT: can a perspective have no perspective configuration file, eg, the runtime perspective? if(in != null) { PerspectiveConfigurationParser parser = new PerspectiveConfigurationParser(in); List<ModuleEditorConfiguration> moduleEditors = parser.getModuleEditors(); moduleEditorConfigurations.put(perspectiveType, moduleEditors); } } return moduleEditorConfigurations; } private static String[] getRegisteredPerspectiveTypes() { return new String[] {"author", "runtime", "soaservice"}; } private static Perspective getPerspective(String perspectiveType) { if ("author".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.author.AuthorPerspective(); } if ("soaservice".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.soa.SOAPerspective(); } if ("runtime".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.runtime.RunTimePerspective(); } return null; } }
guvnor-webapp/src/main/java/org/drools/guvnor/gwtutil/PerspectiveFactoryGenerator.java
/* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.gwtutil; import com.google.gwt.core.client.GWT; import com.google.gwt.core.ext.Generator; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.event.shared.EventBus; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; import com.google.gwt.user.rebind.SourceWriter; import org.drools.guvnor.client.common.DefaultContentUploadEditor; import org.drools.guvnor.client.explorer.ClientFactory; import org.drools.guvnor.client.messages.Constants; import org.drools.guvnor.client.packages.AbstractModuleEditor; import org.drools.guvnor.client.perspectives.Perspective; import org.drools.guvnor.client.perspectives.author.AuthorPerspective; import org.drools.guvnor.client.resources.Images; import org.drools.guvnor.client.rpc.PackageConfigData; import org.drools.guvnor.client.rpc.RuleAsset; import org.drools.guvnor.client.ruleeditor.RuleViewer; import org.drools.guvnor.server.util.AssetEditorConfiguration; import org.drools.guvnor.server.util.AssetEditorConfigurationParser; import org.drools.guvnor.server.util.ModuleEditorConfiguration; import org.drools.guvnor.server.util.PerspectiveConfigurationParser; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This generates {@link PerspectiveFactory} class during GWT compile time as we can not use * Java reflection on GWT client side. */ public class PerspectiveFactoryGenerator extends Generator { public String generate( TreeLogger logger, GeneratorContext context, String requestedClass ) throws UnableToCompleteException { TypeOracle typeOracle = context.getTypeOracle(); JClassType objectType = typeOracle.findType( requestedClass ); if ( objectType == null ) { logger.log( TreeLogger.ERROR, "Could not find type: " + requestedClass ); throw new UnableToCompleteException(); } String implTypeName = objectType.getSimpleSourceName() + "Impl"; String implPackageName = objectType.getPackage().getName(); ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( implPackageName, implTypeName ); composerFactory.addImport( Map.class.getCanonicalName() ); composerFactory.addImport( List.class.getCanonicalName() ); composerFactory.addImport( Constants.class.getCanonicalName() ); composerFactory.addImport( Images.class.getCanonicalName() ); composerFactory.addImport( ImageResource.class.getCanonicalName() ); composerFactory.addImport( RuleAsset.class.getCanonicalName() ); composerFactory.addImport( RuleViewer.class.getCanonicalName() ); composerFactory.addImport( DefaultContentUploadEditor.class.getCanonicalName() ); composerFactory.addImport( Widget.class.getCanonicalName() ); composerFactory.addImport( GWT.class.getCanonicalName() ); composerFactory.addImport( ClientFactory.class.getCanonicalName() ); composerFactory.addImport( EventBus.class.getCanonicalName() ); composerFactory.addImport( PackageConfigData.class.getCanonicalName() ); composerFactory.addImport( Command.class.getCanonicalName() ); composerFactory.addImport( AbstractModuleEditor.class.getCanonicalName() ); composerFactory.addImplementedInterface( objectType .getQualifiedSourceName() ); PrintWriter printWriter = context.tryCreate( logger, implPackageName, implTypeName ); if ( printWriter != null ) { SourceWriter sourceWriter = composerFactory.createSourceWriter( context, printWriter ); Map<String, List<ModuleEditorConfiguration>> registeredEditors = loadModuleEditorMetaData(); generateAttributes( sourceWriter ); generateGetRegisteredAssetEditorFormatsMethod( sourceWriter, registeredEditors ); generateGetRegisteredModuleEditorFormatsMethod( sourceWriter, registeredEditors ); generateGetRegisteredPerspectiveTypesMethod( sourceWriter, registeredEditors ); generateGetModuleEditorMethod( sourceWriter, registeredEditors ); generateGetPerspectiveMethod( sourceWriter, registeredEditors ); sourceWriter.commit( logger ); } return implPackageName + "." + implTypeName; } private void generateAttributes( SourceWriter sourceWriter ) { sourceWriter.indent(); sourceWriter.println( "private static Images images = GWT.create(Images.class);" ); sourceWriter.println( "private static Constants constants = GWT.create(Constants.class);" ); } private void generateGetRegisteredAssetEditorFormatsMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredAssetEditorFormats(String moduleType) {" ); sourceWriter.indent(); sourceWriter.println( "String formats = \"\";" ); for(List<ModuleEditorConfiguration> moduleEditors : registeredEditors.values()) { for (ModuleEditorConfiguration moduleEditorConfiguration : moduleEditors) { sourceWriter.println("if(\"" + moduleEditorConfiguration.getFormat() + "\".equals(moduleType)) {"); sourceWriter.indent(); sourceWriter.println( "formats = \"" + moduleEditorConfiguration.getAssetEditorFormats() + "\";"); sourceWriter.outdent(); sourceWriter.println( "}"); } } sourceWriter.println( "String[] results = formats.split(\",\");"); sourceWriter.println( "return results;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } private void generateGetRegisteredModuleEditorFormatsMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredModuleEditorFormats(String perspectiveType) {" ); sourceWriter.indent(); for(String perspectiveType : registeredEditors.keySet()) { List<ModuleEditorConfiguration> moduleEditors = registeredEditors.get(perspectiveType); sourceWriter.println( "if(\"" + perspectiveType + "\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "String[] formats = new String[] {" ); int i = 0; for (ModuleEditorConfiguration a : moduleEditors) { String format = a.getFormat(); sourceWriter.print( "\"" + format + "\"" ); if ( i < moduleEditors.size() - 1 ) { sourceWriter.print( ", " ); } i++; } sourceWriter.println( "};"); sourceWriter.println( "return formats;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } sourceWriter.println( "return null;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } //TODO: Generate from configuration file. private void generateGetRegisteredPerspectiveTypesMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public String[] getRegisteredPerspectiveTypes() {" ); sourceWriter.indent(); sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\", \"soaservice\"};" ); sourceWriter.println( "return formats;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } private void generateGetModuleEditorMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public AbstractModuleEditor getModuleEditor(PackageConfigData module, ClientFactory clientFactory, EventBus eventBus, boolean isHistoryReadOnly, Command refreshCommand) {" ); sourceWriter.indent(); for (List<ModuleEditorConfiguration> moduleEditorConfigurations : registeredEditors.values()) { for (ModuleEditorConfiguration moduleEditorConfiguration : moduleEditorConfigurations) { String format = moduleEditorConfiguration.getFormat(); String editorClassName = moduleEditorConfiguration.getEditorClass(); sourceWriter.println("if(module.getFormat().equals(\"" + format + "\")) {"); sourceWriter.indent(); sourceWriter.println("return new " + editorClassName + "(module, clientFactory, eventBus, isHistoryReadOnly, refreshCommand);"); sourceWriter.outdent(); sourceWriter.println("}"); } } sourceWriter.println("return null;"); sourceWriter.outdent(); sourceWriter.println( "}" ); } //TODO: Generate from configuration file. private void generateGetPerspectiveMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { sourceWriter.println( "public Perspective getPerspective(String perspectiveType) {" ); sourceWriter.indent(); sourceWriter.println( "if(\"author\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.author.AuthorPerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "if(\"soaservice\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.soa.SOAPerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "if(\"runtime\".equals(perspectiveType)) {"); sourceWriter.indent(); sourceWriter.println( "return new org.drools.guvnor.client.perspectives.runtime.RunTimePerspective();"); sourceWriter.outdent(); sourceWriter.println( "}"); sourceWriter.println( "return null;" ); sourceWriter.outdent(); sourceWriter.println( "}" ); } public static Map<String, List<ModuleEditorConfiguration>> loadModuleEditorMetaData() { Map<String, List<ModuleEditorConfiguration>> moduleEditorConfigurations = new HashMap<String, List<ModuleEditorConfiguration>>(); String[] registeredPerspectiveTypes = getRegisteredPerspectiveTypes(); for(String perspectiveType : registeredPerspectiveTypes) { Perspective p = getPerspective(perspectiveType); InputStream in = p.getClass().getResourceAsStream("perspective.xml"); //REVISIT: can a perspective have no perspective configuration file, eg, the runtime perspective? if(in != null) { PerspectiveConfigurationParser parser = new PerspectiveConfigurationParser(in); List<ModuleEditorConfiguration> moduleEditors = parser.getModuleEditors(); moduleEditorConfigurations.put(perspectiveType, moduleEditors); } } return moduleEditorConfigurations; } private static String[] getRegisteredPerspectiveTypes() { return new String[] {"author", "runtime", "soaservice"}; } private static Perspective getPerspective(String perspectiveType) { if ("author".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.author.AuthorPerspective(); } if ("soaservice".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.soa.SOAPerspective(); } if ("runtime".equals(perspectiveType)) { return new org.drools.guvnor.client.perspectives.runtime.RunTimePerspective(); } return null; } }
disable soa perspective on master
guvnor-webapp/src/main/java/org/drools/guvnor/gwtutil/PerspectiveFactoryGenerator.java
disable soa perspective on master
<ide><path>uvnor-webapp/src/main/java/org/drools/guvnor/gwtutil/PerspectiveFactoryGenerator.java <ide> private void generateGetRegisteredPerspectiveTypesMethod( SourceWriter sourceWriter, Map<String, List<ModuleEditorConfiguration>> registeredEditors ) { <ide> sourceWriter.println( "public String[] getRegisteredPerspectiveTypes() {" ); <ide> sourceWriter.indent(); <del> sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\", \"soaservice\"};" ); <del> <del> sourceWriter.println( "return formats;" ); <add> //sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\", \"soaservice\"};" ); <add> sourceWriter.println( "String[] formats = new String[] {\"author\", \"runtime\"};" ); <add> <add> sourceWriter.println( "return " + getRegisteredPerspectiveTypes() + ";"); <ide> sourceWriter.outdent(); <ide> sourceWriter.println( "}" ); <ide> }
Java
mit
56fa3f9bf2b7c3389712911a05b8239d7131dcd3
0
mback2k/jlibamf
package de.uxnr.amf.v3.type; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import de.uxnr.amf.AMF_Context; import de.uxnr.amf.AMF_Type; import de.uxnr.amf.v0.base.U8; import de.uxnr.amf.v3.AMF3_Type; import de.uxnr.amf.v3.base.U29; public class ByteArray extends AMF3_Type { private int[] value = new int[0]; private java.lang.Integer hashCode = null; public ByteArray() { } public ByteArray(int[] value) { this.value = value; } @Override public void write(AMF_Context context, DataOutputStream output) throws IOException { int reference = context.getAMF3ObjectReference(this); if (reference >= 0) { U29 flag = new U29((reference << 1) & ~1); flag.write(context, output); return; } context.addAMF3Object(this); U29 length = new U29((this.value.length << 1) | 1); length.write(context, output); for (int elem : this.value) { U8 ubyte = new U8(elem); ubyte.write(context, output); } } @Override public AMF_Type read(AMF_Context context, DataInputStream input) throws IOException { U29 flag = new U29(context, input); int flags = flag.get(); if ((flags & 1) == 0) return context.getAMF3Object(flags >> 1); context.addAMF3Object(this); int length = (flags >> 1); this.value = new int[length]; for (int index = 0; index < length; index++) { this.value[index] = input.read(); } return this; } public void set(int[] value) { this.hashCode = null; this.value = value; } public int[] get() { return this.value; } @Override public java.lang.String toString() { StringBuilder sb = new StringBuilder(); sb.append("ByteArray '"); for (int i = 0; i < this.value.length; i++) { int value = this.value[i]; if (value < 10) { sb.append('0'); } sb.append(java.lang.Integer.toHexString(value)); } sb.append("'"); return sb.toString(); } @Override public int hashCode() { if (this.hashCode != null) return this.hashCode; this.hashCode = 0; for (int value : this.value) this.hashCode ^= value; return this.hashCode; } }
src/de/uxnr/amf/v3/type/ByteArray.java
package de.uxnr.amf.v3.type; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import de.uxnr.amf.AMF_Context; import de.uxnr.amf.AMF_Type; import de.uxnr.amf.v0.base.U8; import de.uxnr.amf.v3.AMF3_Type; import de.uxnr.amf.v3.base.U29; public class ByteArray extends AMF3_Type { private int[] value = new int[0]; private java.lang.Integer hashCode = null; public ByteArray() { } public ByteArray(int[] value) { this.value = value; } @Override public void write(AMF_Context context, DataOutputStream output) throws IOException { int reference = context.getAMF3ObjectReference(this); if (reference >= 0) { U29 flag = new U29((reference << 1) & ~1); flag.write(context, output); return; } context.addAMF3Object(this); U29 length = new U29((this.value.length << 1) | 1); length.write(context, output); for (int elem : this.value) { U8 ubyte = new U8(elem); ubyte.write(context, output); } } @Override public AMF_Type read(AMF_Context context, DataInputStream input) throws IOException { U29 flag = new U29(context, input); int flags = flag.get(); if ((flags & 1) == 0) return context.getAMF3Object(flags >> 1); context.addAMF3Object(this); int length = (flags >> 1); this.value = new int[length]; for (int index = 0; index < length; index++) { this.value[index] = input.read(); } return this; } public void set(int[] value) { this.hashCode = null; this.value = value; } public int[] get() { return this.value; } @Override public java.lang.String toString() { return "ByteArray"; } @Override public int hashCode() { if (this.hashCode != null) return this.hashCode; this.hashCode = 0; for (int value : this.value) this.hashCode ^= value; return this.hashCode; } }
Updated toString method of ByteArray
src/de/uxnr/amf/v3/type/ByteArray.java
Updated toString method of ByteArray
<ide><path>rc/de/uxnr/amf/v3/type/ByteArray.java <ide> <ide> @Override <ide> public java.lang.String toString() { <del> return "ByteArray"; <add> StringBuilder sb = new StringBuilder(); <add> sb.append("ByteArray '"); <add> for (int i = 0; i < this.value.length; i++) { <add> int value = this.value[i]; <add> if (value < 10) { <add> sb.append('0'); <add> } <add> sb.append(java.lang.Integer.toHexString(value)); <add> } <add> sb.append("'"); <add> return sb.toString(); <ide> } <ide> <ide> @Override
Java
apache-2.0
af35fb9f05d6187e7d582749cc9a0d4bda2c43d9
0
amidst/toolbox,amidst/toolbox
package eu.amidst.dataGeneration; import eu.amidst.core.classifiers.NaiveBayesClassifier; import eu.amidst.core.datastream.Attributes; import eu.amidst.core.datastream.DataInstance; import eu.amidst.core.datastream.DataStream; import eu.amidst.core.io.DataStreamLoader; import eu.amidst.core.models.BayesianNetwork; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * The script to generate this data can be found in Dropbox under (as it should not be made public) * * Created by [email protected] on 03/12/15. */ public class GenerateCajaMarLikeData { public void generateDataFromRScript() throws IOException{ /* * The 1st parameter is the number of files (per month) * The 2nd parameter is the length of the sequence, i.e., # of clients */ Runtime.getRuntime().exec("Rscript ./extensions/uai2016/doc-experiments/dataGenerationForFlink/" + "data_generator_IDA.R 3 1000"); Runtime.getRuntime().exec("Rscript ./extensions/uai2016/doc-experiments/dataGenerationForFlink/" + "data_generator_SCAI.R 3 1000"); } public void testGeneratedDataWithRScript(){ DataStream<DataInstance> dataIDA = DataStreamLoader.openFromFile( "./extensions/uai2016/doc-experiments/dataGenerationForFlink/IDAlikeData/MONTH1.arff"); Attributes attributes = dataIDA.stream().findFirst().get().getAttributes(); System.out.println(attributes.toString()); System.out.println("DEFAULT[0] = "+dataIDA.stream().findFirst().get().getValue( attributes.getAttributeByName("DEFAULT"))); DataStream<DataInstance> dataSCAI = DataStreamLoader.openFromFile( "./extensions/uai2016/doc-experiments/dataGenerationForFlink/SCAIlikeData/MONTH2.arff"); attributes = dataSCAI.stream().findFirst().get().getAttributes(); System.out.println(attributes.toString()); System.out.println("AGE[0] = "+dataSCAI.stream().findFirst().get().getValue( attributes.getAttributeByName("AGE"))); // Learn NB classifier for IDA data NaiveBayesClassifier model = new NaiveBayesClassifier(); model.setClassName("DEFAULT"); model.setParallelMode(true); model.learn(dataIDA, 1000); BayesianNetwork nbClassifierIDA = model.getBNModel(); System.out.println("\nNB classifier for IDA data learnt succesfully\n"); System.out.println(nbClassifierIDA.toString()); System.out.println("\n-------------------------------------------\n"); // Learn NB classifier for SCAI data model = new NaiveBayesClassifier(); model.setClassName("DEFAULT"); model.setParallelMode(true); model.learn(dataSCAI, 1000); BayesianNetwork nbClassifierSCAI = model.getBNModel(); System.out.println("\nNB classifier for SCAI data learnt succesfully\n"); System.out.println(nbClassifierSCAI.toString()); } public static void main(String[] args) throws Exception{ GenerateCajaMarLikeData generateCajaMarLikeData = new GenerateCajaMarLikeData(); generateCajaMarLikeData.generateDataFromRScript(); TimeUnit.SECONDS.sleep(60); generateCajaMarLikeData.testGeneratedDataWithRScript(); } }
extensions/uai2016/src/main/java/eu/amidst/dataGeneration/GenerateCajaMarLikeData.java
package eu.amidst.dataGeneration; import eu.amidst.core.classifiers.NaiveBayesClassifier; import eu.amidst.core.datastream.Attributes; import eu.amidst.core.datastream.DataInstance; import eu.amidst.core.datastream.DataStream; import eu.amidst.core.io.DataStreamLoader; import eu.amidst.core.models.BayesianNetwork; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * The script to generate this data can be found in Dropbox under (as it should not be made public) * * Created by [email protected] on 03/12/15. */ public class GenerateCajaMarLikeData { public void generateDataFromRScript() throws IOException{ /* * The 1st parameter is the number of files (per month) * The 2nd parameter is the length of the sequence, i.e., # of clients */ Runtime.getRuntime().exec("Rscript ./extensions/uai2016/doc-experiments/dataGenerationForFlink/" + "data_generator_IDA.R 3 1000"); Runtime.getRuntime().exec("Rscript ./extensions/uai2016/doc-experiments/dataGenerationForFlink/" + "data_generator_SCAI.R 3 1000"); } public void testGeneratedDataWithRScript(){ DataStream<DataInstance> dataIDA = DataStreamLoader.openFromFile( "./extensions/uai2016/doc-experiments/dataGenerationForFlink/IDAlikeData/MONTH1.arff"); Attributes attributes = dataIDA.stream().findFirst().get().getAttributes(); System.out.println(attributes.toString()); System.out.println("DEFAULT[0] = "+dataIDA.stream().findFirst().get().getValue( attributes.getAttributeByName("DEFAULT"))); DataStream<DataInstance> dataSCAI = DataStreamLoader.openFromFile( "./extensions/uai2016/doc-experiments/dataGenerationForFlink/SCAIlikeData/MONTH2.arff"); attributes = dataSCAI.stream().findFirst().get().getAttributes(); System.out.println(attributes.toString()); System.out.println("AGE[0] = "+dataSCAI.stream().findFirst().get().getValue( attributes.getAttributeByName("AGE"))); // Learn NB classifier for IDA data NaiveBayesClassifier model = new NaiveBayesClassifier(); model.setClassName("DEFAULT"); model.setParallelMode(true); model.learn(dataIDA, 1000); BayesianNetwork nbClassifierIDA = model.getBNModel(); System.out.println("\nNB classifier for IDA data learnt succesfully\n"); System.out.println(nbClassifierIDA.toString()); System.out.println("\n-------------------------------------------\n"); // Learn NB classifier for SCAI data model = new NaiveBayesClassifier(); model.setClassName("DEFAULT"); model.setParallelMode(true); model.learn(dataIDA, 1000); BayesianNetwork nbClassifierSCAI = model.getBNModel(); System.out.println("\nNB classifier for SCAI data learnt succesfully\n"); System.out.println(nbClassifierSCAI.toString()); } public static void main(String[] args) throws Exception{ GenerateCajaMarLikeData generateCajaMarLikeData = new GenerateCajaMarLikeData(); generateCajaMarLikeData.generateDataFromRScript(); TimeUnit.SECONDS.sleep(5); generateCajaMarLikeData.testGeneratedDataWithRScript(); } }
Small update
extensions/uai2016/src/main/java/eu/amidst/dataGeneration/GenerateCajaMarLikeData.java
Small update
<ide><path>xtensions/uai2016/src/main/java/eu/amidst/dataGeneration/GenerateCajaMarLikeData.java <ide> public class GenerateCajaMarLikeData { <ide> <ide> public void generateDataFromRScript() throws IOException{ <del> /* <add> /* <ide> * The 1st parameter is the number of files (per month) <ide> * The 2nd parameter is the length of the sequence, i.e., # of clients <ide> */ <ide> model = new NaiveBayesClassifier(); <ide> model.setClassName("DEFAULT"); <ide> model.setParallelMode(true); <del> model.learn(dataIDA, 1000); <add> model.learn(dataSCAI, 1000); <ide> BayesianNetwork nbClassifierSCAI = model.getBNModel(); <ide> System.out.println("\nNB classifier for SCAI data learnt succesfully\n"); <ide> System.out.println(nbClassifierSCAI.toString()); <ide> <ide> generateCajaMarLikeData.generateDataFromRScript(); <ide> <del> TimeUnit.SECONDS.sleep(5); <add> TimeUnit.SECONDS.sleep(60); <ide> <ide> generateCajaMarLikeData.testGeneratedDataWithRScript(); <ide>
Java
bsd-3-clause
a2636a5197c7ab613a23a2b0a67e0e71c1119368
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.cananolab.ui.particle; import gov.nih.nci.cananolab.domain.particle.Characterization; import gov.nih.nci.cananolab.domain.particle.NanoparticleSample; import gov.nih.nci.cananolab.dto.common.DataSetBean; import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean; import gov.nih.nci.cananolab.dto.common.FileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean; import gov.nih.nci.cananolab.service.common.ExperimentConfigService; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.common.impl.ExperimentConfigServiceLocalImpl; import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationResultService; import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationResultServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationServiceRemoteImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleSampleServiceLocalImpl; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.protocol.InitProtocolSetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.ClassUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * Base action for characterization actions * * @author pansu * */ public class CharacterizationAction extends BaseAnnotationAction { /** * Add or update the data to database * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); if (charBean.getAssayCategory().equals( "Phsico-Chemical Characterization")) { InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, charBean); InitCharacterizationSetup .getInstance() .persistPhysicalCharacterizationDropdowns(request, charBean); } else if (charBean.getAssayCategory().equals( "Invitro Characterization")) { InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, charBean); InitCharacterizationSetup.getInstance() .persistInvitroCharacterizationDropdowns(request, charBean); } // TODO:: // if (!validateDerivedDatum(request, charBean)) { // return mapping.getInputForward(); // } saveCharacterization(request, theForm, charBean); ActionMessages msgs = new ActionMessages(); // validate number by javascript filterFloatingNumber // validateNumber(request, charBean, msgs); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getCharacterizationName()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return summaryEdit(mapping, form, request, response); } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupNew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; setupInputForm(request, theForm); // reset characterizationBean CharacterizationBean charBean = new CharacterizationBean(); theForm.set("achar", charBean); String charType = request.getParameter("charType"); if (charType != null) { charBean.setCharacterizationType(charType); SortedSet<String> charNames = InitCharacterizationSetup .getInstance().getCharNamesByCharType(request, charBean.getCharacterizationType()); request.getSession().setAttribute("charTypeChars", charNames); } return mapping.getInputForward(); } /** * Set up drop-downs need for the input form * * @param request * @param theForm * @throws Exception */ private void setupInputForm(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String particleId = request.getParameter("particleId"); String charType = request.getParameter("charType"); InitNanoparticleSetup.getInstance().setSharedDropdowns(request); InitCharacterizationSetup.getInstance().setCharactierizationDropDowns( request, particleId); InitExperimentConfigSetup.getInstance().setExperimentConfigDropDowns( request); InitProtocolSetup.getInstance().getProtocolFilesByChar(request, charType); InitCharacterizationSetup.getInstance() .setPhysicalCharacterizationDropdowns(request); InitCharacterizationSetup.getInstance() .setInvitroCharacterizationDropdowns(request); // String detailPage = setupDetailPage(charBean); // request.getSession().setAttribute("characterizationDetailPage", // detailPage); // set up other particles with the same primary point of contact InitNanoparticleSetup.getInstance().getOtherParticleNames(request, particleId); } /** * Set up the input form for editing existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String charId = request.getParameter("charId"); String charClass = request.getParameter("charClassName"); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); Characterization chara = charService.findCharacterizationById(charId, charClass); CharacterizationBean charBean = new CharacterizationBean(chara); // setup correct display for characterization name and characterization // type InitCharacterizationSetup.getInstance().setCharacterizationName( request, charBean); InitCharacterizationSetup.getInstance().setCharacterizationType( request, charBean); // setup dropdown for existing characterization SortedSet<String> charNames = InitCharacterizationSetup.getInstance() .getCharNamesByCharType(request, charBean.getCharacterizationType()); request.getSession().setAttribute("charTypeChars", charNames); SortedSet<String> assayEndpoints = InitCharacterizationSetup .getInstance().getAssayTypesByCharName(request, charBean.getCharacterizationName()); request.getSession().setAttribute("charNameAssays", assayEndpoints); theForm.set("achar", charBean); setupInputForm(request, theForm); return mapping.getInputForward(); } private String setupDetailPage(CharacterizationBean charBean) { String includePage = null; if (charBean.getClassName().equals("PhysicalState") || charBean.getClassName().equals("Shape") || charBean.getClassName().equals("Solubility") || charBean.getClassName().equals("Surface")) { includePage = "/particle/characterization/physical/body" + charBean.getClassName() + "Info.jsp"; } else if (charBean.getClassName().equals("Cytotoxicity")) { includePage = "/particle/characterization/invitro/body" + charBean.getClassName() + "Info.jsp"; } return includePage; } private void saveToOtherParticles(HttpServletRequest request, Characterization copy, UserBean user, String particleSampleName, NanoparticleSample[] otherSamples) throws Exception { FileService fileService = new FileServiceLocalImpl(); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); for (NanoparticleSample sample : otherSamples) { charService.saveCharacterization(sample, copy); // update copied filename and save content and set visibility // TODO // if (copy.getDerivedBioAssayDataCollection() != null) { // for (DerivedBioAssayData bioassay : copy // .getDerivedBioAssayDataCollection()) { // if (bioassay.getFile() != null) { // fileService.saveCopiedFileAndSetVisibility(bioassay // .getFile(), user, particleSampleName, sample // .getName()); // } // } // } } } private void setupDomainChar(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean) throws Exception { // setup domainFile for fileBeans ParticleBean particleBean = setupParticle(theForm, request, "local"); UserBean user = (UserBean) request.getSession().getAttribute("user"); // setup domainFile uri for fileBeans String internalUriPath = CaNanoLabConstants.FOLDER_PARTICLE + "/" + particleBean.getDomainParticleSample().getName() + "/" + StringUtils.getOneWordLowerCaseFirstLetter(InitSetup .getInstance().getDisplayName(charBean.getClassName(), request.getSession().getServletContext())); if (charBean.getClassName() == null) { String className = InitSetup.getInstance().getClassName( charBean.getCharacterizationName(), request.getSession().getServletContext()); charBean.setClassName(className); } charBean.setupDomainChar(user.getLoginName(), internalUriPath); } // TODO for datum and condition // protected boolean validateDerivedDatum(HttpServletRequest request, // CharacterizationBean charBean) throws Exception { // // ActionMessages msgs = new ActionMessages(); // boolean noErrors = true; // for (DerivedBioAssayDataBean derivedBioassayDataBean : charBean // .getDerivedBioAssayDataList()) { // // List<DerivedDatumBean> datumList = derivedBioassayDataBean // .getDatumList(); // FileBean lfBean = derivedBioassayDataBean.getFileBean(); // // // error, if no data input from either the lab file or derived datum // boolean noFileError = true; // if (datumList == null || datumList.size() == 0) { // noFileError = validateFileBean(request, msgs, lfBean); // if (!noFileError) { // ActionMessage msg = new ActionMessage("errors.required", // "If no derived datum entered, the file data"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // this.saveErrors(request, msgs); // noErrors = false; // } // } // // for (DerivedDatumBean datum : datumList) { // // if value field is populated, so does the name field. // if (datum.getDomainDerivedDatum().getName().length() == 0) { // ActionMessage msg = new ActionMessage("errors.required", // "Derived data name"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // this.saveErrors(request, msgs); // noErrors = false; // } // try { // Float value = new Float(datum.getValueStr()); // // for boolean type, the value must be 0/1 // if (datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean") // && value != 0.0 && value != 1.0) { // ActionMessage msg = new ActionMessage( // "error.booleanValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } // } catch (NumberFormatException e) { // // for boolean type, the value must be true/false // if (datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean") // && !datum.getValueStr().equalsIgnoreCase("true") // && !datum.getValueStr().equalsIgnoreCase("false")) { // ActionMessage msg = new ActionMessage( // "error.booleanValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } else if (!datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean")) { // ActionMessage msg = new ActionMessage( // "error.derivedDatumValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } // } // } // } // return noErrors; // } private void saveCharacterization(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean) throws Exception { // setup domainFile for fileBeans ParticleBean particleBean = setupParticle(theForm, request, "local"); UserBean user = (UserBean) request.getSession().getAttribute("user"); // setup domainFile uri for fileBeans setupDomainChar(request, theForm, charBean); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); charService.saveCharacterization( particleBean.getDomainParticleSample(), charBean .getDomainChar()); // set public visibility AuthorizationService authService = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = authService.getAccessibleGroups( particleBean.getDomainParticleSample().getName(), CaNanoLabConstants.CSM_READ_PRIVILEGE); if (accessibleGroups != null && accessibleGroups .contains(CaNanoLabConstants.CSM_PUBLIC_GROUP)) { charService.assignPublicVisibility(authService, charBean .getDomainChar()); } // save file data to file system and set visibility List<FileBean> files = new ArrayList<FileBean>(); // TODO:: // for (DerivedBioAssayDataBean bioassay : charBean // .getDerivedBioAssayDataList()) { // if (bioassay.getFileBean() != null) { // files.add(bioassay.getFileBean()); // } // } saveFilesToFileSystem(files); // save to other particles NanoparticleSample[] otherSamples = prepareCopy(request, theForm); if (otherSamples != null) { Boolean copyData = (Boolean) theForm.get("copyData"); Characterization copy = charBean.getDomainCopy(copyData); saveToOtherParticles(request, copy, user, particleBean .getDomainParticleSample().getName(), otherSamples); } particleBean = setupParticle(theForm, request, "local"); } private void deleteCharacterization(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean, String createdBy) throws Exception { ParticleBean particleBean = setupParticle(theForm, request, "local"); // setup domainFile uri for fileBeans String internalUriPath = CaNanoLabConstants.FOLDER_PARTICLE + "/" + particleBean.getDomainParticleSample().getName() + "/" + StringUtils.getOneWordLowerCaseFirstLetter(InitSetup .getInstance().getDisplayName(charBean.getClassName(), request.getSession().getServletContext())); charBean.setupDomainChar(createdBy, internalUriPath); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); charService.deleteCharacterization(charBean.getDomainChar()); } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); UserBean user = (UserBean) request.getSession().getAttribute("user"); deleteCharacterization(request, theForm, charBean, user.getLoginName()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.deleteCharacterization"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); ActionForward forward = mapping.findForward("success"); request.setAttribute("updateDataTree", "true"); String particleId = theForm.getString("particleId"); NanoparticleSampleService sampleService = new NanoparticleSampleServiceLocalImpl(); ParticleBean particleBean = sampleService .findNanoparticleSampleById(particleId); InitNanoparticleSetup.getInstance().getDataTree(particleBean, request); return forward; } public void validateNumber(HttpServletRequest request, CharacterizationBean charBean, ActionMessages msgs) throws Exception { if (charBean.getSolubility().getCriticalConcentration() == 0.0) { ActionMessage msg = new ActionMessage("message.invalidNumber"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); } } private void setCharacterizationFileFullPath(HttpServletRequest request, CharacterizationBean charBean, String location) throws Exception { if (location.equals("local")) { // TODO:: // set file full path // for (DerivedBioAssayDataBean bioassayBean : charBean // .getDerivedBioAssayDataList()) { // if (bioassayBean.getFileBean() != null) { // FileBean fileBean = bioassayBean.getFileBean(); // if (!fileBean.getDomainFile().getUriExternal()) { // String fileRoot = PropertyReader.getProperty( // CaNanoLabConstants.FILEUPLOAD_PROPERTY, // "fileRepositoryDir"); // fileBean.setFullPath(fileRoot + File.separator // + fileBean.getDomainFile().getUri()); // } else { // fileBean.setFullPath(fileBean.getDomainFile().getUri()); // } // } // } } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); URL localURL = new URL(request.getRequestURL().toString()); String actionPath = localURL.getPath(); URL remoteUrl = new URL(serviceUrl); String remoteServerHostUrl = remoteUrl.getProtocol() + "://" + remoteUrl.getHost() + ":" + remoteUrl.getPort(); String remoteDownloadUrlBase = remoteServerHostUrl + actionPath + "?dispatch=download&location=local&fileId="; // TODO:: // for (DerivedBioAssayDataBean bioassayBean : charBean // .getDerivedBioAssayDataList()) { // if (bioassayBean.getFileBean() != null) { // FileBean fileBean = bioassayBean.getFileBean(); // String remoteDownloadUrl = remoteDownloadUrlBase // + fileBean.getDomainFile().getId().toString(); // fileBean.setFullPath(remoteDownloadUrl); // } // } } } private CharacterizationSummaryBean setupCharSummary( DynaValidatorForm theForm, HttpServletRequest request) throws Exception { String submitType = request.getParameter("submitType"); String className = InitSetup.getInstance().getClassName(submitType, request.getSession().getServletContext()); String fullClassName = ClassUtils.getFullClass(className) .getCanonicalName(); String location = request.getParameter("location"); ParticleBean particleBean = setupParticle(theForm, request, location); UserBean user = (UserBean) request.getSession().getAttribute("user"); NanoparticleCharacterizationService service = null; if (location.equals("local")) { service = new NanoparticleCharacterizationServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); service = new NanoparticleCharacterizationServiceRemoteImpl( serviceUrl); } CharacterizationSummaryBean charSummary = service .getParticleCharacterizationSummaryByClass(particleBean .getDomainParticleSample().getName(), fullClassName, user); request.setAttribute("charSummary", charSummary); return charSummary; } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleId = request.getParameter("particleId"); // setupCharSummary(theForm, request); String location = request.getParameter("location"); String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&submitType=" + "&dispatch=printSummaryView" + "&location=" + location; String printAllLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&dispatch=printFullSummaryView" + "&location=" + location; request.getSession().setAttribute("printSummaryViewLinkURL", printLinkURL); request.getSession().setAttribute("printFullSummaryViewLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward summaryEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleId = request.getParameter("particleId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationServiceLocalImpl(); List<CharacterizationBean> charBeans = service .findCharsByParticleSampleId(particleId); // set characterization types for (CharacterizationBean charBean : charBeans) { InitCharacterizationSetup.getInstance().setCharacterizationType( request, charBean); InitCharacterizationSetup.getInstance().setCharacterizationName( request, charBean); } CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean( charBeans); request.setAttribute("characterizationSummaryView", summaryView); // setupCharSummary(theForm, request); String location = request.getParameter("location"); String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&submitType=" + "&dispatch=printSummaryView" + "&location=" + location; String printAllLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&dispatch=printFullSummaryView" + "&location=" + location; request.getSession().setAttribute("printSummaryViewLinkURL", printLinkURL); request.getSession().setAttribute("printFullSummaryViewLinkURL", printAllLinkURL); return mapping.findForward("summaryEdit"); } public ActionForward saveExperimentConfig(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); // setupDomainChar(request, theForm, achar); ExperimentConfigBean configBean = achar.getTheExperimentConfig(); UserBean user = (UserBean) request.getSession().getAttribute("user"); configBean.setupDomain(user.getLoginName()); ExperimentConfigService service = new ExperimentConfigServiceLocalImpl(); service.saveExperimentConfig(configBean.getDomain()); achar.addExperimentConfig(configBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); InitExperimentConfigSetup.getInstance() .persistExperimentConfigDropdowns(request, configBean); return mapping.getInputForward(); } public ActionForward saveDataSet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); DataSetBean dataSetBean = achar.getTheDataSet(); String theDataSetId = (String) theForm .get("theDataSetId"); if (theDataSetId!=null) { dataSetBean.getDomain().setId(new Long(theDataSetId)); } UserBean user = (UserBean) request.getSession().getAttribute("user"); dataSetBean.setupDomain(user.getLoginName()); NanoparticleCharacterizationResultService service = new NanoparticleCharacterizationResultServiceLocalImpl(); service.saveData(dataSetBean.getData()); achar.addDataSet(dataSetBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return mapping.getInputForward(); } public ActionForward deleteExperimentConfig(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); setupDomainChar(request, theForm, achar); ExperimentConfigBean configBean = achar.getTheExperimentConfig(); ExperimentConfigService service = new ExperimentConfigServiceLocalImpl(); service.deleteExperimentConfig(configBean.getDomain()); achar.removeExperimentConfig(configBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return mapping.getInputForward(); } }
src/gov/nih/nci/cananolab/ui/particle/CharacterizationAction.java
package gov.nih.nci.cananolab.ui.particle; import gov.nih.nci.cananolab.domain.particle.Characterization; import gov.nih.nci.cananolab.domain.particle.NanoparticleSample; import gov.nih.nci.cananolab.dto.common.DataSetBean; import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean; import gov.nih.nci.cananolab.dto.common.FileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean; import gov.nih.nci.cananolab.service.common.ExperimentConfigService; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.common.impl.ExperimentConfigServiceLocalImpl; import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationResultService; import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationResultServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleCharacterizationServiceRemoteImpl; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleSampleServiceLocalImpl; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.protocol.InitProtocolSetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.ClassUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * Base action for characterization actions * * @author pansu * */ public class CharacterizationAction extends BaseAnnotationAction { /** * Add or update the data to database * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); if (charBean.getAssayCategory().equals( "Phsico-Chemical Characterization")) { InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, charBean); InitCharacterizationSetup .getInstance() .persistPhysicalCharacterizationDropdowns(request, charBean); } else if (charBean.getAssayCategory().equals( "Invitro Characterization")) { InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, charBean); InitCharacterizationSetup.getInstance() .persistInvitroCharacterizationDropdowns(request, charBean); } // TODO:: // if (!validateDerivedDatum(request, charBean)) { // return mapping.getInputForward(); // } saveCharacterization(request, theForm, charBean); ActionMessages msgs = new ActionMessages(); // validate number by javascript filterFloatingNumber // validateNumber(request, charBean, msgs); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getCharacterizationName()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return summaryEdit(mapping, form, request, response); } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupNew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; setupInputForm(request, theForm); // reset characterizationBean CharacterizationBean charBean = new CharacterizationBean(); theForm.set("achar", charBean); String charType = request.getParameter("charType"); if (charType != null) { charBean.setCharacterizationType(charType); SortedSet<String> charNames = InitCharacterizationSetup .getInstance().getCharNamesByCharType(request, charBean.getCharacterizationType()); request.getSession().setAttribute("charTypeChars", charNames); } return mapping.getInputForward(); } /** * Set up drop-downs need for the input form * * @param request * @param theForm * @throws Exception */ private void setupInputForm(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String particleId = request.getParameter("particleId"); String charType = request.getParameter("charType"); InitNanoparticleSetup.getInstance().setSharedDropdowns(request); InitCharacterizationSetup.getInstance().setCharactierizationDropDowns( request, particleId); InitExperimentConfigSetup.getInstance().setExperimentConfigDropDowns( request); InitProtocolSetup.getInstance().getProtocolFilesByChar(request, charType); InitCharacterizationSetup.getInstance() .setPhysicalCharacterizationDropdowns(request); InitCharacterizationSetup.getInstance() .setInvitroCharacterizationDropdowns(request); // String detailPage = setupDetailPage(charBean); // request.getSession().setAttribute("characterizationDetailPage", // detailPage); // set up other particles with the same primary point of contact InitNanoparticleSetup.getInstance().getOtherParticleNames(request, particleId); } /** * Set up the input form for editing existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String charId = request.getParameter("charId"); String charClass = request.getParameter("charClassName"); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); Characterization chara = charService.findCharacterizationById(charId, charClass); CharacterizationBean charBean = new CharacterizationBean(chara); // setup correct display for characterization name and characterization // type InitCharacterizationSetup.getInstance().setCharacterizationName( request, charBean); InitCharacterizationSetup.getInstance().setCharacterizationType( request, charBean); // setup dropdown for existing characterization SortedSet<String> charNames = InitCharacterizationSetup.getInstance() .getCharNamesByCharType(request, charBean.getCharacterizationType()); request.getSession().setAttribute("charTypeChars", charNames); SortedSet<String> assayEndpoints = InitCharacterizationSetup .getInstance().getAssayTypesByCharName(request, charBean.getCharacterizationName()); request.getSession().setAttribute("charNameAssays", assayEndpoints); theForm.set("achar", charBean); setupInputForm(request, theForm); return mapping.getInputForward(); } private String setupDetailPage(CharacterizationBean charBean) { String includePage = null; if (charBean.getClassName().equals("PhysicalState") || charBean.getClassName().equals("Shape") || charBean.getClassName().equals("Solubility") || charBean.getClassName().equals("Surface")) { includePage = "/particle/characterization/physical/body" + charBean.getClassName() + "Info.jsp"; } else if (charBean.getClassName().equals("Cytotoxicity")) { includePage = "/particle/characterization/invitro/body" + charBean.getClassName() + "Info.jsp"; } return includePage; } private void saveToOtherParticles(HttpServletRequest request, Characterization copy, UserBean user, String particleSampleName, NanoparticleSample[] otherSamples) throws Exception { FileService fileService = new FileServiceLocalImpl(); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); for (NanoparticleSample sample : otherSamples) { charService.saveCharacterization(sample, copy); // update copied filename and save content and set visibility // TODO // if (copy.getDerivedBioAssayDataCollection() != null) { // for (DerivedBioAssayData bioassay : copy // .getDerivedBioAssayDataCollection()) { // if (bioassay.getFile() != null) { // fileService.saveCopiedFileAndSetVisibility(bioassay // .getFile(), user, particleSampleName, sample // .getName()); // } // } // } } } private void setupDomainChar(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean) throws Exception { // setup domainFile for fileBeans ParticleBean particleBean = setupParticle(theForm, request, "local"); UserBean user = (UserBean) request.getSession().getAttribute("user"); // setup domainFile uri for fileBeans String internalUriPath = CaNanoLabConstants.FOLDER_PARTICLE + "/" + particleBean.getDomainParticleSample().getName() + "/" + StringUtils.getOneWordLowerCaseFirstLetter(InitSetup .getInstance().getDisplayName(charBean.getClassName(), request.getSession().getServletContext())); if (charBean.getClassName() == null) { String className = InitSetup.getInstance().getClassName( charBean.getCharacterizationName(), request.getSession().getServletContext()); charBean.setClassName(className); } charBean.setupDomainChar(user.getLoginName(), internalUriPath); } // TODO for datum and condition // protected boolean validateDerivedDatum(HttpServletRequest request, // CharacterizationBean charBean) throws Exception { // // ActionMessages msgs = new ActionMessages(); // boolean noErrors = true; // for (DerivedBioAssayDataBean derivedBioassayDataBean : charBean // .getDerivedBioAssayDataList()) { // // List<DerivedDatumBean> datumList = derivedBioassayDataBean // .getDatumList(); // FileBean lfBean = derivedBioassayDataBean.getFileBean(); // // // error, if no data input from either the lab file or derived datum // boolean noFileError = true; // if (datumList == null || datumList.size() == 0) { // noFileError = validateFileBean(request, msgs, lfBean); // if (!noFileError) { // ActionMessage msg = new ActionMessage("errors.required", // "If no derived datum entered, the file data"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // this.saveErrors(request, msgs); // noErrors = false; // } // } // // for (DerivedDatumBean datum : datumList) { // // if value field is populated, so does the name field. // if (datum.getDomainDerivedDatum().getName().length() == 0) { // ActionMessage msg = new ActionMessage("errors.required", // "Derived data name"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // this.saveErrors(request, msgs); // noErrors = false; // } // try { // Float value = new Float(datum.getValueStr()); // // for boolean type, the value must be 0/1 // if (datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean") // && value != 0.0 && value != 1.0) { // ActionMessage msg = new ActionMessage( // "error.booleanValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } // } catch (NumberFormatException e) { // // for boolean type, the value must be true/false // if (datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean") // && !datum.getValueStr().equalsIgnoreCase("true") // && !datum.getValueStr().equalsIgnoreCase("false")) { // ActionMessage msg = new ActionMessage( // "error.booleanValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } else if (!datum.getDomainDerivedDatum().getValueType() // .equalsIgnoreCase("boolean")) { // ActionMessage msg = new ActionMessage( // "error.derivedDatumValue", "Derived data value"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveErrors(request, msgs); // noErrors = false; // } // } // } // } // return noErrors; // } private void saveCharacterization(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean) throws Exception { // setup domainFile for fileBeans ParticleBean particleBean = setupParticle(theForm, request, "local"); UserBean user = (UserBean) request.getSession().getAttribute("user"); // setup domainFile uri for fileBeans setupDomainChar(request, theForm, charBean); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); charService.saveCharacterization( particleBean.getDomainParticleSample(), charBean .getDomainChar()); // set public visibility AuthorizationService authService = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); List<String> accessibleGroups = authService.getAccessibleGroups( particleBean.getDomainParticleSample().getName(), CaNanoLabConstants.CSM_READ_PRIVILEGE); if (accessibleGroups != null && accessibleGroups .contains(CaNanoLabConstants.CSM_PUBLIC_GROUP)) { charService.assignPublicVisibility(authService, charBean .getDomainChar()); } // save file data to file system and set visibility List<FileBean> files = new ArrayList<FileBean>(); // TODO:: // for (DerivedBioAssayDataBean bioassay : charBean // .getDerivedBioAssayDataList()) { // if (bioassay.getFileBean() != null) { // files.add(bioassay.getFileBean()); // } // } saveFilesToFileSystem(files); // save to other particles NanoparticleSample[] otherSamples = prepareCopy(request, theForm); if (otherSamples != null) { Boolean copyData = (Boolean) theForm.get("copyData"); Characterization copy = charBean.getDomainCopy(copyData); saveToOtherParticles(request, copy, user, particleBean .getDomainParticleSample().getName(), otherSamples); } particleBean = setupParticle(theForm, request, "local"); } private void deleteCharacterization(HttpServletRequest request, DynaValidatorForm theForm, CharacterizationBean charBean, String createdBy) throws Exception { ParticleBean particleBean = setupParticle(theForm, request, "local"); // setup domainFile uri for fileBeans String internalUriPath = CaNanoLabConstants.FOLDER_PARTICLE + "/" + particleBean.getDomainParticleSample().getName() + "/" + StringUtils.getOneWordLowerCaseFirstLetter(InitSetup .getInstance().getDisplayName(charBean.getClassName(), request.getSession().getServletContext())); charBean.setupDomainChar(createdBy, internalUriPath); NanoparticleCharacterizationService charService = new NanoparticleCharacterizationServiceLocalImpl(); charService.deleteCharacterization(charBean.getDomainChar()); } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); UserBean user = (UserBean) request.getSession().getAttribute("user"); deleteCharacterization(request, theForm, charBean, user.getLoginName()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.deleteCharacterization"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); ActionForward forward = mapping.findForward("success"); request.setAttribute("updateDataTree", "true"); String particleId = theForm.getString("particleId"); NanoparticleSampleService sampleService = new NanoparticleSampleServiceLocalImpl(); ParticleBean particleBean = sampleService .findNanoparticleSampleById(particleId); InitNanoparticleSetup.getInstance().getDataTree(particleBean, request); return forward; } public void validateNumber(HttpServletRequest request, CharacterizationBean charBean, ActionMessages msgs) throws Exception { if (charBean.getSolubility().getCriticalConcentration() == 0.0) { ActionMessage msg = new ActionMessage("message.invalidNumber"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); } } private void setCharacterizationFileFullPath(HttpServletRequest request, CharacterizationBean charBean, String location) throws Exception { if (location.equals("local")) { // TODO:: // set file full path // for (DerivedBioAssayDataBean bioassayBean : charBean // .getDerivedBioAssayDataList()) { // if (bioassayBean.getFileBean() != null) { // FileBean fileBean = bioassayBean.getFileBean(); // if (!fileBean.getDomainFile().getUriExternal()) { // String fileRoot = PropertyReader.getProperty( // CaNanoLabConstants.FILEUPLOAD_PROPERTY, // "fileRepositoryDir"); // fileBean.setFullPath(fileRoot + File.separator // + fileBean.getDomainFile().getUri()); // } else { // fileBean.setFullPath(fileBean.getDomainFile().getUri()); // } // } // } } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); URL localURL = new URL(request.getRequestURL().toString()); String actionPath = localURL.getPath(); URL remoteUrl = new URL(serviceUrl); String remoteServerHostUrl = remoteUrl.getProtocol() + "://" + remoteUrl.getHost() + ":" + remoteUrl.getPort(); String remoteDownloadUrlBase = remoteServerHostUrl + actionPath + "?dispatch=download&location=local&fileId="; // TODO:: // for (DerivedBioAssayDataBean bioassayBean : charBean // .getDerivedBioAssayDataList()) { // if (bioassayBean.getFileBean() != null) { // FileBean fileBean = bioassayBean.getFileBean(); // String remoteDownloadUrl = remoteDownloadUrlBase // + fileBean.getDomainFile().getId().toString(); // fileBean.setFullPath(remoteDownloadUrl); // } // } } } private CharacterizationSummaryBean setupCharSummary( DynaValidatorForm theForm, HttpServletRequest request) throws Exception { String submitType = request.getParameter("submitType"); String className = InitSetup.getInstance().getClassName(submitType, request.getSession().getServletContext()); String fullClassName = ClassUtils.getFullClass(className) .getCanonicalName(); String location = request.getParameter("location"); ParticleBean particleBean = setupParticle(theForm, request, location); UserBean user = (UserBean) request.getSession().getAttribute("user"); NanoparticleCharacterizationService service = null; if (location.equals("local")) { service = new NanoparticleCharacterizationServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); service = new NanoparticleCharacterizationServiceRemoteImpl( serviceUrl); } CharacterizationSummaryBean charSummary = service .getParticleCharacterizationSummaryByClass(particleBean .getDomainParticleSample().getName(), fullClassName, user); request.setAttribute("charSummary", charSummary); return charSummary; } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleId = request.getParameter("particleId"); // setupCharSummary(theForm, request); String location = request.getParameter("location"); String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&submitType=" + "&dispatch=printSummaryView" + "&location=" + location; String printAllLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&dispatch=printFullSummaryView" + "&location=" + location; request.getSession().setAttribute("printSummaryViewLinkURL", printLinkURL); request.getSession().setAttribute("printFullSummaryViewLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward summaryEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleId = request.getParameter("particleId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationServiceLocalImpl(); List<CharacterizationBean> charBeans = service .findCharsByParticleSampleId(particleId); // set characterization types for (CharacterizationBean charBean : charBeans) { InitCharacterizationSetup.getInstance().setCharacterizationType( request, charBean); InitCharacterizationSetup.getInstance().setCharacterizationName( request, charBean); } CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean( charBeans); request.setAttribute("characterizationSummaryView", summaryView); // setupCharSummary(theForm, request); String location = request.getParameter("location"); String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&submitType=" + "&dispatch=printSummaryView" + "&location=" + location; String printAllLinkURL = requestUrl + "?page=0&particleId=" + particleId + "&dispatch=printFullSummaryView" + "&location=" + location; request.getSession().setAttribute("printSummaryViewLinkURL", printLinkURL); request.getSession().setAttribute("printFullSummaryViewLinkURL", printAllLinkURL); return mapping.findForward("summaryEdit"); } public ActionForward saveExperimentConfig(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); // setupDomainChar(request, theForm, achar); ExperimentConfigBean configBean = achar.getTheExperimentConfig(); UserBean user = (UserBean) request.getSession().getAttribute("user"); configBean.setupDomain(user.getLoginName()); ExperimentConfigService service = new ExperimentConfigServiceLocalImpl(); service.saveExperimentConfig(configBean.getDomain()); achar.addExperimentConfig(configBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); InitExperimentConfigSetup.getInstance() .persistExperimentConfigDropdowns(request, configBean); return mapping.getInputForward(); } public ActionForward saveDataSet(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); DataSetBean dataSetBean = achar.getTheDataSet(); UserBean user = (UserBean) request.getSession().getAttribute("user"); dataSetBean.setupDomain(user.getLoginName()); NanoparticleCharacterizationResultService service = new NanoparticleCharacterizationResultServiceLocalImpl(); service.saveData(dataSetBean.getData()); achar.addDataSet(dataSetBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return mapping.getInputForward(); } public ActionForward deleteExperimentConfig(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); setupDomainChar(request, theForm, achar); ExperimentConfigBean configBean = achar.getTheExperimentConfig(); ExperimentConfigService service = new ExperimentConfigServiceLocalImpl(); service.deleteExperimentConfig(configBean.getDomain()); achar.removeExperimentConfig(configBean); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return mapping.getInputForward(); } }
retrieve theDataSetId to charactizationForm SVN-Revision: 14754
src/gov/nih/nci/cananolab/ui/particle/CharacterizationAction.java
retrieve theDataSetId to charactizationForm
<ide><path>rc/gov/nih/nci/cananolab/ui/particle/CharacterizationAction.java <ide> DynaValidatorForm theForm = (DynaValidatorForm) form; <ide> CharacterizationBean achar = (CharacterizationBean) theForm <ide> .get("achar"); <del> DataSetBean dataSetBean = achar.getTheDataSet(); <add> DataSetBean dataSetBean = achar.getTheDataSet(); <add> String theDataSetId = (String) theForm <add> .get("theDataSetId"); <add> if (theDataSetId!=null) { <add> dataSetBean.getDomain().setId(new Long(theDataSetId)); <add> } <ide> UserBean user = (UserBean) request.getSession().getAttribute("user"); <ide> dataSetBean.setupDomain(user.getLoginName()); <ide> NanoparticleCharacterizationResultService service = new NanoparticleCharacterizationResultServiceLocalImpl();
Java
apache-2.0
a21fdf2c78de47deff30759ed7c00d1b892f12ef
0
Wechat-Group/WxJava,comeonc/weixin-java-tools,comeonc/weixin-java-tools,binarywang/weixin-java-tools,binarywang/weixin-java-tools,Wechat-Group/WxJava
package me.chanjar.weixin.mp.api.test; import com.thoughtworks.xstream.annotations.XStreamAlias; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.concurrent.locks.Lock; @XStreamAlias("xml") public class TestConfigStorage extends WxMpInMemoryConfigStorage { private String openid; private String kfAccount; private String qrconnectRedirectUrl; private String templateId; private String keyPath; public String getKeyPath() { return keyPath; } public void setKeyPath(String keyPath) { this.keyPath = keyPath; } public String getOpenid() { return this.openid; } public void setOpenid(String openid) { this.openid = openid; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public String getKfAccount() { return this.kfAccount; } public void setKfAccount(String kfAccount) { this.kfAccount = kfAccount; } public String getQrconnectRedirectUrl() { return this.qrconnectRedirectUrl; } public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) { this.qrconnectRedirectUrl = qrconnectRedirectUrl; } @Override public String getTemplateId() { return this.templateId; } @Override public void setTemplateId(String templateId) { this.templateId = templateId; } public void setAccessTokenLock(Lock lock) { super.accessTokenLock = lock; } }
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/TestConfigStorage.java
package me.chanjar.weixin.mp.api.test; import com.thoughtworks.xstream.annotations.XStreamAlias; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.concurrent.locks.Lock; @XStreamAlias("xml") public class TestConfigStorage extends WxMpInMemoryConfigStorage { private String openid; private String kfAccount; private String qrconnectRedirectUrl; private String templateId; private String keyPath; public String getKeyPath() { return keyPath; } public void setKeyPath(String keyPath) { this.keyPath = keyPath; } public String getOpenid() { return this.openid; } public void setOpenid(String openid) { this.openid = openid; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public String getKfAccount() { return this.kfAccount; } public void setKfAccount(String kfAccount) { this.kfAccount = kfAccount; } public String getQrconnectRedirectUrl() { return this.qrconnectRedirectUrl; } public void setQrconnectRedirectUrl(String qrconnectRedirectUrl) { this.qrconnectRedirectUrl = qrconnectRedirectUrl; } public String getTemplateId() { return this.templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public void setAccessTokenLock(Lock lock) { super.accessTokenLock = lock; } }
fix code
weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/TestConfigStorage.java
fix code
<ide><path>eixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/TestConfigStorage.java <ide> this.qrconnectRedirectUrl = qrconnectRedirectUrl; <ide> } <ide> <add> @Override <ide> public String getTemplateId() { <ide> return this.templateId; <ide> } <ide> <add> @Override <ide> public void setTemplateId(String templateId) { <ide> this.templateId = templateId; <ide> }
Java
mit
338488b156de110ed5455c29de648b2bc9262b1c
0
razorpay/razorpay-java
package com.razorpay; import java.util.List; import org.json.JSONObject; public class OrderClient extends ApiClient { OrderClient(String auth) { super(auth); } public Order create(JSONObject request) throws RazorpayException { return post(Constants.ORDER_CREATE, request); } public List<Order> fetchAll() throws RazorpayException { return fetchAll(null); } public List<Order> fetchAll(JSONObject request) throws RazorpayException { return getCollection(Constants.ORDER_LIST, request); } public Order fetch(String id) throws RazorpayException { return get(String.format(Constants.ORDER_GET, id), null); } public List<Payment> fetchPayments(String id) throws RazorpayException { return getCollection(String.format(Constants.ORDER_PAYMENT_LIST, id), null); } }
src/main/java/com/razorpay/OrderClient.java
package com.razorpay; import java.util.List; import org.json.JSONObject; public class OrderClient extends ApiClient { OrderClient(String auth) { super(auth); } public Order create(JSONObject request) throws RazorpayException { return post(Constants.ORDER_CREATE, request); } public List<Order> fetchAll(JSONObject request) throws RazorpayException { return getCollection(Constants.ORDER_LIST, request); } public Order fetch(String id) throws RazorpayException { return get(String.format(Constants.ORDER_GET, id), null); } public List<Payment> fetchPayments(String id) throws RazorpayException { return getCollection(String.format(Constants.ORDER_PAYMENT_LIST, id), null); } }
Adding fetchAll() method in OrderClient
src/main/java/com/razorpay/OrderClient.java
Adding fetchAll() method in OrderClient
<ide><path>rc/main/java/com/razorpay/OrderClient.java <ide> return post(Constants.ORDER_CREATE, request); <ide> } <ide> <add> public List<Order> fetchAll() throws RazorpayException { <add> return fetchAll(null); <add> } <add> <ide> public List<Order> fetchAll(JSONObject request) throws RazorpayException { <ide> return getCollection(Constants.ORDER_LIST, request); <ide> }
Java
apache-2.0
ff48ce10f98aedebd6e99270cc067a4a677a8cba
0
irudyak/java-driver,ptnapoleon/java-driver,tolbertam/java-driver,amasta/java-driver,spodkowinski/java-driver,adejanovski/java-driver,csm/java-driver,pingtimeout/java-driver,ptnapoleon/java-driver,adejanovski/java-driver,mcanini/java-driver,bsideup/java-driver,techkrish/java-driver,kjniemi/java-driver,bsideup/java-driver,beckje01/java-driver,irudyak/java-driver,newkek/java-driver,techkrish/java-driver,normanmaurer/java-driver,fromanator/java-driver,techkrish/java-driver,joeljacobson/java-driver,mebigfatguy/java-driver,a-burylov/java-driver,irudyak/java-driver,codefollower/Cassandra-Java-Driver-Research,mcanini/java-driver,amasta/java-driver,newkek/java-driver,adejanovski/java-driver,tommystendahl/java-driver,cesarmarinhorj/java-driver,mebigfatguy/java-driver,newkek/java-driver,normanmaurer/java-driver,DICL/cassandra-driver,mashuai/Cassandra-Java-Driver-Research,joeljacobson/java-driver,pingtimeout/java-driver,beckje01/java-driver,mike-tr-adamson/java-driver,adutra/java-driver,tommystendahl/java-driver,pkdevbox/java-driver,amasta/java-driver,fengshao0907/Cassandra-Java-Driver-Research,codefollower/Cassandra-Java-Driver-Research,a-burylov/java-driver,ptnapoleon/java-driver,adutra/java-driver,spodkowinski/java-driver,cesarmarinhorj/java-driver,codefollower/Cassandra-Java-Driver-Research,mcanini/java-driver,bsideup/java-driver,joeljacobson/java-driver,adutra/java-driver,cesarmarinhorj/java-driver,mike-tr-adamson/java-driver,kjniemi/java-driver,fengshao0907/Cassandra-Java-Driver-Research,mashuai/Cassandra-Java-Driver-Research,tolbertam/java-driver,fromanator/java-driver,csm/java-driver,beckje01/java-driver,pkdevbox/java-driver,kjniemi/java-driver,pingtimeout/java-driver,fengshao0907/Cassandra-Java-Driver-Research,fromanator/java-driver,csm/java-driver,DICL/cassandra-driver,tommystendahl/java-driver,spodkowinski/java-driver,mike-tr-adamson/java-driver,mebigfatguy/java-driver,normanmaurer/java-driver,tolbertam/java-driver,DICL/cassandra-driver,mashuai/Cassandra-Java-Driver-Research,pkdevbox/java-driver,a-burylov/java-driver
/* * Copyright (C) 2012-2014 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.core; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.exceptions.AuthenticationException; class HostConnectionPool { private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class); private static final int MAX_SIMULTANEOUS_CREATION = 1; // When a request timeout, we may never release its stream ID. So over time, a given connection // may get less an less available streams. When the number of available ones go below the // following threshold, we just replace the connection by a new one. private static final int MIN_AVAILABLE_STREAMS = 96; public final Host host; public volatile HostDistance hostDistance; private final SessionManager manager; final List<PooledConnection> connections; private final AtomicInteger open; private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); private volatile int waiter = 0; private final Lock waitLock = new ReentrantLock(true); private final Condition hasAvailableConnection = waitLock.newCondition(); private final Runnable newConnectionTask; private final AtomicInteger scheduledForCreation = new AtomicInteger(); private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { assert hostDistance != HostDistance.IGNORED; this.host = host; this.hostDistance = hostDistance; this.manager = manager; this.newConnectionTask = new Runnable() { @Override public void run() { addConnectionIfUnderMaximum(); scheduledForCreation.decrementAndGet(); } }; // Create initial core connections List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance)); try { for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) l.add(manager.connectionFactory().open(this)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // If asked to interrupt, we can skip opening core connections, the pool will still work. // But we ignore otherwise cause I'm not sure we can do much better currently. } catch (ConnectionException e) { forceClose(l); throw e; } catch (UnsupportedProtocolVersionException e) { forceClose(l); throw e; } catch (ClusterNameMismatchException e) { forceClose(l); throw e; } catch (RuntimeException e) { forceClose(l); throw e; } this.connections = new CopyOnWriteArrayList<PooledConnection>(l); this.open = new AtomicInteger(connections.size()); logger.trace("Created connection pool to host {}", host); } // Clean up if we got an error at construction time but still created part of the core connections private void forceClose(List<PooledConnection> l) { for (PooledConnection connection : l) { connection.closeAsync().force(); } } private PoolingOptions options() { return manager.configuration().getPoolingOptions(); } public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { if (isClosed()) // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host. // That being said, maybe having a specific exception could be cleaner. throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); if (connections.isEmpty()) { for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to // protect against creating connection in excess of core too quickly scheduledForCreation.incrementAndGet(); manager.blockingExecutor().submit(newConnectionTask); } PooledConnection c = waitForConnection(timeout, unit); c.setKeyspace(manager.poolsState.keyspace); return c; } int minInFlight = Integer.MAX_VALUE; PooledConnection leastBusy = null; for (PooledConnection connection : connections) { int inFlight = connection.inFlight.get(); if (inFlight < minInFlight) { minInFlight = inFlight; leastBusy = connection; } } if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance)) maybeSpawnNewConnection(); if (leastBusy == null) { // We could have raced with a shutdown since the last check if (isClosed()) throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between // the previous check to connections and now. But in that case, the line above will have trigger the creation of // a new connection, so just wait that connection and move on leastBusy = waitForConnection(timeout, unit); } else { while (true) { int inFlight = leastBusy.inFlight.get(); if (inFlight >= leastBusy.maxAvailableStreams()) { leastBusy = waitForConnection(timeout, unit); break; } if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) break; } } leastBusy.setKeyspace(manager.poolsState.keyspace); return leastBusy; } private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException { waitLock.lock(); waiter++; try { hasAvailableConnection.await(timeout, unit); } finally { waiter--; waitLock.unlock(); } } private void signalAvailableConnection() { // Quick check if it's worth signaling to avoid locking if (waiter == 0) return; waitLock.lock(); try { hasAvailableConnection.signal(); } finally { waitLock.unlock(); } } private void signalAllAvailableConnection() { // Quick check if it's worth signaling to avoid locking if (waiter == 0) return; waitLock.lock(); try { hasAvailableConnection.signalAll(); } finally { waitLock.unlock(); } } private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { if (timeout == 0) throw new TimeoutException(); long start = System.nanoTime(); long remaining = timeout; do { try { awaitAvailableConnection(remaining, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // If we're interrupted fine, check if there is a connection available but stop waiting otherwise timeout = 0; // this will make us stop the loop if we don't get a connection right away } if (isClosed()) throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); int minInFlight = Integer.MAX_VALUE; PooledConnection leastBusy = null; for (PooledConnection connection : connections) { int inFlight = connection.inFlight.get(); if (inFlight < minInFlight) { minInFlight = inFlight; leastBusy = connection; } } // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next // iteration anyway if (leastBusy != null) { while (true) { int inFlight = leastBusy.inFlight.get(); if (inFlight >= leastBusy.maxAvailableStreams()) break; if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) return leastBusy; } } remaining = timeout - Cluster.timeSince(start, unit); } while (remaining > 0); throw new TimeoutException(); } public void returnConnection(PooledConnection connection) { int inFlight = connection.inFlight.decrementAndGet(); if (isClosed()) { close(connection); return; } if (connection.isDefunct()) { // As part of making it defunct, we have already replaced it or // closed the pool. return; } if (trash.contains(connection)) { if (inFlight == 0 && trash.remove(connection)) close(connection); } else { if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) { trashConnection(connection); } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { replaceConnection(connection); } else { signalAvailableConnection(); } } } // Trash the connection and create a new one, but we don't call trashConnection // directly because we want to make sure the connection is always trashed. private void replaceConnection(PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); maybeSpawnNewConnection(); doTrashConnection(connection); } private boolean trashConnection(PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) { // First, make sure we don't go below core connections for (;;) { int opened = open.get(); if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { connection.markForTrash.set(false); return false; } if (open.compareAndSet(opened, opened - 1)) break; } doTrashConnection(connection); } // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection. // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do // it: // - the current thread decremented inFlight in returnConnection // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))` // in returnConnection and not arrived here. // - so the other thread will see the up-to-date value of inFlight and take appropriate action. return true; } private void doTrashConnection(PooledConnection connection) { trash.add(connection); connections.remove(connection); if (connection.inFlight.get() == 0 && trash.remove(connection)) close(connection); } private boolean addConnectionIfUnderMaximum() { // First, make sure we don't cross the allowed limit of open connections for(;;) { int opened = open.get(); if (opened >= options().getMaxConnectionsPerHost(hostDistance)) return false; if (open.compareAndSet(opened, opened + 1)) break; } if (isClosed()) { open.decrementAndGet(); return false; } // Now really open the connection try { connections.add(manager.connectionFactory().open(this)); signalAvailableConnection(); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Skip the open but ignore otherwise open.decrementAndGet(); return false; } catch (ConnectionException e) { open.decrementAndGet(); logger.debug("Connection error to {} while creating additional connection", host); return false; } catch (AuthenticationException e) { // This shouldn't really happen in theory open.decrementAndGet(); logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage()); return false; } catch (UnsupportedProtocolVersionException e) { // This shouldn't happen since we shouldn't have been able to connect in the first place open.decrementAndGet(); logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage()); return false; } catch (ClusterNameMismatchException e) { open.decrementAndGet(); logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage()); return false; } } private void maybeSpawnNewConnection() { while (true) { int inCreation = scheduledForCreation.get(); if (inCreation >= MAX_SIMULTANEOUS_CREATION) return; if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1)) break; } logger.debug("Creating new connection on busy pool to {}", host); manager.blockingExecutor().submit(newConnectionTask); } void replaceDefunctConnection(final PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); connections.remove(connection); connection.closeAsync(); manager.blockingExecutor().submit(new Runnable() { @Override public void run() { addConnectionIfUnderMaximum(); } }); } private void close(final Connection connection) { connection.closeAsync(); } public boolean isClosed() { return closeFuture.get() != null; } public CloseFuture closeAsync() { CloseFuture future = closeFuture.get(); if (future != null) return future; // Wake up all threads that waits signalAllAvailableConnection(); future = new CloseFuture.Forwarding(discardAvailableConnections()); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); // We raced, it's ok, return the future that was actually set } public int opened() { return open.get(); } private List<CloseFuture> discardAvailableConnections() { // This can happen if creating the connections in the constructor fails if (connections == null) return Lists.newArrayList(CloseFuture.immediateFuture()); List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size()); for (final PooledConnection connection : connections) { CloseFuture future = connection.closeAsync(); future.addListener(new Runnable() { public void run() { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); } }, MoreExecutors.sameThreadExecutor()); futures.add(future); } return futures; } // This creates connections if we have less than core connections (if we // have more than core, connection will just get trash when we can). public void ensureCoreConnections() { if (isClosed()) return; // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create // more connection than maximum (and if we create more than core connection due to a race but this isn't // justified by the load, the connection in excess will be quickly trashed anyway) int opened = open.get(); for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) { // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to // protect against creating connection in excess of core too quickly scheduledForCreation.incrementAndGet(); manager.blockingExecutor().submit(newConnectionTask); } } static class PoolState { volatile String keyspace; public void setKeyspace(String keyspace) { this.keyspace = keyspace; } } }
driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java
/* * Copyright (C) 2012-2014 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.core; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.exceptions.AuthenticationException; class HostConnectionPool { private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class); private static final int MAX_SIMULTANEOUS_CREATION = 1; // When a request timeout, we may never release its stream ID. So over time, a given connection // may get less an less available streams. When the number of available ones go below the // following threshold, we just replace the connection by a new one. private static final int MIN_AVAILABLE_STREAMS = 96; public final Host host; public volatile HostDistance hostDistance; private final SessionManager manager; final List<PooledConnection> connections; private final AtomicInteger open; private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); private volatile int waiter = 0; private final Lock waitLock = new ReentrantLock(true); private final Condition hasAvailableConnection = waitLock.newCondition(); private final Runnable newConnectionTask; private final AtomicInteger scheduledForCreation = new AtomicInteger(); private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { assert hostDistance != HostDistance.IGNORED; this.host = host; this.hostDistance = hostDistance; this.manager = manager; this.newConnectionTask = new Runnable() { @Override public void run() { addConnectionIfUnderMaximum(); scheduledForCreation.decrementAndGet(); } }; // Create initial core connections List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance)); try { for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) l.add(manager.connectionFactory().open(this)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // If asked to interrupt, we can skip opening core connections, the pool will still work. // But we ignore otherwise cause I'm not sure we can do much better currently. } catch (ConnectionException e) { forceClose(l); throw e; } catch (UnsupportedProtocolVersionException e) { forceClose(l); throw e; } catch (ClusterNameMismatchException e) { forceClose(l); throw e; } catch (RuntimeException e) { forceClose(l); throw e; } this.connections = new CopyOnWriteArrayList<PooledConnection>(l); this.open = new AtomicInteger(connections.size()); logger.trace("Created connection pool to host {}", host); } // Clean up if we got an error at construction time but still created part of the core connections private void forceClose(List<PooledConnection> l) { for (PooledConnection connection : l) { connection.closeAsync().force(); } } private PoolingOptions options() { return manager.configuration().getPoolingOptions(); } public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { if (isClosed()) // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host. // That being said, maybe having a specific exception could be cleaner. throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); if (connections.isEmpty()) { for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) { // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to // protect against creating connection in excess of core too quickly scheduledForCreation.incrementAndGet(); manager.blockingExecutor().submit(newConnectionTask); } PooledConnection c = waitForConnection(timeout, unit); c.setKeyspace(manager.poolsState.keyspace); return c; } int minInFlight = Integer.MAX_VALUE; PooledConnection leastBusy = null; for (PooledConnection connection : connections) { int inFlight = connection.inFlight.get(); if (inFlight < minInFlight) { minInFlight = inFlight; leastBusy = connection; } } if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance)) maybeSpawnNewConnection(); if (leastBusy == null) { // We could have raced with a shutdown since the last check if (isClosed()) throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between // the previous check to connections and now. But in that case, the line above will have trigger the creation of // a new connection, so just wait that connection and move on leastBusy = waitForConnection(timeout, unit); } else { while (true) { int inFlight = leastBusy.inFlight.get(); if (inFlight >= leastBusy.maxAvailableStreams()) { leastBusy = waitForConnection(timeout, unit); break; } if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) break; } } leastBusy.setKeyspace(manager.poolsState.keyspace); return leastBusy; } private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException { waitLock.lock(); waiter++; try { hasAvailableConnection.await(timeout, unit); } finally { waiter--; waitLock.unlock(); } } private void signalAvailableConnection() { // Quick check if it's worth signaling to avoid locking if (waiter == 0) return; waitLock.lock(); try { hasAvailableConnection.signal(); } finally { waitLock.unlock(); } } private void signalAllAvailableConnection() { // Quick check if it's worth signaling to avoid locking if (waiter == 0) return; waitLock.lock(); try { hasAvailableConnection.signalAll(); } finally { waitLock.unlock(); } } private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { if (timeout == 0) throw new TimeoutException(); long start = System.nanoTime(); long remaining = timeout; do { try { awaitAvailableConnection(remaining, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // If we're interrupted fine, check if there is a connection available but stop waiting otherwise timeout = 0; // this will make us stop the loop if we don't get a connection right away } if (isClosed()) throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); int minInFlight = Integer.MAX_VALUE; PooledConnection leastBusy = null; for (PooledConnection connection : connections) { int inFlight = connection.inFlight.get(); if (inFlight < minInFlight) { minInFlight = inFlight; leastBusy = connection; } } // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next // iteration anyway if (leastBusy != null) { while (true) { int inFlight = leastBusy.inFlight.get(); if (inFlight >= leastBusy.maxAvailableStreams()) break; if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) return leastBusy; } } remaining = timeout - Cluster.timeSince(start, unit); } while (remaining > 0); throw new TimeoutException(); } public void returnConnection(PooledConnection connection) { if (isClosed()) { close(connection); return; } if (connection.isDefunct()) { // As part of making it defunct, we have already replaced it or // closed the pool. return; } int inFlight = connection.inFlight.decrementAndGet(); if (trash.contains(connection)) { if (inFlight == 0 && trash.remove(connection)) close(connection); } else { if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) { trashConnection(connection); } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { replaceConnection(connection); } else { signalAvailableConnection(); } } } // Trash the connection and create a new one, but we don't call trashConnection // directly because we want to make sure the connection is always trashed. private void replaceConnection(PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); maybeSpawnNewConnection(); doTrashConnection(connection); } private boolean trashConnection(PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) { // First, make sure we don't go below core connections for (;;) { int opened = open.get(); if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { connection.markForTrash.set(false); return false; } if (open.compareAndSet(opened, opened - 1)) break; } doTrashConnection(connection); } // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection. // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do // it: // - the current thread decremented inFlight in returnConnection // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))` // in returnConnection and not arrived here. // - so the other thread will see the up-to-date value of inFlight and take appropriate action. return true; } private void doTrashConnection(PooledConnection connection) { trash.add(connection); connections.remove(connection); if (connection.inFlight.get() == 0 && trash.remove(connection)) close(connection); } private boolean addConnectionIfUnderMaximum() { // First, make sure we don't cross the allowed limit of open connections for(;;) { int opened = open.get(); if (opened >= options().getMaxConnectionsPerHost(hostDistance)) return false; if (open.compareAndSet(opened, opened + 1)) break; } if (isClosed()) { open.decrementAndGet(); return false; } // Now really open the connection try { connections.add(manager.connectionFactory().open(this)); signalAvailableConnection(); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Skip the open but ignore otherwise open.decrementAndGet(); return false; } catch (ConnectionException e) { open.decrementAndGet(); logger.debug("Connection error to {} while creating additional connection", host); return false; } catch (AuthenticationException e) { // This shouldn't really happen in theory open.decrementAndGet(); logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage()); return false; } catch (UnsupportedProtocolVersionException e) { // This shouldn't happen since we shouldn't have been able to connect in the first place open.decrementAndGet(); logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage()); return false; } catch (ClusterNameMismatchException e) { open.decrementAndGet(); logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage()); return false; } } private void maybeSpawnNewConnection() { while (true) { int inCreation = scheduledForCreation.get(); if (inCreation >= MAX_SIMULTANEOUS_CREATION) return; if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1)) break; } logger.debug("Creating new connection on busy pool to {}", host); manager.blockingExecutor().submit(newConnectionTask); } void replaceDefunctConnection(final PooledConnection connection) { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); connections.remove(connection); connection.closeAsync(); manager.blockingExecutor().submit(new Runnable() { @Override public void run() { addConnectionIfUnderMaximum(); } }); } private void close(final Connection connection) { connection.closeAsync(); } public boolean isClosed() { return closeFuture.get() != null; } public CloseFuture closeAsync() { CloseFuture future = closeFuture.get(); if (future != null) return future; // Wake up all threads that waits signalAllAvailableConnection(); future = new CloseFuture.Forwarding(discardAvailableConnections()); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); // We raced, it's ok, return the future that was actually set } public int opened() { return open.get(); } private List<CloseFuture> discardAvailableConnections() { // This can happen if creating the connections in the constructor fails if (connections == null) return Lists.newArrayList(CloseFuture.immediateFuture()); List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size()); for (final PooledConnection connection : connections) { CloseFuture future = connection.closeAsync(); future.addListener(new Runnable() { public void run() { if (connection.markForTrash.compareAndSet(false, true)) open.decrementAndGet(); } }, MoreExecutors.sameThreadExecutor()); futures.add(future); } return futures; } // This creates connections if we have less than core connections (if we // have more than core, connection will just get trash when we can). public void ensureCoreConnections() { if (isClosed()) return; // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create // more connection than maximum (and if we create more than core connection due to a race but this isn't // justified by the load, the connection in excess will be quickly trashed anyway) int opened = open.get(); for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) { // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to // protect against creating connection in excess of core too quickly scheduledForCreation.incrementAndGet(); manager.blockingExecutor().submit(newConnectionTask); } } static class PoolState { volatile String keyspace; public void setKeyspace(String keyspace) { this.keyspace = keyspace; } } }
Decrement connection.inFlight even if pool is closed.
driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java
Decrement connection.inFlight even if pool is closed.
<ide><path>river-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java <ide> } <ide> <ide> public void returnConnection(PooledConnection connection) { <add> int inFlight = connection.inFlight.decrementAndGet(); <add> <ide> if (isClosed()) { <ide> close(connection); <ide> return; <ide> // closed the pool. <ide> return; <ide> } <del> <del> int inFlight = connection.inFlight.decrementAndGet(); <ide> <ide> if (trash.contains(connection)) { <ide> if (inFlight == 0 && trash.remove(connection))
Java
agpl-3.0
ea8b82d7fcb5c6b2f32b070d465ad13ab482e2f8
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.elki.distance.distancefunction; /* This file is part of ELKI: Environment for Developing KDD-Applications Supported by Index-Structures Copyright (C) 2011 Ludwig-Maximilians-Universität München Lehr- und Forschungseinheit für Datenbanksysteme ELKI Development Team This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.List; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.database.QueryUtil; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.query.DatabaseQuery; import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair; import de.lmu.ifi.dbs.elki.database.query.distance.AbstractDatabaseDistanceQuery; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.DistanceUtil; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter; /** * A distance that is at least the distance to the kth nearest neighbor. * * This is essentially the "reachability distance" of LOF, but with arguments * reversed! * * Reachability of B <em>from</em> A, i.e. * * <pre> * reachability-distance(A,B) = max( k-distance(A), distance(A,B) ) * </pre> * * Where <tt>k-distance(A)</tt> is the distance to the k nearest neighbor of A, * and <tt>distance</tt> is the actual distance of A and B. * * This distance is NOT symmetric. You need to pay attention to the order of * arguments! * * @author Erich Schubert * * @apiviz.uses DistanceFunction * @apiviz.has MinKDistance.Instance * * @param <O> Database object type * @param <D> Distance type */ public class MinKDistance<O, D extends Distance<D>> extends AbstractDatabaseDistanceFunction<O, D> { /** * OptionID for the base distance used to compute reachability */ public static final OptionID DISTANCE_FUNCTION_ID = OptionID.getOrCreateOptionID("reachdist.basedistance", "Base distance function to use."); /** * OptionID for the KNN query class to use (preprocessor, approximation, ...) */ public static final OptionID KNNQUERY_ID = OptionID.getOrCreateOptionID("reachdist.knnquery", "kNN query to use"); /** * OptionID for the "k" parameter. */ public static final OptionID K_ID = OptionID.getOrCreateOptionID("reachdist.k", "The number of nearest neighbors of an object to be considered for computing its reachability distance."); /** * The distance function to determine the exact distance. */ protected DistanceFunction<? super O, D> parentDistance; /** * The value of k */ private int k; /** * Include object itself in kNN neighborhood. * * In the official LOF publication, the point itself is not considered to be * part of its k nearest neighbors. */ static boolean objectIsInKNN = false; /** * Full constructor. See {@link Parameterizer} for factory. * * @param parentDistance distance function to use * @param k K parameter */ public MinKDistance(DistanceFunction<? super O, D> parentDistance, int k) { super(); this.parentDistance = parentDistance; this.k = k; } @Override public <T extends O> DistanceQuery<T, D> instantiate(Relation<T> relation) { return new Instance<T>(relation, k, parentDistance); } /** * Instance for an actual database. * * @author Erich Schubert * * @apiviz.uses KNNQuery */ public class Instance<T extends O> extends AbstractDatabaseDistanceQuery<T, D> { /** * KNN query instance */ private KNNQuery<T, D> knnQuery; /** * Value for k */ private int k; /** * Constructor. * * @param relation Database * @param k Value of k */ public Instance(Relation<T> relation, int k, DistanceFunction<? super O, D> parentDistance) { super(relation); this.k = k; this.knnQuery = QueryUtil.getKNNQuery(relation, parentDistance, k, DatabaseQuery.HINT_HEAVY_USE); } @Override public D distance(DBID id1, DBID id2) { List<DistanceResultPair<D>> neighborhood = knnQuery.getKNNForDBID(id1, k); D truedist = knnQuery.getDistanceQuery().distance(id1, id2); return computeReachdist(neighborhood, truedist); } @Override public DistanceFunction<? super T, D> getDistanceFunction() { return MinKDistance.this; } } /** * Actually compute the distance, whichever way we obtained the neighborhood * above. * * @param neighborhood Neighborhood * @param truedist True distance * @return Reachability distance */ protected D computeReachdist(List<DistanceResultPair<D>> neighborhood, D truedist) { // TODO: need to check neighborhood size? // TODO: Do we need to check we actually got the object itself in the // neighborhood? D kdist = neighborhood.get(neighborhood.size() - 1).getDistance(); return DistanceUtil.max(kdist, truedist); } @Override public boolean isMetric() { return false; } @Override public boolean isSymmetric() { return false; } @Override public D getDistanceFactory() { return parentDistance.getDistanceFactory(); } @Override public TypeInformation getInputTypeRestriction() { return parentDistance.getInputTypeRestriction(); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if (!this.getClass().equals(obj.getClass())) { return false; } MinKDistance<?,?> other = (MinKDistance<?, ?>) obj; return this.parentDistance.equals(other.parentDistance) && this.k == other.k; } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer<O, D extends Distance<D>> extends AbstractParameterizer { /** * The distance function to determine the exact distance. */ protected DistanceFunction<? super O, D> parentDistance = null; /** * The value of k */ private int k = 0; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); final IntParameter kP = new IntParameter(K_ID, new GreaterConstraint(1)); if(config.grab(kP)) { k = kP.getValue(); } final ObjectParameter<DistanceFunction<? super O, D>> parentDistanceP = new ObjectParameter<DistanceFunction<? super O, D>>(DISTANCE_FUNCTION_ID, DistanceFunction.class, EuclideanDistanceFunction.class); if (config.grab(parentDistanceP)) { parentDistance = parentDistanceP.instantiateClass(config); } } @Override protected MinKDistance<O, D> makeInstance() { return new MinKDistance<O, D>(parentDistance, k + (objectIsInKNN ? 0 : 1)); } } }
src/de/lmu/ifi/dbs/elki/distance/distancefunction/MinKDistance.java
package de.lmu.ifi.dbs.elki.distance.distancefunction; /* This file is part of ELKI: Environment for Developing KDD-Applications Supported by Index-Structures Copyright (C) 2011 Ludwig-Maximilians-Universität München Lehr- und Forschungseinheit für Datenbanksysteme ELKI Development Team This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.List; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.database.QueryUtil; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.query.DatabaseQuery; import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair; import de.lmu.ifi.dbs.elki.database.query.distance.AbstractDatabaseDistanceQuery; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.DistanceUtil; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter; /** * A distance that is at least the distance to the kth nearest neighbor. * * This is essentially the "reachability distance" of LOF, but with arguments * reversed! * * Reachability of B <em>from</em> A, i.e. * * <pre> * reachability-distance(A,B) = max( k-distance(A), distance(A,B) ) * </pre> * * Where <tt>k-distance(A)</tt> is the distance to the k nearest neighbor of A, * and <tt>distance</tt> is the actual distance of A and B. * * This distance is NOT symmetric. You need to pay attention to the order of * arguments! * * @author Erich Schubert * * @apiviz.uses DistanceFunction * @apiviz.has MinKDistance.Instance * * @param <O> Database object type * @param <D> Distance type */ public class MinKDistance<O, D extends Distance<D>> extends AbstractDatabaseDistanceFunction<O, D> { /** * OptionID for the base distance used to compute reachability */ public static final OptionID DISTANCE_FUNCTION_ID = OptionID.getOrCreateOptionID("reachdist.basedistance", "Base distance function to use."); /** * OptionID for the KNN query class to use (preprocessor, approximation, ...) */ public static final OptionID KNNQUERY_ID = OptionID.getOrCreateOptionID("reachdist.knnquery", "kNN query to use"); /** * OptionID for the "k" parameter. */ public static final OptionID K_ID = OptionID.getOrCreateOptionID("reachdist.k", "The number of nearest neighbors of an object to be considered for computing its reachability distance."); /** * The distance function to determine the exact distance. */ protected DistanceFunction<? super O, D> parentDistance; /** * The value of k */ private int k; /** * Include object itself in kNN neighborhood. * * In the official LOF publication, the point itself is not considered to be * part of its k nearest neighbors. */ static boolean objectIsInKNN = false; /** * Full constructor. See {@link Parameterizer} for factory. * * @param parentDistance distance function to use * @param k K parameter */ public MinKDistance(DistanceFunction<? super O, D> parentDistance, int k) { super(); this.parentDistance = parentDistance; this.k = k; } @Override public <T extends O> DistanceQuery<T, D> instantiate(Relation<T> relation) { return new Instance<T>(relation, k, parentDistance); } /** * Instance for an actual database. * * @author Erich Schubert * * @apiviz.use KNNQuery */ public class Instance<T extends O> extends AbstractDatabaseDistanceQuery<T, D> { /** * KNN query instance */ private KNNQuery<T, D> knnQuery; /** * Value for k */ private int k; /** * Constructor. * * @param relation Database * @param k Value of k */ public Instance(Relation<T> relation, int k, DistanceFunction<? super O, D> parentDistance) { super(relation); this.k = k; this.knnQuery = QueryUtil.getKNNQuery(relation, parentDistance, k, DatabaseQuery.HINT_HEAVY_USE); } @Override public D distance(DBID id1, DBID id2) { List<DistanceResultPair<D>> neighborhood = knnQuery.getKNNForDBID(id1, k); D truedist = knnQuery.getDistanceQuery().distance(id1, id2); return computeReachdist(neighborhood, truedist); } @Override public DistanceFunction<? super T, D> getDistanceFunction() { return MinKDistance.this; } } /** * Actually compute the distance, whichever way we obtained the neighborhood * above. * * @param neighborhood Neighborhood * @param truedist True distance * @return Reachability distance */ protected D computeReachdist(List<DistanceResultPair<D>> neighborhood, D truedist) { // TODO: need to check neighborhood size? // TODO: Do we need to check we actually got the object itself in the // neighborhood? D kdist = neighborhood.get(neighborhood.size() - 1).getDistance(); return DistanceUtil.max(kdist, truedist); } @Override public boolean isMetric() { return false; } @Override public boolean isSymmetric() { return false; } @Override public D getDistanceFactory() { return parentDistance.getDistanceFactory(); } @Override public TypeInformation getInputTypeRestriction() { return parentDistance.getInputTypeRestriction(); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if (!this.getClass().equals(obj.getClass())) { return false; } MinKDistance<?,?> other = (MinKDistance<?, ?>) obj; return this.parentDistance.equals(other.parentDistance) && this.k == other.k; } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer<O, D extends Distance<D>> extends AbstractParameterizer { /** * The distance function to determine the exact distance. */ protected DistanceFunction<? super O, D> parentDistance = null; /** * The value of k */ private int k = 0; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); final IntParameter kP = new IntParameter(K_ID, new GreaterConstraint(1)); if(config.grab(kP)) { k = kP.getValue(); } final ObjectParameter<DistanceFunction<? super O, D>> parentDistanceP = new ObjectParameter<DistanceFunction<? super O, D>>(DISTANCE_FUNCTION_ID, DistanceFunction.class, EuclideanDistanceFunction.class); if (config.grab(parentDistanceP)) { parentDistance = parentDistanceP.instantiateClass(config); } } @Override protected MinKDistance<O, D> makeInstance() { return new MinKDistance<O, D>(parentDistance, k + (objectIsInKNN ? 0 : 1)); } } }
JavaDoc, ApiViz.
src/de/lmu/ifi/dbs/elki/distance/distancefunction/MinKDistance.java
JavaDoc, ApiViz.
<ide><path>rc/de/lmu/ifi/dbs/elki/distance/distancefunction/MinKDistance.java <ide> * <ide> * @author Erich Schubert <ide> * <del> * @apiviz.use KNNQuery <add> * @apiviz.uses KNNQuery <ide> */ <ide> public class Instance<T extends O> extends AbstractDatabaseDistanceQuery<T, D> { <ide> /**
Java
bsd-3-clause
a1bd6d848aa066fda112a06fada6ad56cc0c7eb8
0
sebastiangraf/treetank,sebastiangraf/treetank,sebastiangraf/treetank
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group All * rights reserved. Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of * the University of Konstanz nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior * written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.jscsi; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import org.treetank.CoreTestHelper; import org.treetank.ModuleFactory; import org.treetank.access.conf.ResourceConfiguration; import org.treetank.access.conf.ResourceConfiguration.IResourceConfigurationFactory; import org.treetank.access.conf.StandardSettings; import org.treetank.access.conf.StorageConfiguration; import org.treetank.exception.TTException; import com.google.inject.Inject; @Guice(moduleFactory = ModuleFactory.class) public class TreetankStorageModuleTest { private TreetankStorageModule storageModule; private StorageConfiguration configuration; private File file; @Inject private IResourceConfigurationFactory mResourceConfig; private ResourceConfiguration mResource; @BeforeClass public void setUp() throws TTException { CoreTestHelper.deleteEverything(); CoreTestHelper.Holder.generateStorage(); Properties props = StandardSettings.getProps(CoreTestHelper.PATHS.PATH1.getFile() .getAbsolutePath(), CoreTestHelper.RESOURCENAME); mResource = mResourceConfig.create(props); CoreTestHelper.createResource(mResource); file = CoreTestHelper.PATHS.PATH1.getFile(); configuration = CoreTestHelper.PATHS.PATH1.getConfig(); storageModule = new TreetankStorageModule(64, 1024*64, 4, configuration, file); } @Test(groups = "Initial read write") public void testReadAndWrite() throws TTException, IOException { final byte[] writeArray = new byte[64*1024*5]; for (int i = 0; i < 64*1024*5; ++i) writeArray[i] = (byte)(CoreTestHelper.random.nextDouble() * 256); final byte[] readArray = new byte[64*1024*5]; System.arraycopy(writeArray, 0, readArray, 0, 64*1024*5); // write storageModule.write(writeArray,// bytes (source) 50,// bytesOffset 64*1024*5 - 50,// length 80); // read storageModule.read(readArray,// bytes (destination) 50,// bytesOffset 64*1024*5 - 50,// length 80); // check for errors assertTrue(Arrays.equals(writeArray, readArray)); // byte[][] splitBytes = new byte[16][8192]; // // ByteArrayInputStream writeArrayInputStream = new ByteArrayInputStream(writeArray); // // for (int i = 0; i < splitBytes.length; i++) { // splitBytes[i] = new byte[8192]; // storageModule.read(splitBytes[i],// bytes (destination) // 0,// bytesOffset // 8192,// length // i * 16 * 512); // byte[] b = new byte[8192]; // System.out.println(i); // writeArrayInputStream.read(b, 0, 8192); // // assertTrue(Arrays.equals(splitBytes[i], b)); // } } @Test(dependsOnGroups = "Initial read write") public void testCheckBounds1() { // wrong logical block address int result = storageModule.checkBounds(-1,// logicalBlockAddress 1);// transferLengthInBlocks assertEquals(1, result); result = storageModule.checkBounds(2,// logicalBlockAddress 1);// transferLengthInBlocks assertEquals(0, result); } @Test public void testOpen() { // behavior to test is performed in setUpBeforeClass() assertTrue(storageModule != null); } }
interfacemodules/iscsi/src/test/java/org/treetank/jscsi/TreetankStorageModuleTest.java
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group All * rights reserved. Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of * the University of Konstanz nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior * written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.jscsi; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import org.treetank.CoreTestHelper; import org.treetank.ModuleFactory; import org.treetank.access.conf.ResourceConfiguration; import org.treetank.access.conf.ResourceConfiguration.IResourceConfigurationFactory; import org.treetank.access.conf.StandardSettings; import org.treetank.access.conf.StorageConfiguration; import org.treetank.exception.TTException; import com.google.inject.Inject; @Guice(moduleFactory = ModuleFactory.class) public class TreetankStorageModuleTest { private TreetankStorageModule storageModule; private StorageConfiguration configuration; private File file; @Inject private IResourceConfigurationFactory mResourceConfig; private ResourceConfiguration mResource; @BeforeClass public void setUp() throws TTException { CoreTestHelper.deleteEverything(); CoreTestHelper.Holder.generateStorage(); Properties props = StandardSettings.getProps(CoreTestHelper.PATHS.PATH1.getFile() .getAbsolutePath(), CoreTestHelper.RESOURCENAME); mResource = mResourceConfig.create(props); CoreTestHelper.createResource(mResource); file = CoreTestHelper.PATHS.PATH1.getFile(); configuration = CoreTestHelper.PATHS.PATH1.getConfig(); storageModule = new TreetankStorageModule(64, 1024*64, 32, configuration, file); } @Test(groups = "Initial read write") public void testReadAndWrite() throws TTException, IOException { final byte[] writeArray = new byte[64*1024*5]; for (int i = 0; i < 64*1024*5; ++i) writeArray[i] = (byte)(CoreTestHelper.random.nextDouble() * 256); final byte[] readArray = new byte[64*1024*5]; System.arraycopy(writeArray, 0, readArray, 0, 64*1024*5); // write storageModule.write(writeArray,// bytes (source) 50,// bytesOffset 64*1024*5 - 50,// length 80); // read storageModule.read(readArray,// bytes (destination) 50,// bytesOffset 64*1024*5 - 50,// length 80); // check for errors assertTrue(Arrays.equals(writeArray, readArray)); // byte[][] splitBytes = new byte[16][8192]; // // ByteArrayInputStream writeArrayInputStream = new ByteArrayInputStream(writeArray); // // for (int i = 0; i < splitBytes.length; i++) { // splitBytes[i] = new byte[8192]; // storageModule.read(splitBytes[i],// bytes (destination) // 0,// bytesOffset // 8192,// length // i * 16 * 512); // byte[] b = new byte[8192]; // System.out.println(i); // writeArrayInputStream.read(b, 0, 8192); // // assertTrue(Arrays.equals(splitBytes[i], b)); // } } @Test(dependsOnGroups = "Initial read write") public void testCheckBounds1() { // wrong logical block address int result = storageModule.checkBounds(-1,// logicalBlockAddress 1);// transferLengthInBlocks assertEquals(1, result); result = storageModule.checkBounds(2,// logicalBlockAddress 1);// transferLengthInBlocks assertEquals(0, result); } @Test public void testOpen() { // behavior to test is performed in setUpBeforeClass() assertTrue(storageModule != null); } }
[MOD] It seems the node size has been to big.. 1024*64*32 ~ > 1MB. Without regular commits the treetank backend will crush. Made the size a little bit smaller so the test works, but this needs to be checked further! git-svn-id: a5379eb5ca3beb2b6e029be3b1b7f6aa53f2352b@7320 e3ddb328-5bfe-0310-b762-aafcbcbd2528
interfacemodules/iscsi/src/test/java/org/treetank/jscsi/TreetankStorageModuleTest.java
[MOD] It seems the node size has been to big.. 1024*64*32 ~ > 1MB. Without regular commits the treetank backend will crush. Made the size a little bit smaller so the test works, but this needs to be checked further!
<ide><path>nterfacemodules/iscsi/src/test/java/org/treetank/jscsi/TreetankStorageModuleTest.java <ide> file = CoreTestHelper.PATHS.PATH1.getFile(); <ide> configuration = CoreTestHelper.PATHS.PATH1.getConfig(); <ide> <del> storageModule = new TreetankStorageModule(64, 1024*64, 32, configuration, file); <add> storageModule = new TreetankStorageModule(64, 1024*64, 4, configuration, file); <ide> } <ide> <ide> @Test(groups = "Initial read write")
Java
epl-1.0
91f27a6ae295ba3089345db42e2a998f8c28af0e
0
sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; import org.eclipse.birt.core.archive.FileArchiveWriter; import org.eclipse.birt.core.archive.IDocArchiveWriter; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.framework.Platform; import org.eclipse.birt.core.framework.PlatformConfig; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IRenderTask; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.IReportEngineFactory; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunAndRenderTask; import org.eclipse.birt.report.engine.api.IRunTask; import org.eclipse.birt.report.engine.api.RenderOptionBase; import org.eclipse.birt.report.engine.api.ReportRunner; /** * Base class for Engine test. * */ public abstract class EngineCase extends TestCase { private String caseName; protected static final String BUNDLE_NAME = "org.eclipse.birt.report.tests.engine.messages";//$NON-NLS-1$ protected static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle( BUNDLE_NAME ); protected static final String PLUGIN_NAME = "org.eclipse.birt.report.tests.engine"; //$NON-NLS-1$ protected static final String PLUGINLOC = "/org.eclipse.birt.report.tests.engine/"; //$NON-NLS-1$ protected static final String PLUGIN_PATH = System.getProperty( "user.dir" ) //$NON-NLS-1$ + "/plugins/" + PLUGINLOC.substring( PLUGINLOC.indexOf( "/" ) + 1 ) //$NON-NLS-1$//$NON-NLS-2$ + "bin/"; //$NON-NLS-1$ protected static final String TEST_FOLDER = "src/"; //$NON-NLS-1$ protected static final String OUTPUT_FOLDER = "output"; //$NON-NLS-1$ protected static final String INPUT_FOLDER = "input"; //$NON-NLS-1$ protected static final String GOLDEN_FOLDER = "golden"; //$NON-NLS-1$ protected IReportEngine engine = null; private static final String FORMAT_HTML = "html"; //$NON-NLS-1$ private static final String ENCODING_UTF8 = "UTF-8"; //$NON-NLS-1$ private static final String IMAGE_DIR = "image"; //$NON-NLS-1$ private boolean pagination = false; //$NON-NLS-1$ /* * @see TestCase#setUp() */ protected void setUp( ) throws Exception { super.setUp( ); // IPlatformContext context = new PlatformFileContext( ); // config.setEngineContext( context ); // this.engine = new ReportEngine( config ); EngineConfig config = new EngineConfig( ); this.engine = createReportEngine( config ); } /** * Create a report engine instance. * * @throws BirtException */ public IReportEngine createReportEngine( EngineConfig config ) throws BirtException { if ( config == null ) { config = new EngineConfig( ); } Platform.startup( new PlatformConfig( ) ); // assume we has in the platform Object factory = Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); if ( factory instanceof IReportEngineFactory ) { return ( (IReportEngineFactory) factory ) .createReportEngine( config ); } return null; } /** * Constructor. */ public EngineCase( ) { super( null ); } /** * Constructor for DemoCase. * * @param name */ public EngineCase( String name ) { super( name ); } protected void setCase( String caseName ) { // set the case and emitter manager accroding to caseName. this.caseName = caseName; } protected void runCase( String args[] ) { Vector runArgs = new Vector( ); // invoke the report runner. String input = PLUGIN_PATH + System.getProperty( "file.separator" ) //$NON-NLS-1$ + RESOURCE_BUNDLE.getString( "CASE_INPUT" ); //$NON-NLS-1$ input += System.getProperty( "file.separator" ) + caseName //$NON-NLS-1$ + ".rptdesign"; //$NON-NLS-1$ System.out.println( "input is : " + input ); //$NON-NLS-1$ // run report runner. if ( args != null ) { for ( int i = 0; i < args.length; i++ ) { runArgs.add( args[i] ); } } runArgs.add( "-f" ); //$NON-NLS-1$ runArgs.add( "test" ); //$NON-NLS-1$ runArgs.add( input ); args = (String[]) runArgs.toArray( new String[runArgs.size( )] ); ReportRunner.main( args ); } /** * Make a copy of a given file to the target file. * * @param from * the file where to copy from * @param to * the target file to copy to. * @throws IOException */ protected final void copyFile( String from, String to ) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { new File( to ).createNewFile( ); bis = new BufferedInputStream( new FileInputStream( from ) ); bos = new BufferedOutputStream( new FileOutputStream( to ) ); int nextByte = 0; while ( ( nextByte = bis.read( ) ) != -1 ) { bos.write( nextByte ); } } catch ( IOException e ) { throw e; } finally { try { if ( bis != null ) bis.close( ); if ( bos != null ) bos.close( ); } catch ( IOException e ) { // ignore } } } /** * Remove a given file or directory recursively. * * @param file */ public void removeFile( File file ) { if ( file.isDirectory( ) ) { File[] children = file.listFiles( ); for ( int i = 0; i < children.length; i++ ) { removeFile( children[i] ); } } if ( file.exists( ) ) { if ( !file.delete( ) ) { System.out.println( file.toString( ) + " can't be removed" ); } } } /** * Remove a given file or directory recursively. * * @param file * */ public void removeFile( String file ) { removeFile( new File( file ) ); } /** * Locates the folder where the unit test java source file is saved. * * @return the path name where the test java source file locates. */ protected String getClassFolder( ) { String pathBase = null; ProtectionDomain domain = this.getClass( ).getProtectionDomain( ); if ( domain != null ) { CodeSource source = domain.getCodeSource( ); if ( source != null ) { URL url = source.getLocation( ); pathBase = url.getPath( ); if ( pathBase.endsWith( "bin/" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 4 ); if ( pathBase.endsWith( "bin" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 3 ); } } pathBase = pathBase + TEST_FOLDER; String className = this.getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); className = pathBase + className.replace( '.', '/' ); return className; } /** * Compares two text file. The comparison will ignore the line containing * "modificationDate". * * @param golden * the 1st file name to be compared. * @param output * the 2nd file name to be compared. * @return true if two text files are same line by line * @throws Exception * if any exception. */ protected boolean compareHTML( String golden, String output ) throws Exception { FileReader readerA = null; FileReader readerB = null; boolean same = true; StringBuffer errorText = new StringBuffer( ); try { golden = getClassFolder( ) + "/" + GOLDEN_FOLDER + "/" + golden; //$NON-NLS-1$//$NON-NLS-2$ output = getClassFolder( ) + "/" + OUTPUT_FOLDER + "/" + output; //$NON-NLS-1$//$NON-NLS-2$ readerA = new FileReader( golden ); readerB = new FileReader( output ); same = compareTextFile( readerA, readerB, output ); } catch ( IOException e ) { errorText.append( e.toString( ) ); errorText.append( "\n" ); //$NON-NLS-1$ e.printStackTrace( ); } finally { try { readerA.close( ); readerB.close( ); } catch ( Exception e ) { readerA = null; readerB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * Run and render the given design file into html file. If the input is * "a.xml", output html file will be named "a.html" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_HTML( String input, String output ) throws EngineException { this.pagination = false; runAndRender( input, output, null, "html" ); //$NON-NLS-1$ } /** * Run and render the given design file into html file with pagination. If * the input is "a.xml", output html file will be named "a.html" under * folder "output". * * @param input * @throws EngineException */ protected void runAndRender_HTMLWithPagination( String input, String output ) throws EngineException { this.pagination = true; runAndRender( input, output, null, "html" ); //$NON-NLS-1$ } /** * Run and render the given design file into pdf file. If the input is * "a.xml", output html file will be named "a.pdf" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_PDF( String input, String output ) throws EngineException { runAndRender( input, output, null, "pdf" ); //$NON-NLS-1$ } /** * RunAndRender a report with the given parameters. */ protected final void runAndRender( String input, String output, Map paramValues, String format ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + input; //$NON-NLS-1$ //$NON-NLS-2$ IReportRunnable runnable = engine.openReportDesign( inputFile ); IRunAndRenderTask task = engine.createRunAndRenderTask( runnable ); if ( paramValues != null ) { Iterator keys = paramValues.keySet( ).iterator( ); while ( keys.hasNext( ) ) { String key = (String) keys.next( ); task.setParameterValue( key, paramValues.get( key ) ); } } task.setLocale( Locale.ENGLISH ); IRenderOption options = null; if ( "pdf".equals( format ) ) //$NON-NLS-1$ { options = new RenderOptionBase( ); options.setOutputFileName( outputFile ); } else { options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); task.setAppContext( appContext ); } options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, ENCODING_UTF8 ); ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); task.setRenderOption( options ); task.run( ); task.close( ); } /** * Run a report, generate a self-contained report document. * * @throws EngineException */ protected final void run( String input, String output ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + input; //$NON-NLS-1$ //$NON-NLS-2$ IReportRunnable runnable = engine.openReportDesign( inputFile ); IRunTask task = engine.createRunTask( runnable ); task.setAppContext( new HashMap( ) ); IDocArchiveWriter archive = null; try { archive = new FileArchiveWriter( outputFile ); } catch ( IOException e ) { e.printStackTrace( ); } task.run( archive ); task.close( ); } /** * * @param doc * input rpt docuement file * @param output * output file of the generation. * @param pageRange * The pages to render, use "All" to render all, use 1-N to * render a selected page. * @throws EngineException */ protected void render_HTML( String doc, String output, String pageRange ) throws EngineException { this.pagination = false; render( "html", doc, output, pageRange ); //$NON-NLS-1$ } /** * Render a html file with pagination * * @param doc * input rpt docuement file * @param output * output file of the generation. * @param pageRange * The pages to render, use "All" to render all, use 1-N to * render a selected page. * @throws EngineException */ protected void render_HTMLWithPagination( String doc, String output, String pageRange ) throws EngineException { this.pagination = true; render( "html", doc, output, pageRange ); //$NON-NLS-1$ } /** * Render a report document into PDF file. * * @param doc * @param output * @param pageRange * @throws EngineException */ protected void render_PDF( String doc, String output, String pageRange ) throws EngineException { render( "pdf", doc, output, pageRange ); //$NON-NLS-1$ } private void render( String format, String doc, String output, String pageRange ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + doc; //$NON-NLS-1$ //$NON-NLS-2$ String encoding = "UTF-8"; //$NON-NLS-1$ IReportDocument document = engine.openReportDocument( inputFile ); IRenderTask task = engine.createRenderTask( document ); task.setLocale( Locale.ENGLISH ); IRenderOption options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, encoding ); ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); task.setAppContext( appContext ); task.setRenderOption( options ); task.setPageRange( pageRange ); task.render( ); task.close( ); } /** * Run the input design, generate a report document, and then render the * report document into a html file, <code>pageRange</code> specified the * page(s) to render. * * @throws IOException * @throws EngineException */ protected final void runAndThenRender( String input, String output, String pageRange, String format ) throws Exception { String tempDoc = "temp_123aaabbbccc789.rptdocument"; //$NON-NLS-1$ run( input, tempDoc ); String from = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + tempDoc; //$NON-NLS-1$ String temp = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + tempDoc; //$NON-NLS-1$//$NON-NLS-2$ try { copyFile( from, temp ); if ( "pdf".equals( format ) ) //$NON-NLS-1$ render_PDF( tempDoc, output, pageRange ); else render_HTML( tempDoc, output, pageRange ); } catch ( Exception e ) { throw e; } finally { // remove the temp file on exit. removeFile( temp ); } } /** * Compares the two text files. * * @param golden * the reader for golden file * @param output * the reader for output file * @return true if two text files are same. * @throws Exception * if any exception */ private boolean compareTextFile( Reader golden, Reader output, String fileName ) throws Exception { StringBuffer errorText = new StringBuffer( ); BufferedReader lineReaderA = null; BufferedReader lineReaderB = null; boolean same = true; int lineNo = 1; try { lineReaderA = new BufferedReader( golden ); lineReaderB = new BufferedReader( output ); String strA = lineReaderA.readLine( ).trim( ); String strB = lineReaderB.readLine( ).trim( ); while ( strA != null ) { // filter the random part of the page. String filterA = this.filterLine( strA ); String filterB = this.filterLine( strB ); same = filterA.trim( ).equals( filterB.trim( ) ); if ( !same ) { StringBuffer message = new StringBuffer( ); message.append( "line=" ); //$NON-NLS-1$ message.append( lineNo ); message.append( "(" ); //$NON-NLS-1$ message.append( fileName ); message.append( ")" ); //$NON-NLS-1$ message.append( " is different:\n" );//$NON-NLS-1$ message.append( " The line from golden file: " );//$NON-NLS-1$ message.append( strA ); message.append( "\n" );//$NON-NLS-1$ message.append( " The line from result file: " );//$NON-NLS-1$ message.append( strB ); message.append( "\n" );//$NON-NLS-1$ message.append( "Text after filtering: \n" ); //$NON-NLS-1$ message.append( " golden file: " ); //$NON-NLS-1$ message.append( filterA ); message.append( "\n" );//$NON-NLS-1$ message.append( " result file: " ); //$NON-NLS-1$ message.append( filterB ); throw new Exception( message.toString( ) ); } strA = lineReaderA.readLine( ); strB = lineReaderB.readLine( ); lineNo++; } same = ( strA == null ) && ( strB == null ); } finally { try { lineReaderA.close( ); lineReaderB.close( ); } catch ( Exception e ) { lineReaderA = null; lineReaderB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * All kinds of filter-pattern pairs that will be filtered and replace * during comparasion. */ // Sample: id="AUTOGENBOOKMARK_6354527823361272054" private final static Pattern PATTERN_ID_AUTOBOOKMARK = Pattern .compile( "id[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: private final static Pattern PATTERN_NAME_AUTOBOOKMARK = Pattern .compile( "name[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: iid="/9(QuRs13:0)" private final static Pattern PATTERN_IID = Pattern .compile( "iid[\\s]*=[\\s]*\"/.*(.*)\"" ); //$NON-NLS-1$ // Sample: style="background-image:url(image\file44.jpg)" private final static Pattern PATTERN_BG_IMAGE = Pattern .compile( "background-image[\\s]*: url[(]'image.*'[)]" ); //$NON-NLS-1$ //$NON-NLS-2$ // Sample: src="image/design31" // src="image\file31.jpg" private final static Pattern PATTERN_IMAGE_SOURCE = Pattern .compile( "src=\"image.*\"" ); //$NON-NLS-1$ /** * Normalize some seeding values, lines that matches certain patterns will * be repalced by a replacement. */ private static Object[][] FILTER_PATTERNS = { {PATTERN_ID_AUTOBOOKMARK, "REPLACEMENT_ID_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_NAME_AUTOBOOKMARK, "REPLACEMENT_NAME_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_IID, "REPLACEMENT_IID"}, //$NON-NLS-1$ {PATTERN_BG_IMAGE, "REPLACEMENT_BG_IMAGE"}, //$NON-NLS-1$ {PATTERN_IMAGE_SOURCE, "REPLACEMENT_IMAGE_SOURCE"}, //$NON-NLS-1$ }; /** * Replace the given string with a replacement if it matches a certain * pattern. * * @param str * @return filtered string, the tokens that matches the patterns are * replaced with replacement. */ protected String filterLine( String str ) { String result = str; for ( int i = 0; i < FILTER_PATTERNS.length; i++ ) { Pattern pattern = (Pattern) FILTER_PATTERNS[i][0]; String replacement = (String) FILTER_PATTERNS[i][1]; Matcher matcher = pattern.matcher( result ); while ( matcher.find( ) ) { result = matcher.replaceFirst( replacement ); } // result = matcher.replaceAll( replacement ); } return result; } /** * Locates the folder where the unit test java source file is saved. * * @return the path where the test java source file locates. */ protected String getBaseFolder( ) { String className = getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); return PLUGIN_PATH + className.replace( '.', '/' ); } }
testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/EngineCase.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: Actuate Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.birt.report.tests.engine; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; import org.eclipse.birt.core.archive.FileArchiveWriter; import org.eclipse.birt.core.archive.IDocArchiveWriter; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.framework.Platform; import org.eclipse.birt.core.framework.PlatformConfig; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.HTMLRenderContext; import org.eclipse.birt.report.engine.api.HTMLRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IRenderTask; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportEngine; import org.eclipse.birt.report.engine.api.IReportEngineFactory; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IRunAndRenderTask; import org.eclipse.birt.report.engine.api.IRunTask; import org.eclipse.birt.report.engine.api.RenderOptionBase; import org.eclipse.birt.report.engine.api.ReportRunner; /** * Base class for Engine test. * */ public abstract class EngineCase extends TestCase { private String caseName; protected static final String BUNDLE_NAME = "org.eclipse.birt.report.tests.engine.messages";//$NON-NLS-1$ protected static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle( BUNDLE_NAME ); protected static final String PLUGIN_NAME = "org.eclipse.birt.report.tests.engine"; //$NON-NLS-1$ protected static final String PLUGINLOC = "/org.eclipse.birt.report.tests.engine/"; //$NON-NLS-1$ protected static final String PLUGIN_PATH = System.getProperty( "user.dir" ) //$NON-NLS-1$ + "/plugins/" + PLUGINLOC.substring( PLUGINLOC.indexOf( "/" ) + 1 ) //$NON-NLS-1$//$NON-NLS-2$ + "bin/"; //$NON-NLS-1$ protected static final String TEST_FOLDER = "src/"; //$NON-NLS-1$ protected static final String OUTPUT_FOLDER = "output"; //$NON-NLS-1$ protected static final String INPUT_FOLDER = "input"; //$NON-NLS-1$ protected static final String GOLDEN_FOLDER = "golden"; //$NON-NLS-1$ protected IReportEngine engine = null; private static final String FORMAT_HTML = "html"; //$NON-NLS-1$ private static final String ENCODING_UTF8 = "UTF-8"; //$NON-NLS-1$ private static final String IMAGE_DIR = "image"; //$NON-NLS-1$ private static boolean pagination=false; //$NON-NLS-1$ /* * @see TestCase#setUp() */ protected void setUp( ) throws Exception { super.setUp( ); // IPlatformContext context = new PlatformFileContext( ); // config.setEngineContext( context ); // this.engine = new ReportEngine( config ); EngineConfig config = new EngineConfig( ); this.engine = createReportEngine( config ); } /** * Create a report engine instance. * * @throws BirtException */ public IReportEngine createReportEngine( EngineConfig config ) throws BirtException { if ( config == null ) { config = new EngineConfig( ); } Platform.startup( new PlatformConfig( ) ); // assume we has in the platform Object factory = Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); if ( factory instanceof IReportEngineFactory ) { return ( (IReportEngineFactory) factory ) .createReportEngine( config ); } return null; } /** * Constructor. */ public EngineCase( ) { super( null ); } /** * Constructor for DemoCase. * * @param name */ public EngineCase( String name ) { super( name ); } protected void setCase( String caseName ) { // set the case and emitter manager accroding to caseName. this.caseName = caseName; } protected void runCase( String args[] ) { Vector runArgs = new Vector( ); // invoke the report runner. String input = PLUGIN_PATH + System.getProperty( "file.separator" ) //$NON-NLS-1$ + RESOURCE_BUNDLE.getString( "CASE_INPUT" ); //$NON-NLS-1$ input += System.getProperty( "file.separator" ) + caseName //$NON-NLS-1$ + ".rptdesign"; //$NON-NLS-1$ System.out.println( "input is : " + input ); //$NON-NLS-1$ // run report runner. if ( args != null ) { for ( int i = 0; i < args.length; i++ ) { runArgs.add( args[i] ); } } runArgs.add( "-f" ); //$NON-NLS-1$ runArgs.add( "test" ); //$NON-NLS-1$ runArgs.add( input ); args = (String[]) runArgs.toArray( new String[runArgs.size( )] ); ReportRunner.main( args ); } /** * Make a copy of a given file to the target file. * * @param from * the file where to copy from * @param to * the target file to copy to. * @throws IOException */ protected final void copyFile( String from, String to ) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { new File( to ).createNewFile( ); bis = new BufferedInputStream( new FileInputStream( from ) ); bos = new BufferedOutputStream( new FileOutputStream( to ) ); int nextByte = 0; while ( ( nextByte = bis.read( ) ) != -1 ) { bos.write( nextByte ); } } catch ( IOException e ) { throw e; } finally { try { if ( bis != null ) bis.close( ); if ( bos != null ) bos.close( ); } catch ( IOException e ) { // ignore } } } /** * Remove a given file or directory recursively. * @param file */ public void removeFile( File file ) { if ( file.isDirectory( ) ) { File[] children = file.listFiles( ); for ( int i = 0; i < children.length; i++ ) { removeFile( children[i] ); } } if ( file.exists( ) ) { if ( !file.delete( ) ) { System.out.println( file.toString( ) + " can't be removed" ); } } } /** * Remove a given file or directory recursively. * @param file * */ public void removeFile( String file ) { removeFile( new File( file ) ); } /** * Locates the folder where the unit test java source file is saved. * * @return the path name where the test java source file locates. */ protected String getClassFolder( ) { String pathBase = null; ProtectionDomain domain = this.getClass( ).getProtectionDomain( ); if ( domain != null ) { CodeSource source = domain.getCodeSource( ); if ( source != null ) { URL url = source.getLocation( ); pathBase = url.getPath( ); if ( pathBase.endsWith( "bin/" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 4 ); if ( pathBase.endsWith( "bin" ) ) //$NON-NLS-1$ pathBase = pathBase.substring( 0, pathBase.length( ) - 3 ); } } pathBase = pathBase + TEST_FOLDER; String className = this.getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); className = pathBase + className.replace( '.', '/' ); return className; } /** * Compares two text file. The comparison will ignore the line containing * "modificationDate". * * @param golden * the 1st file name to be compared. * @param output * the 2nd file name to be compared. * @return true if two text files are same line by line * @throws Exception * if any exception. */ protected boolean compareHTML( String golden, String output ) throws Exception { FileReader readerA = null; FileReader readerB = null; boolean same = true; StringBuffer errorText = new StringBuffer( ); try { golden = getClassFolder( ) + "/" + GOLDEN_FOLDER + "/" + golden; //$NON-NLS-1$//$NON-NLS-2$ output = getClassFolder( ) + "/" + OUTPUT_FOLDER + "/" + output; //$NON-NLS-1$//$NON-NLS-2$ readerA = new FileReader( golden ); readerB = new FileReader( output ); same = compareTextFile( readerA, readerB, output ); } catch ( IOException e ) { errorText.append( e.toString( ) ); errorText.append( "\n" ); //$NON-NLS-1$ e.printStackTrace( ); } finally { try { readerA.close( ); readerB.close( ); } catch ( Exception e ) { readerA = null; readerB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * Run and render the given design file into html file. If the input is * "a.xml", output html file will be named "a.html" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_HTML( String input, String output ) throws EngineException { this.pagination =false; runAndRender( input, output, null, "html" ); //$NON-NLS-1$ } /** * Run and render the given design file into html file with pagination. If the input is * "a.xml", output html file will be named "a.html" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_HTMLWithPagination( String input, String output ) throws EngineException { this.pagination=true; runAndRender( input, output, null, "html" ); //$NON-NLS-1$ } /** * Run and render the given design file into pdf file. If the input is * "a.xml", output html file will be named "a.pdf" under folder "output". * * @param input * @throws EngineException */ protected void runAndRender_PDF( String input, String output ) throws EngineException { runAndRender( input, output, null, "pdf" ); //$NON-NLS-1$ } /** * RunAndRender a report with the given parameters. */ protected final void runAndRender( String input, String output, Map paramValues, String format ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + input; //$NON-NLS-1$ //$NON-NLS-2$ IReportRunnable runnable = engine.openReportDesign( inputFile ); IRunAndRenderTask task = engine.createRunAndRenderTask( runnable ); if ( paramValues != null ) { Iterator keys = paramValues.keySet( ).iterator( ); while ( keys.hasNext( ) ) { String key = (String) keys.next( ); task.setParameterValue( key, paramValues.get( key ) ); } } task.setLocale( Locale.ENGLISH ); IRenderOption options = null; if ( "pdf".equals( format ) ) //$NON-NLS-1$ { options = new RenderOptionBase( ); options.setOutputFileName( outputFile ); } else { options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); task.setAppContext( appContext ); } options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, ENCODING_UTF8 ); ((HTMLRenderOption)options).setHtmlPagination( this.pagination ); task.setRenderOption( options ); task.run( ); task.close( ); } /** * Run a report, generate a self-contained report document. * * @throws EngineException */ protected final void run( String input, String output ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + input; //$NON-NLS-1$ //$NON-NLS-2$ IReportRunnable runnable = engine.openReportDesign( inputFile ); IRunTask task = engine.createRunTask( runnable ); task.setAppContext( new HashMap( ) ); IDocArchiveWriter archive = null; try { archive = new FileArchiveWriter( outputFile ); } catch ( IOException e ) { e.printStackTrace( ); } task.run( archive ); task.close( ); } /** * * @param doc * input rpt docuement file * @param output * output file of the generation. * @param pageRange * The pages to render, use "All" to render all, use 1-N to * render a selected page. * @throws EngineException */ protected void render_HTML( String doc, String output, String pageRange ) throws EngineException { this.pagination =false; render( "html", doc, output, pageRange ); //$NON-NLS-1$ } /** * Render a html file with pagination * * @param doc * input rpt docuement file * @param output * output file of the generation. * @param pageRange * The pages to render, use "All" to render all, use 1-N to * render a selected page. * @throws EngineException */ protected void render_HTMLWithPagination( String doc, String output, String pageRange ) throws EngineException { this.pagination=true; render( "html", doc, output, pageRange ); //$NON-NLS-1$ } /** * Render a report document into PDF file. * * @param doc * @param output * @param pageRange * @throws EngineException */ protected void render_PDF( String doc, String output, String pageRange ) throws EngineException { render( "pdf", doc, output, pageRange ); //$NON-NLS-1$ } private void render( String format, String doc, String output, String pageRange ) throws EngineException { String outputFile = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + output; //$NON-NLS-1$ String inputFile = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + doc; //$NON-NLS-1$ //$NON-NLS-2$ String encoding = "UTF-8"; //$NON-NLS-1$ IReportDocument document = engine.openReportDocument( inputFile ); IRenderTask task = engine.createRenderTask( document ); task.setLocale( Locale.ENGLISH ); IRenderOption options = new HTMLRenderOption( ); options.setOutputFileName( outputFile ); options.setOutputFormat( format ); options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, encoding ); ((HTMLRenderOption)options).setHtmlPagination( this.pagination ); HTMLRenderContext renderContext = new HTMLRenderContext( ); renderContext.setImageDirectory( IMAGE_DIR ); HashMap appContext = new HashMap( ); appContext.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext ); task.setAppContext( appContext ); task.setRenderOption( options ); task.setPageRange( pageRange ); task.render( ); task.close( ); } /** * Run the input design, generate a report document, and then render the * report document into a html file, <code>pageRange</code> specified the * page(s) to render. * * @throws IOException * @throws EngineException */ protected final void runAndThenRender( String input, String output, String pageRange, String format ) throws Exception { String tempDoc = "temp_123aaabbbccc789.rptdocument"; //$NON-NLS-1$ run( input, tempDoc ); String from = this.getClassFolder( ) + "/" + OUTPUT_FOLDER //$NON-NLS-1$ + "/" + tempDoc; //$NON-NLS-1$ String temp = this.getClassFolder( ) + "/" + INPUT_FOLDER + "/" + tempDoc; //$NON-NLS-1$//$NON-NLS-2$ try { copyFile( from, temp ); if ( "pdf".equals( format ) ) //$NON-NLS-1$ render_PDF( tempDoc, output, pageRange ); else render_HTML( tempDoc, output, pageRange ); } catch ( Exception e ) { throw e; } finally { // remove the temp file on exit. removeFile( temp ); } } /** * Compares the two text files. * * @param golden * the reader for golden file * @param output * the reader for output file * @return true if two text files are same. * @throws Exception * if any exception */ private boolean compareTextFile( Reader golden, Reader output, String fileName ) throws Exception { StringBuffer errorText = new StringBuffer( ); BufferedReader lineReaderA = null; BufferedReader lineReaderB = null; boolean same = true; int lineNo = 1; try { lineReaderA = new BufferedReader( golden ); lineReaderB = new BufferedReader( output ); String strA = lineReaderA.readLine( ).trim( ); String strB = lineReaderB.readLine( ).trim( ); while ( strA != null ) { // filter the random part of the page. String filterA = this.filterLine( strA ); String filterB = this.filterLine( strB ); same = filterA.trim( ).equals( filterB.trim( ) ); if ( !same ) { StringBuffer message = new StringBuffer( ); message.append( "line=" ); //$NON-NLS-1$ message.append( lineNo ); message.append( "(" ); //$NON-NLS-1$ message.append( fileName ); message.append( ")" ); //$NON-NLS-1$ message.append( " is different:\n" );//$NON-NLS-1$ message.append( " The line from golden file: " );//$NON-NLS-1$ message.append( strA ); message.append( "\n" );//$NON-NLS-1$ message.append( " The line from result file: " );//$NON-NLS-1$ message.append( strB ); message.append( "\n" );//$NON-NLS-1$ message.append( "Text after filtering: \n" ); //$NON-NLS-1$ message.append( " golden file: " ); //$NON-NLS-1$ message.append( filterA ); message.append( "\n" );//$NON-NLS-1$ message.append( " result file: " ); //$NON-NLS-1$ message.append( filterB ); throw new Exception( message.toString( ) ); } strA = lineReaderA.readLine( ); strB = lineReaderB.readLine( ); lineNo++; } same = ( strA == null ) && ( strB == null ); } finally { try { lineReaderA.close( ); lineReaderB.close( ); } catch ( Exception e ) { lineReaderA = null; lineReaderB = null; errorText.append( e.toString( ) ); throw new Exception( errorText.toString( ) ); } } return same; } /** * All kinds of filter-pattern pairs that will be filtered and replace * during comparasion. */ // Sample: id="AUTOGENBOOKMARK_6354527823361272054" private final static Pattern PATTERN_ID_AUTOBOOKMARK = Pattern .compile( "id[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: private final static Pattern PATTERN_NAME_AUTOBOOKMARK = Pattern .compile( "name[\\s]*=[\\s]*\"AUTOGENBOOKMARK_[\\d]+\"" ); //$NON-NLS-1$ // Sample: iid="/9(QuRs13:0)" private final static Pattern PATTERN_IID = Pattern .compile( "iid[\\s]*=[\\s]*\"/.*(.*)\"" ); //$NON-NLS-1$ // Sample: style="background-image:url(image\file44.jpg)" private final static Pattern PATTERN_BG_IMAGE = Pattern .compile( "background-image[\\s]*: url[(]'image.*'[)]" ); //$NON-NLS-1$ //$NON-NLS-2$ // Sample: src="image/design31" // src="image\file31.jpg" private final static Pattern PATTERN_IMAGE_SOURCE = Pattern .compile( "src=\"image.*\"" ); //$NON-NLS-1$ /** * Normalize some seeding values, lines that matches certain patterns will * be repalced by a replacement. */ private static Object[][] FILTER_PATTERNS = { {PATTERN_ID_AUTOBOOKMARK, "REPLACEMENT_ID_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_NAME_AUTOBOOKMARK, "REPLACEMENT_NAME_AUTOBOOKMARK"}, //$NON-NLS-1$ {PATTERN_IID, "REPLACEMENT_IID"}, //$NON-NLS-1$ {PATTERN_BG_IMAGE, "REPLACEMENT_BG_IMAGE"}, //$NON-NLS-1$ {PATTERN_IMAGE_SOURCE, "REPLACEMENT_IMAGE_SOURCE"}, //$NON-NLS-1$ }; /** * Replace the given string with a replacement if it matches a certain * pattern. * * @param str * @return filtered string, the tokens that matches the patterns are * replaced with replacement. */ protected String filterLine( String str ) { String result = str; for ( int i = 0; i < FILTER_PATTERNS.length; i++ ) { Pattern pattern = (Pattern) FILTER_PATTERNS[i][0]; String replacement = (String) FILTER_PATTERNS[i][1]; Matcher matcher = pattern.matcher( result ); while ( matcher.find( ) ) { result = matcher.replaceFirst( replacement ); } // result = matcher.replaceAll( replacement ); } return result; } /** * Locates the folder where the unit test java source file is saved. * * @return the path where the test java source file locates. */ protected String getBaseFolder( ) { String className = getClass( ).getName( ); int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$ className = className.substring( 0, lastDotIndex ); return PLUGIN_PATH + className.replace( '.', '/' ); } }
Delete static from boolean variable pagination
testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/EngineCase.java
Delete static from boolean variable pagination
<ide><path>estsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/EngineCase.java <ide> private static final String FORMAT_HTML = "html"; //$NON-NLS-1$ <ide> private static final String ENCODING_UTF8 = "UTF-8"; //$NON-NLS-1$ <ide> private static final String IMAGE_DIR = "image"; //$NON-NLS-1$ <del> private static boolean pagination=false; //$NON-NLS-1$ <add> private boolean pagination = false; //$NON-NLS-1$ <ide> <ide> /* <ide> * @see TestCase#setUp() <ide> <ide> /** <ide> * Remove a given file or directory recursively. <add> * <ide> * @param file <ide> */ <ide> public void removeFile( File file ) <ide> } <ide> } <ide> } <del> <del> <add> <ide> /** <ide> * Remove a given file or directory recursively. <add> * <ide> * @param file <del> * <del> */ <del> <add> * <add> */ <add> <ide> public void removeFile( String file ) <ide> { <ide> removeFile( new File( file ) ); <ide> protected void runAndRender_HTML( String input, String output ) <ide> throws EngineException <ide> { <del> this.pagination =false; <add> this.pagination = false; <ide> runAndRender( input, output, null, "html" ); //$NON-NLS-1$ <ide> } <ide> <ide> /** <del> * Run and render the given design file into html file with pagination. If the input is <del> * "a.xml", output html file will be named "a.html" under folder "output". <add> * Run and render the given design file into html file with pagination. If <add> * the input is "a.xml", output html file will be named "a.html" under <add> * folder "output". <ide> * <ide> * @param input <ide> * @throws EngineException <ide> protected void runAndRender_HTMLWithPagination( String input, String output ) <ide> throws EngineException <ide> { <del> this.pagination=true; <add> this.pagination = true; <ide> runAndRender( input, output, null, "html" ); //$NON-NLS-1$ <ide> } <ide> <del> <ide> /** <ide> * Run and render the given design file into pdf file. If the input is <ide> * "a.xml", output html file will be named "a.pdf" under folder "output". <ide> * @param input <ide> * @throws EngineException <ide> */ <del> <add> <ide> protected void runAndRender_PDF( String input, String output ) <ide> throws EngineException <ide> { <ide> options.setOutputFormat( format ); <ide> options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, <ide> ENCODING_UTF8 ); <del> ((HTMLRenderOption)options).setHtmlPagination( this.pagination ); <add> ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); <ide> task.setRenderOption( options ); <ide> task.run( ); <ide> task.close( ); <ide> protected void render_HTML( String doc, String output, String pageRange ) <ide> throws EngineException <ide> { <del> this.pagination =false; <add> this.pagination = false; <ide> render( "html", doc, output, pageRange ); //$NON-NLS-1$ <ide> } <ide> <ide> * render a selected page. <ide> * @throws EngineException <ide> */ <del> protected void render_HTMLWithPagination( String doc, String output, String pageRange ) <del> throws EngineException <del> { <del> this.pagination=true; <add> protected void render_HTMLWithPagination( String doc, String output, <add> String pageRange ) throws EngineException <add> { <add> this.pagination = true; <ide> render( "html", doc, output, pageRange ); //$NON-NLS-1$ <ide> } <ide> <del> <ide> /** <ide> * Render a report document into PDF file. <ide> * <ide> options.setOutputFormat( format ); <ide> options.getOutputSetting( ).put( HTMLRenderOption.URL_ENCODING, <ide> encoding ); <del> ((HTMLRenderOption)options).setHtmlPagination( this.pagination ); <add> ( (HTMLRenderOption) options ).setHtmlPagination( this.pagination ); <ide> HTMLRenderContext renderContext = new HTMLRenderContext( ); <ide> renderContext.setImageDirectory( IMAGE_DIR ); <ide> HashMap appContext = new HashMap( );
Java
mit
error: pathspec 'src/main/java/com/maddenabbott/jenny/command/help/TemplateHelpCommand.java' did not match any file(s) known to git
6531e5be93d84a9e47208e9d2c5a314cb412a13c
1
jenny-the-generator/jenny,jenny-the-generator/jenny
package com.maddenabbott.jenny.command.help; import com.maddenabbott.jenny.cli.Parameter; import com.maddenabbott.jenny.cli.Summary; import com.maddenabbott.jenny.command.Command; @Summary("You can also get help with a specific template.") public class TemplateHelpCommand implements Command { @Parameter("the name of the repository containing the template.") private final String alias; @Parameter("the name of the template that you want help with.") private final String template; public TemplateHelpCommand(final String alias, final String template) { this.alias = alias; this.template = template; } @Override public void run() { } }
src/main/java/com/maddenabbott/jenny/command/help/TemplateHelpCommand.java
Add skeleton for template help command.
src/main/java/com/maddenabbott/jenny/command/help/TemplateHelpCommand.java
Add skeleton for template help command.
<ide><path>rc/main/java/com/maddenabbott/jenny/command/help/TemplateHelpCommand.java <add>package com.maddenabbott.jenny.command.help; <add> <add>import com.maddenabbott.jenny.cli.Parameter; <add>import com.maddenabbott.jenny.cli.Summary; <add>import com.maddenabbott.jenny.command.Command; <add> <add>@Summary("You can also get help with a specific template.") <add>public class TemplateHelpCommand implements Command { <add> @Parameter("the name of the repository containing the template.") <add> private final String alias; <add> @Parameter("the name of the template that you want help with.") <add> private final String template; <add> <add> public TemplateHelpCommand(final String alias, final String template) { <add> this.alias = alias; <add> this.template = template; <add> } <add> <add> @Override <add> public void run() { <add> <add> } <add>}
JavaScript
mit
74ba7621149919cd0b81d32f5c92259c5107c19f
0
jillix/engine-tools,jillix/flow-api
"use strict" const cayley = require('./cayley'); exports.flow = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: missing sequence id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.flow(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.resume = data.readable; next(null, data); }; exports.networks = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing user info.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.networks(state.g, data.id, role); data.readable.pause(); data.resume = data.readable; next(null, data); }; exports.entrypoints = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing network id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.entrypoints(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.resume = data.readable; next(null, data); }; exports.entrypoint = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing entrypoint id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.entrypoint(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.readable[3].pause(); data.resume = data.readable; next(null, data); }; exports.sequence = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing sequence id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.sequence(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.readable[3].pause(); data.resume = data.readable; next(null, data); }; exports.handler = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing handler id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.handler(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.readable[3].pause(); data.readable[4].pause(); data.resume = data.readable; next(null, data); };
lib/sequence.js
"use strict" const cayley = require('./cayley'); exports.flow = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: missing sequence id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.flow(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.resume = data.readable; next(null, data); }; exports.networks = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing user info.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.networks(state.g, data.id, role); data.readable.pause(); data.resume = data.readable; next(null, data); }; exports.entrypoints = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing network id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.entrypoints(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.resume = data.readable; next(null, data); }; exports.entrypoint = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing entrypoint id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.entrypoint(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.readable[3].pause(); data.resume = data.readable; next(null, data); }; exports.sequence = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing sequence id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.sequence(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.resume = data.readable; next(null, data); }; exports.handler = (scope, state, args, data, next) => { if (!data.id) { return next(new Error('Flow-api.get.flow: Missing handler id.')); } let role = !data.session || !data.session.role ? scope.env.role : data.session.role; data.readable = cayley.handler(state.g, data.id, role); data.readable[0].pause(); data.readable[1].pause(); data.readable[2].pause(); data.readable[3].pause(); data.readable[4].pause(); data.resume = data.readable; next(null, data); };
pause all streams
lib/sequence.js
pause all streams
<ide><path>ib/sequence.js <ide> data.readable[0].pause(); <ide> data.readable[1].pause(); <ide> data.readable[2].pause(); <add> data.readable[3].pause(); <ide> data.resume = data.readable; <ide> next(null, data); <ide> };
Java
apache-2.0
4904d6f5ea5fdce01f8a418ddf789a100d57e72c
0
minhthuanit/selenium,eric-stanley/selenium,isaksky/selenium,jsakamoto/selenium,sebady/selenium,freynaud/selenium,dbo/selenium,alb-i986/selenium,SouWilliams/selenium,HtmlUnit/selenium,houchj/selenium,markodolancic/selenium,juangj/selenium,slongwang/selenium,rplevka/selenium,soundcloud/selenium,doungni/selenium,slongwang/selenium,compstak/selenium,krmahadevan/selenium,onedox/selenium,Tom-Trumper/selenium,joshbruning/selenium,gregerrag/selenium,oddui/selenium,dcjohnson1989/selenium,sankha93/selenium,JosephCastro/selenium,GorK-ChO/selenium,MeetMe/selenium,dcjohnson1989/selenium,anshumanchatterji/selenium,bmannix/selenium,vinay-qa/vinayit-android-server-apk,MeetMe/selenium,petruc/selenium,rrussell39/selenium,slongwang/selenium,lummyare/lummyare-test,dimacus/selenium,yukaReal/selenium,dibagga/selenium,markodolancic/selenium,doungni/selenium,mojwang/selenium,o-schneider/selenium,pulkitsinghal/selenium,tbeadle/selenium,dibagga/selenium,vveliev/selenium,gabrielsimas/selenium,titusfortner/selenium,dandv/selenium,meksh/selenium,knorrium/selenium,chrisblock/selenium,SouWilliams/selenium,aluedeke/chromedriver,soundcloud/selenium,jknguyen/josephknguyen-selenium,freynaud/selenium,livioc/selenium,HtmlUnit/selenium,blueyed/selenium,p0deje/selenium,amar-sharma/selenium,dbo/selenium,uchida/selenium,Ardesco/selenium,stupidnetizen/selenium,jabbrwcky/selenium,asolntsev/selenium,livioc/selenium,DrMarcII/selenium,krosenvold/selenium,telefonicaid/selenium,krosenvold/selenium-git-release-candidate,GorK-ChO/selenium,gabrielsimas/selenium,doungni/selenium,gemini-testing/selenium,vveliev/selenium,jerome-jacob/selenium,zenefits/selenium,eric-stanley/selenium,titusfortner/selenium,joshbruning/selenium,minhthuanit/selenium,slongwang/selenium,dbo/selenium,krmahadevan/selenium,meksh/selenium,TikhomirovSergey/selenium,jerome-jacob/selenium,rplevka/selenium,anshumanchatterji/selenium,DrMarcII/selenium,tarlabs/selenium,SeleniumHQ/selenium,slongwang/selenium,Jarob22/selenium,sankha93/selenium,i17c/selenium,MCGallaspy/selenium,lrowe/selenium,MCGallaspy/selenium,manuelpirez/selenium,rrussell39/selenium,vveliev/selenium,joshbruning/selenium,sevaseva/selenium,GorK-ChO/selenium,JosephCastro/selenium,onedox/selenium,livioc/selenium,gurayinan/selenium,joshmgrant/selenium,gabrielsimas/selenium,BlackSmith/selenium,jabbrwcky/selenium,Jarob22/selenium,pulkitsinghal/selenium,joshmgrant/selenium,krosenvold/selenium-git-release-candidate,Tom-Trumper/selenium,isaksky/selenium,Dude-X/selenium,krosenvold/selenium,lilredindy/selenium,manuelpirez/selenium,sankha93/selenium,krosenvold/selenium,soundcloud/selenium,carlosroh/selenium,xmhubj/selenium,Jarob22/selenium,rovner/selenium,chrsmithdemos/selenium,jknguyen/josephknguyen-selenium,RamaraoDonta/ramarao-clone,amar-sharma/selenium,lummyare/lummyare-lummy,gregerrag/selenium,p0deje/selenium,dandv/selenium,xsyntrex/selenium,5hawnknight/selenium,wambat/selenium,lummyare/lummyare-lummy,anshumanchatterji/selenium,onedox/selenium,Dude-X/selenium,gorlemik/selenium,rplevka/selenium,thanhpete/selenium,s2oBCN/selenium,alexec/selenium,titusfortner/selenium,lrowe/selenium,gurayinan/selenium,dandv/selenium,sri85/selenium,amikey/selenium,isaksky/selenium,isaksky/selenium,knorrium/selenium,quoideneuf/selenium,carsonmcdonald/selenium,TheBlackTuxCorp/selenium,o-schneider/selenium,Appdynamics/selenium,lummyare/lummyare-test,actmd/selenium,gregerrag/selenium,TikhomirovSergey/selenium,5hawnknight/selenium,sag-enorman/selenium,juangj/selenium,SevInf/IEDriver,kalyanjvn1/selenium,blueyed/selenium,dandv/selenium,MeetMe/selenium,joshuaduffy/selenium,sri85/selenium,soundcloud/selenium,bayandin/selenium,valfirst/selenium,dkentw/selenium,yukaReal/selenium,Ardesco/selenium,soundcloud/selenium,misttechnologies/selenium,sebady/selenium,valfirst/selenium,Dude-X/selenium,Sravyaksr/selenium,blueyed/selenium,gotcha/selenium,p0deje/selenium,gorlemik/selenium,gregerrag/selenium,asolntsev/selenium,jsakamoto/selenium,p0deje/selenium,tbeadle/selenium,joshbruning/selenium,houchj/selenium,yukaReal/selenium,uchida/selenium,blackboarddd/selenium,zenefits/selenium,carsonmcdonald/selenium,valfirst/selenium,BlackSmith/selenium,eric-stanley/selenium,valfirst/selenium,customcommander/selenium,krosenvold/selenium,denis-vilyuzhanin/selenium-fastview,sevaseva/selenium,rrussell39/selenium,valfirst/selenium,amikey/selenium,skurochkin/selenium,alb-i986/selenium,lukeis/selenium,krmahadevan/selenium,lukeis/selenium,vveliev/selenium,sebady/selenium,rrussell39/selenium,temyers/selenium,skurochkin/selenium,5hawnknight/selenium,dkentw/selenium,joshbruning/selenium,sag-enorman/selenium,doungni/selenium,twalpole/selenium,MeetMe/selenium,uchida/selenium,mestihudson/selenium,jabbrwcky/selenium,bartolkaruza/selenium,AutomatedTester/selenium,RamaraoDonta/ramarao-clone,chrsmithdemos/selenium,amikey/selenium,quoideneuf/selenium,joshmgrant/selenium,joshbruning/selenium,juangj/selenium,mestihudson/selenium,twalpole/selenium,arunsingh/selenium,skurochkin/selenium,joshbruning/selenium,mach6/selenium,misttechnologies/selenium,chrsmithdemos/selenium,gabrielsimas/selenium,blackboarddd/selenium,jsarenik/jajomojo-selenium,skurochkin/selenium,titusfortner/selenium,5hawnknight/selenium,telefonicaid/selenium,freynaud/selenium,Tom-Trumper/selenium,denis-vilyuzhanin/selenium-fastview,bayandin/selenium,s2oBCN/selenium,meksh/selenium,lrowe/selenium,s2oBCN/selenium,amar-sharma/selenium,eric-stanley/selenium,Dude-X/selenium,JosephCastro/selenium,davehunt/selenium,rovner/selenium,jknguyen/josephknguyen-selenium,o-schneider/selenium,gurayinan/selenium,denis-vilyuzhanin/selenium-fastview,quoideneuf/selenium,aluedeke/chromedriver,chrisblock/selenium,orange-tv-blagnac/selenium,vinay-qa/vinayit-android-server-apk,aluedeke/chromedriver,rovner/selenium,actmd/selenium,valfirst/selenium,SouWilliams/selenium,orange-tv-blagnac/selenium,Tom-Trumper/selenium,telefonicaid/selenium,5hawnknight/selenium,jsakamoto/selenium,twalpole/selenium,valfirst/selenium,jerome-jacob/selenium,Jarob22/selenium,freynaud/selenium,AutomatedTester/selenium,gemini-testing/selenium,alb-i986/selenium,temyers/selenium,SouWilliams/selenium,vinay-qa/vinayit-android-server-apk,alexec/selenium,krmahadevan/selenium,temyers/selenium,bayandin/selenium,sevaseva/selenium,gregerrag/selenium,tbeadle/selenium,sankha93/selenium,MeetMe/selenium,Jarob22/selenium,lukeis/selenium,zenefits/selenium,bartolkaruza/selenium,gemini-testing/selenium,onedox/selenium,JosephCastro/selenium,skurochkin/selenium,lummyare/lummyare-test,rrussell39/selenium,i17c/selenium,gotcha/selenium,knorrium/selenium,gotcha/selenium,krmahadevan/selenium,asolntsev/selenium,freynaud/selenium,i17c/selenium,RamaraoDonta/ramarao-clone,SevInf/IEDriver,knorrium/selenium,alb-i986/selenium,telefonicaid/selenium,minhthuanit/selenium,MCGallaspy/selenium,s2oBCN/selenium,jsarenik/jajomojo-selenium,joshuaduffy/selenium,carsonmcdonald/selenium,gregerrag/selenium,compstak/selenium,joshbruning/selenium,lmtierney/selenium,MCGallaspy/selenium,compstak/selenium,alexec/selenium,joshmgrant/selenium,AutomatedTester/selenium,eric-stanley/selenium,Jarob22/selenium,onedox/selenium,RamaraoDonta/ramarao-clone,gotcha/selenium,freynaud/selenium,carlosroh/selenium,meksh/selenium,sri85/selenium,houchj/selenium,asolntsev/selenium,telefonicaid/selenium,soundcloud/selenium,alb-i986/selenium,clavery/selenium,bartolkaruza/selenium,krmahadevan/selenium,quoideneuf/selenium,amar-sharma/selenium,chrsmithdemos/selenium,lrowe/selenium,TheBlackTuxCorp/selenium,sevaseva/selenium,Herst/selenium,markodolancic/selenium,petruc/selenium,BlackSmith/selenium,sag-enorman/selenium,MCGallaspy/selenium,kalyanjvn1/selenium,asolntsev/selenium,lmtierney/selenium,HtmlUnit/selenium,telefonicaid/selenium,stupidnetizen/selenium,blackboarddd/selenium,lmtierney/selenium,Herst/selenium,o-schneider/selenium,o-schneider/selenium,o-schneider/selenium,lmtierney/selenium,AutomatedTester/selenium,DrMarcII/selenium,blackboarddd/selenium,actmd/selenium,gemini-testing/selenium,GorK-ChO/selenium,o-schneider/selenium,lummyare/lummyare-test,orange-tv-blagnac/selenium,Appdynamics/selenium,compstak/selenium,joshuaduffy/selenium,gemini-testing/selenium,krosenvold/selenium-git-release-candidate,petruc/selenium,orange-tv-blagnac/selenium,Ardesco/selenium,SouWilliams/selenium,Dude-X/selenium,pulkitsinghal/selenium,orange-tv-blagnac/selenium,meksh/selenium,tkurnosova/selenium,mojwang/selenium,i17c/selenium,TikhomirovSergey/selenium,blackboarddd/selenium,juangj/selenium,TheBlackTuxCorp/selenium,denis-vilyuzhanin/selenium-fastview,carlosroh/selenium,davehunt/selenium,TikhomirovSergey/selenium,Sravyaksr/selenium,Herst/selenium,SeleniumHQ/selenium,slongwang/selenium,jsakamoto/selenium,actmd/selenium,twalpole/selenium,BlackSmith/selenium,misttechnologies/selenium,aluedeke/chromedriver,tkurnosova/selenium,skurochkin/selenium,livioc/selenium,dimacus/selenium,customcommander/selenium,yukaReal/selenium,xsyntrex/selenium,s2oBCN/selenium,chrsmithdemos/selenium,clavery/selenium,alexec/selenium,freynaud/selenium,blackboarddd/selenium,jsarenik/jajomojo-selenium,temyers/selenium,bmannix/selenium,asashour/selenium,Sravyaksr/selenium,Ardesco/selenium,xsyntrex/selenium,dcjohnson1989/selenium,bmannix/selenium,jsarenik/jajomojo-selenium,stupidnetizen/selenium,amar-sharma/selenium,dbo/selenium,knorrium/selenium,manuelpirez/selenium,rplevka/selenium,clavery/selenium,DrMarcII/selenium,carlosroh/selenium,sri85/selenium,arunsingh/selenium,lmtierney/selenium,dcjohnson1989/selenium,zenefits/selenium,carsonmcdonald/selenium,asashour/selenium,RamaraoDonta/ramarao-clone,asashour/selenium,anshumanchatterji/selenium,petruc/selenium,bayandin/selenium,petruc/selenium,mach6/selenium,SevInf/IEDriver,DrMarcII/selenium,soundcloud/selenium,gurayinan/selenium,temyers/selenium,SouWilliams/selenium,dibagga/selenium,TheBlackTuxCorp/selenium,clavery/selenium,wambat/selenium,bartolkaruza/selenium,blueyed/selenium,skurochkin/selenium,alb-i986/selenium,pulkitsinghal/selenium,jabbrwcky/selenium,krosenvold/selenium,HtmlUnit/selenium,davehunt/selenium,manuelpirez/selenium,jabbrwcky/selenium,knorrium/selenium,i17c/selenium,SevInf/IEDriver,Sravyaksr/selenium,gurayinan/selenium,alexec/selenium,xsyntrex/selenium,xmhubj/selenium,thanhpete/selenium,jabbrwcky/selenium,xmhubj/selenium,HtmlUnit/selenium,sag-enorman/selenium,manuelpirez/selenium,bmannix/selenium,zenefits/selenium,zenefits/selenium,Tom-Trumper/selenium,gorlemik/selenium,aluedeke/chromedriver,gabrielsimas/selenium,denis-vilyuzhanin/selenium-fastview,mestihudson/selenium,sri85/selenium,rrussell39/selenium,gemini-testing/selenium,Ardesco/selenium,amikey/selenium,bmannix/selenium,titusfortner/selenium,minhthuanit/selenium,petruc/selenium,gorlemik/selenium,aluedeke/chromedriver,tbeadle/selenium,twalpole/selenium,mestihudson/selenium,bayandin/selenium,thanhpete/selenium,gregerrag/selenium,alexec/selenium,valfirst/selenium,doungni/selenium,tarlabs/selenium,vveliev/selenium,mojwang/selenium,lmtierney/selenium,bayandin/selenium,5hawnknight/selenium,joshuaduffy/selenium,p0deje/selenium,JosephCastro/selenium,anshumanchatterji/selenium,onedox/selenium,5hawnknight/selenium,blackboarddd/selenium,TheBlackTuxCorp/selenium,orange-tv-blagnac/selenium,bmannix/selenium,dimacus/selenium,dibagga/selenium,livioc/selenium,Tom-Trumper/selenium,JosephCastro/selenium,krmahadevan/selenium,aluedeke/chromedriver,rplevka/selenium,mach6/selenium,dcjohnson1989/selenium,telefonicaid/selenium,BlackSmith/selenium,tbeadle/selenium,tkurnosova/selenium,SevInf/IEDriver,eric-stanley/selenium,RamaraoDonta/ramarao-clone,rovner/selenium,denis-vilyuzhanin/selenium-fastview,SeleniumHQ/selenium,pulkitsinghal/selenium,tarlabs/selenium,markodolancic/selenium,valfirst/selenium,SeleniumHQ/selenium,Dude-X/selenium,amikey/selenium,gabrielsimas/selenium,dkentw/selenium,stupidnetizen/selenium,doungni/selenium,Dude-X/selenium,mach6/selenium,mestihudson/selenium,zenefits/selenium,arunsingh/selenium,misttechnologies/selenium,i17c/selenium,tarlabs/selenium,sankha93/selenium,misttechnologies/selenium,RamaraoDonta/ramarao-clone,jknguyen/josephknguyen-selenium,wambat/selenium,Sravyaksr/selenium,dkentw/selenium,sankha93/selenium,SeleniumHQ/selenium,tkurnosova/selenium,pulkitsinghal/selenium,dkentw/selenium,thanhpete/selenium,sebady/selenium,RamaraoDonta/ramarao-clone,rovner/selenium,blackboarddd/selenium,quoideneuf/selenium,joshuaduffy/selenium,gotcha/selenium,wambat/selenium,chrisblock/selenium,mojwang/selenium,JosephCastro/selenium,slongwang/selenium,dbo/selenium,Jarob22/selenium,customcommander/selenium,tarlabs/selenium,jerome-jacob/selenium,sebady/selenium,gurayinan/selenium,markodolancic/selenium,oddui/selenium,lummyare/lummyare-lummy,mojwang/selenium,rplevka/selenium,lilredindy/selenium,joshmgrant/selenium,actmd/selenium,jerome-jacob/selenium,mestihudson/selenium,tbeadle/selenium,eric-stanley/selenium,lilredindy/selenium,temyers/selenium,sri85/selenium,jerome-jacob/selenium,twalpole/selenium,mach6/selenium,TikhomirovSergey/selenium,GorK-ChO/selenium,carsonmcdonald/selenium,rovner/selenium,Jarob22/selenium,MCGallaspy/selenium,kalyanjvn1/selenium,titusfortner/selenium,titusfortner/selenium,lrowe/selenium,sag-enorman/selenium,soundcloud/selenium,gemini-testing/selenium,tarlabs/selenium,lukeis/selenium,jerome-jacob/selenium,chrisblock/selenium,onedox/selenium,actmd/selenium,misttechnologies/selenium,zenefits/selenium,davehunt/selenium,uchida/selenium,actmd/selenium,valfirst/selenium,dimacus/selenium,customcommander/selenium,dandv/selenium,SeleniumHQ/selenium,stupidnetizen/selenium,jsakamoto/selenium,isaksky/selenium,vveliev/selenium,eric-stanley/selenium,meksh/selenium,rplevka/selenium,amikey/selenium,clavery/selenium,mach6/selenium,orange-tv-blagnac/selenium,mach6/selenium,Jarob22/selenium,gotcha/selenium,mojwang/selenium,juangj/selenium,vinay-qa/vinayit-android-server-apk,Ardesco/selenium,Ardesco/selenium,petruc/selenium,blueyed/selenium,Herst/selenium,jabbrwcky/selenium,blueyed/selenium,misttechnologies/selenium,chrisblock/selenium,bmannix/selenium,Sravyaksr/selenium,misttechnologies/selenium,oddui/selenium,asashour/selenium,sag-enorman/selenium,compstak/selenium,tbeadle/selenium,bartolkaruza/selenium,lummyare/lummyare-test,alb-i986/selenium,wambat/selenium,arunsingh/selenium,lrowe/selenium,denis-vilyuzhanin/selenium-fastview,xmhubj/selenium,soundcloud/selenium,valfirst/selenium,joshuaduffy/selenium,jsarenik/jajomojo-selenium,lummyare/lummyare-test,wambat/selenium,sevaseva/selenium,asashour/selenium,chrisblock/selenium,minhthuanit/selenium,mestihudson/selenium,lilredindy/selenium,yukaReal/selenium,davehunt/selenium,kalyanjvn1/selenium,TheBlackTuxCorp/selenium,petruc/selenium,juangj/selenium,AutomatedTester/selenium,blueyed/selenium,lukeis/selenium,MeetMe/selenium,jknguyen/josephknguyen-selenium,minhthuanit/selenium,anshumanchatterji/selenium,bayandin/selenium,SeleniumHQ/selenium,jsarenik/jajomojo-selenium,Ardesco/selenium,gorlemik/selenium,customcommander/selenium,slongwang/selenium,SeleniumHQ/selenium,meksh/selenium,gabrielsimas/selenium,SevInf/IEDriver,arunsingh/selenium,i17c/selenium,sevaseva/selenium,amar-sharma/selenium,lummyare/lummyare-test,kalyanjvn1/selenium,carlosroh/selenium,GorK-ChO/selenium,isaksky/selenium,bayandin/selenium,petruc/selenium,Tom-Trumper/selenium,HtmlUnit/selenium,gabrielsimas/selenium,titusfortner/selenium,vinay-qa/vinayit-android-server-apk,dbo/selenium,oddui/selenium,asolntsev/selenium,tbeadle/selenium,twalpole/selenium,AutomatedTester/selenium,amikey/selenium,zenefits/selenium,lummyare/lummyare-lummy,uchida/selenium,AutomatedTester/selenium,slongwang/selenium,carsonmcdonald/selenium,lummyare/lummyare-lummy,oddui/selenium,joshuaduffy/selenium,stupidnetizen/selenium,MeetMe/selenium,p0deje/selenium,compstak/selenium,SeleniumHQ/selenium,yukaReal/selenium,markodolancic/selenium,minhthuanit/selenium,jabbrwcky/selenium,chrsmithdemos/selenium,houchj/selenium,lmtierney/selenium,wambat/selenium,customcommander/selenium,pulkitsinghal/selenium,actmd/selenium,dimacus/selenium,Ardesco/selenium,gorlemik/selenium,titusfortner/selenium,oddui/selenium,xmhubj/selenium,sebady/selenium,sri85/selenium,jsakamoto/selenium,uchida/selenium,chrisblock/selenium,carsonmcdonald/selenium,houchj/selenium,lilredindy/selenium,sevaseva/selenium,amar-sharma/selenium,quoideneuf/selenium,titusfortner/selenium,alb-i986/selenium,gorlemik/selenium,kalyanjvn1/selenium,SevInf/IEDriver,stupidnetizen/selenium,HtmlUnit/selenium,wambat/selenium,vveliev/selenium,gregerrag/selenium,dibagga/selenium,clavery/selenium,krosenvold/selenium,Sravyaksr/selenium,SouWilliams/selenium,bmannix/selenium,onedox/selenium,lukeis/selenium,mojwang/selenium,knorrium/selenium,jknguyen/josephknguyen-selenium,Herst/selenium,customcommander/selenium,dbo/selenium,chrisblock/selenium,sankha93/selenium,chrsmithdemos/selenium,JosephCastro/selenium,Herst/selenium,meksh/selenium,jsarenik/jajomojo-selenium,skurochkin/selenium,joshmgrant/selenium,mestihudson/selenium,clavery/selenium,aluedeke/chromedriver,dkentw/selenium,tkurnosova/selenium,carlosroh/selenium,lummyare/lummyare-test,Dude-X/selenium,Sravyaksr/selenium,o-schneider/selenium,compstak/selenium,MeetMe/selenium,TheBlackTuxCorp/selenium,Sravyaksr/selenium,dandv/selenium,dandv/selenium,DrMarcII/selenium,BlackSmith/selenium,dcjohnson1989/selenium,krosenvold/selenium-git-release-candidate,jknguyen/josephknguyen-selenium,krosenvold/selenium,s2oBCN/selenium,bartolkaruza/selenium,twalpole/selenium,gorlemik/selenium,lrowe/selenium,dibagga/selenium,blueyed/selenium,sag-enorman/selenium,juangj/selenium,markodolancic/selenium,asashour/selenium,meksh/selenium,joshuaduffy/selenium,o-schneider/selenium,amar-sharma/selenium,BlackSmith/selenium,xsyntrex/selenium,Appdynamics/selenium,AutomatedTester/selenium,davehunt/selenium,TikhomirovSergey/selenium,TheBlackTuxCorp/selenium,telefonicaid/selenium,rovner/selenium,davehunt/selenium,dbo/selenium,knorrium/selenium,dandv/selenium,xsyntrex/selenium,SouWilliams/selenium,lmtierney/selenium,joshmgrant/selenium,p0deje/selenium,xsyntrex/selenium,carlosroh/selenium,lilredindy/selenium,doungni/selenium,Herst/selenium,HtmlUnit/selenium,isaksky/selenium,arunsingh/selenium,xmhubj/selenium,TikhomirovSergey/selenium,SeleniumHQ/selenium,DrMarcII/selenium,vinay-qa/vinayit-android-server-apk,Appdynamics/selenium,krosenvold/selenium-git-release-candidate,temyers/selenium,gurayinan/selenium,Tom-Trumper/selenium,dbo/selenium,rovner/selenium,temyers/selenium,Appdynamics/selenium,gotcha/selenium,krosenvold/selenium-git-release-candidate,asashour/selenium,sevaseva/selenium,SevInf/IEDriver,Appdynamics/selenium,jsakamoto/selenium,joshmgrant/selenium,clavery/selenium,rrussell39/selenium,5hawnknight/selenium,Tom-Trumper/selenium,juangj/selenium,customcommander/selenium,p0deje/selenium,markodolancic/selenium,rrussell39/selenium,blackboarddd/selenium,oddui/selenium,jsarenik/jajomojo-selenium,amikey/selenium,dkentw/selenium,dcjohnson1989/selenium,isaksky/selenium,alb-i986/selenium,rovner/selenium,orange-tv-blagnac/selenium,jsarenik/jajomojo-selenium,Dude-X/selenium,customcommander/selenium,sag-enorman/selenium,uchida/selenium,vveliev/selenium,s2oBCN/selenium,alexec/selenium,livioc/selenium,SevInf/IEDriver,xsyntrex/selenium,yukaReal/selenium,lummyare/lummyare-lummy,lukeis/selenium,sebady/selenium,sebady/selenium,rrussell39/selenium,onedox/selenium,Appdynamics/selenium,livioc/selenium,lummyare/lummyare-lummy,titusfortner/selenium,amikey/selenium,doungni/selenium,mestihudson/selenium,davehunt/selenium,vinay-qa/vinayit-android-server-apk,uchida/selenium,quoideneuf/selenium,lummyare/lummyare-lummy,amar-sharma/selenium,carlosroh/selenium,dkentw/selenium,compstak/selenium,denis-vilyuzhanin/selenium-fastview,lmtierney/selenium,anshumanchatterji/selenium,kalyanjvn1/selenium,joshmgrant/selenium,dandv/selenium,clavery/selenium,xsyntrex/selenium,krmahadevan/selenium,oddui/selenium,knorrium/selenium,vinay-qa/vinayit-android-server-apk,manuelpirez/selenium,Appdynamics/selenium,sankha93/selenium,kalyanjvn1/selenium,orange-tv-blagnac/selenium,carlosroh/selenium,gemini-testing/selenium,carsonmcdonald/selenium,thanhpete/selenium,telefonicaid/selenium,i17c/selenium,i17c/selenium,lrowe/selenium,Appdynamics/selenium,dimacus/selenium,MCGallaspy/selenium,wambat/selenium,lummyare/lummyare-test,manuelpirez/selenium,pulkitsinghal/selenium,lukeis/selenium,twalpole/selenium,tarlabs/selenium,houchj/selenium,GorK-ChO/selenium,carsonmcdonald/selenium,freynaud/selenium,jabbrwcky/selenium,joshbruning/selenium,lrowe/selenium,mojwang/selenium,tarlabs/selenium,sri85/selenium,gorlemik/selenium,sevaseva/selenium,bartolkaruza/selenium,tkurnosova/selenium,asolntsev/selenium,chrisblock/selenium,asolntsev/selenium,yukaReal/selenium,jerome-jacob/selenium,alexec/selenium,5hawnknight/selenium,jsakamoto/selenium,temyers/selenium,pulkitsinghal/selenium,MCGallaspy/selenium,manuelpirez/selenium,minhthuanit/selenium,TikhomirovSergey/selenium,sebady/selenium,oddui/selenium,sri85/selenium,AutomatedTester/selenium,thanhpete/selenium,DrMarcII/selenium,joshuaduffy/selenium,MCGallaspy/selenium,juangj/selenium,s2oBCN/selenium,thanhpete/selenium,mach6/selenium,gurayinan/selenium,xmhubj/selenium,gotcha/selenium,gregerrag/selenium,SeleniumHQ/selenium,bartolkaruza/selenium,Herst/selenium,MeetMe/selenium,dimacus/selenium,sankha93/selenium,lummyare/lummyare-lummy,krosenvold/selenium-git-release-candidate,sag-enorman/selenium,minhthuanit/selenium,chrsmithdemos/selenium,eric-stanley/selenium,actmd/selenium,freynaud/selenium,mojwang/selenium,dibagga/selenium,houchj/selenium,joshmgrant/selenium,anshumanchatterji/selenium,bartolkaruza/selenium,rplevka/selenium,dibagga/selenium,TikhomirovSergey/selenium,JosephCastro/selenium,Herst/selenium,TheBlackTuxCorp/selenium,arunsingh/selenium,SouWilliams/selenium,jsakamoto/selenium,anshumanchatterji/selenium,quoideneuf/selenium,joshmgrant/selenium,asolntsev/selenium,yukaReal/selenium,krosenvold/selenium,HtmlUnit/selenium,lilredindy/selenium,livioc/selenium,tkurnosova/selenium,livioc/selenium,skurochkin/selenium,alexec/selenium,houchj/selenium,markodolancic/selenium,xmhubj/selenium,compstak/selenium,lukeis/selenium,DrMarcII/selenium,vinay-qa/vinayit-android-server-apk,gurayinan/selenium,gabrielsimas/selenium,dcjohnson1989/selenium,davehunt/selenium,s2oBCN/selenium,houchj/selenium,dibagga/selenium,xmhubj/selenium,doungni/selenium,krmahadevan/selenium,mach6/selenium,aluedeke/chromedriver,gemini-testing/selenium,isaksky/selenium,tkurnosova/selenium,rplevka/selenium,dkentw/selenium,BlackSmith/selenium,lilredindy/selenium,bayandin/selenium,vveliev/selenium,kalyanjvn1/selenium,krosenvold/selenium,bmannix/selenium,misttechnologies/selenium,arunsingh/selenium,stupidnetizen/selenium,manuelpirez/selenium,HtmlUnit/selenium,stupidnetizen/selenium,BlackSmith/selenium,GorK-ChO/selenium,gotcha/selenium,tkurnosova/selenium,lilredindy/selenium,dimacus/selenium,RamaraoDonta/ramarao-clone,arunsingh/selenium,uchida/selenium,krosenvold/selenium-git-release-candidate,asashour/selenium,thanhpete/selenium,GorK-ChO/selenium,chrsmithdemos/selenium,dimacus/selenium,quoideneuf/selenium,jerome-jacob/selenium,jknguyen/josephknguyen-selenium,tarlabs/selenium,tbeadle/selenium,dcjohnson1989/selenium,asashour/selenium,thanhpete/selenium,blueyed/selenium,p0deje/selenium,denis-vilyuzhanin/selenium-fastview,jknguyen/josephknguyen-selenium
package org.openqa.selenium.firefox.internal; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverException; import java.io.File; import java.util.Map; /** * Wrapper around our runtime environment requirements. * Performs discovery of firefox instances. * * <p>NOTE: System and platform binaries will only be discovered at class initialization. * * @author [email protected] (Gregory Block) */ public class Executable { private static final File SYSTEM_BINARY = locateFirefoxBinaryFromSystemProperty(); private static final File PLATFORM_BINARY = locateFirefoxBinaryFromPlatform(); private final File binary; public Executable(File userSpecifiedBinaryPath) { if (userSpecifiedBinaryPath != null) { // It should exist and be a file. if (userSpecifiedBinaryPath.exists() && userSpecifiedBinaryPath.isFile()) { binary = userSpecifiedBinaryPath; return; } throw new WebDriverException( "Specified firefox binary location does not exist or is not a real file: " + userSpecifiedBinaryPath); } if (SYSTEM_BINARY != null && SYSTEM_BINARY.exists()) { binary = SYSTEM_BINARY; return; } if (PLATFORM_BINARY != null && PLATFORM_BINARY.exists()) { binary = PLATFORM_BINARY; return; } throw new WebDriverException("Cannot find firefox binary in PATH. " + "Make sure firefox is installed. OS appears to be: " + Platform.getCurrent()); } public File getFile() { return binary; } public String getPath() { return binary.getAbsolutePath(); } public void setLibraryPath(ProcessBuilder builder, Map<String, String> extraEnv) { final String propertyName = getLibraryPathPropertyName(); StringBuilder libraryPath = new StringBuilder(); // If we have an env var set for the path, use it. String env = getEnvVar(propertyName, null); if (env != null) { libraryPath.append(env).append(File.pathSeparator); } // Check our extra env vars for the same var, and use it too. env = extraEnv.get(propertyName); if (env != null) { libraryPath.append(env).append(File.pathSeparator); } // Last, add the contents of the specified system property, defaulting to the binary's path. String firefoxLibraryPath = System.getProperty("webdriver.firefox.library.path", binary.getParentFile().getAbsolutePath()); libraryPath.append(firefoxLibraryPath).append(File.pathSeparator).append(libraryPath); // Add the library path to the builder. builder.environment().put(propertyName, libraryPath.toString()); } /** * Locates the firefox binary from a system property. Will throw an exception if the binary * cannot be found. */ private static File locateFirefoxBinaryFromSystemProperty() { String binaryName = System.getProperty("webdriver.firefox.bin"); if (binaryName == null) return null; File binary = new File(binaryName); if (binary.exists()) return binary; switch (Platform.getCurrent()) { case WINDOWS: case VISTA: case XP: if (!binaryName.endsWith(".exe")) binaryName += ".exe"; break; case MAC: if (!binaryName.endsWith(".app")) binaryName += ".app"; binaryName += "/Contents/MacOS/firefox"; break; default: // Fall through } binary = new File(binaryName); if (binary.exists()) return binary; throw new WebDriverException( String.format( "\"webdriver.firefox.bin\" property set, but unable to locate the requested binary: %s", binaryName )); } /** * Locates the firefox binary by platform. */ private static File locateFirefoxBinaryFromPlatform() { File binary = null; switch (Platform.getCurrent()) { case WINDOWS: case VISTA: case XP: binary = new File(getEnvVar("PROGRAMFILES", "\\Program Files") + "\\Mozilla Firefox\\firefox.exe"); if (!binary.exists()) { binary = new File("/Program Files (x86)/Mozilla Firefox/firefox.exe"); } break; case MAC: binary = new File("/Applications/Firefox.app/Contents/MacOS/firefox"); break; default: // Do nothing } return binary != null && binary.exists() ? binary : findBinary("firefox3", "firefox2", "firefox"); } /** * Retrieve an env var; if no var is set, returns the default * * @param name the name of the variable * @param defaultValue the default value of the variable * @return the env var */ private static String getEnvVar(String name, String defaultValue) { final String value = System.getenv(name); if (value != null) { return value; } return defaultValue; } /** * Retrieves the platform specific env property name which contains the library path. */ private static String getLibraryPathPropertyName() { switch (Platform.getCurrent()) { case MAC: return "DYLD_LIBRARY_PATH"; case WINDOWS: case VISTA: case XP: return "PATH"; default: return "LD_LIBRARY_PATH"; } } /** * Walk a PATH to locate binaries with a specified name. Binaries will be searched for in the * order they are provided. * * @param binaryNames the binary names to search for * @return the first binary found matching that name. */ private static File findBinary(String... binaryNames) { final String[] paths = System.getenv("PATH").split(File.pathSeparator); for (String binaryName : binaryNames) { for (String path : paths) { File file = new File(path, binaryName); if (file.exists()) { return file; } if (Platform.getCurrent().is(Platform.WINDOWS)) { File exe = new File(path, binaryName + ".exe"); if (exe.exists()) { return exe; } } } } return null; } }
firefox/src/java/org/openqa/selenium/firefox/internal/Executable.java
package org.openqa.selenium.firefox.internal; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverException; import java.io.File; import java.util.Map; /** * Wrapper around our runtime environment requirements. * Performs discovery of firefox instances. * * <p>NOTE: System and platform binaries will only be discovered at class initialization. * * @author [email protected] (Gregory Block) */ public class Executable { private static final File SYSTEM_BINARY = locateFirefoxBinaryFromSystemProperty(); private static final File PLATFORM_BINARY = locateFirefoxBinaryFromPlatform(); private final File binary; public Executable(File userSpecifiedBinaryPath) { if (userSpecifiedBinaryPath != null) { // It should exist and be a file. if (userSpecifiedBinaryPath.exists() && userSpecifiedBinaryPath.isFile()) { binary = userSpecifiedBinaryPath; return; } throw new WebDriverException( "Specified firefox binary location does not exist or is not a real file: " + userSpecifiedBinaryPath); } if (SYSTEM_BINARY != null && SYSTEM_BINARY.exists()) { binary = SYSTEM_BINARY; return; } if (PLATFORM_BINARY != null && PLATFORM_BINARY.exists()) { binary = PLATFORM_BINARY; return; } throw new WebDriverException("Cannot find firefox binary in PATH. " + "Make sure firefox is installed. OS appears to be: " + Platform.getCurrent()); } public File getFile() { return binary; } public String getPath() { return binary.getAbsolutePath(); } public void setLibraryPath(ProcessBuilder builder, Map<String, String> extraEnv) { final String propertyName = getLibraryPathPropertyName(); StringBuilder libraryPath = new StringBuilder(); // If we have an env var set for the path, use it. String env = getEnvVar(propertyName, null); if (env != null) { libraryPath.append(env).append(File.pathSeparator); } // Check our extra env vars for the same var, and use it too. env = extraEnv.get(propertyName); if (env != null) { libraryPath.append(env).append(File.pathSeparator); } // Last, add the contents of the specified system property, defaulting to the binary's path. String firefoxLibraryPath = System.getProperty("webdriver.firefox.library.path", binary.getParentFile().getAbsolutePath()); libraryPath.append(firefoxLibraryPath).append(File.pathSeparator).append(libraryPath); // Add the library path to the builder. builder.environment().put(propertyName, libraryPath.toString()); } /** * Locates the firefox binary from a system property. Will throw an exception if the binary * cannot be found. */ private static File locateFirefoxBinaryFromSystemProperty() { String binaryName = System.getProperty("webdriver.firefox.bin"); if (binaryName == null) return null; File binary = new File(binaryName); if (binary.exists()) return binary; switch (Platform.getCurrent()) { case WINDOWS: case VISTA: case XP: if (!binaryName.endsWith(".exe")) binaryName += ".exe"; break; case MAC: if (!binaryName.endsWith(".app")) binaryName += ".app"; binaryName += "/Contents/MacOS/firefox"; break; default: // Fall through } binary = new File(binaryName); if (binary.exists()) return binary; throw new WebDriverException( String.format( "\"webdriver.firefox.bin\" property set, but unable to locate the requested binary: %s", binaryName )); } /** * Locates the firefox binary by platform. */ private static File locateFirefoxBinaryFromPlatform() { File binary = null; switch (Platform.getCurrent()) { case WINDOWS: case VISTA: case XP: binary = new File(getEnvVar("PROGRAMFILES", "\\Program Files") + "\\Mozilla Firefox\\firefox.exe"); if (!binary.exists()) { binary = new File("/Program Files (x64)/Mozilla Firefox/firefox.exe"); } break; case MAC: binary = new File("/Applications/Firefox.app/Contents/MacOS/firefox"); break; default: // Do nothing } return binary != null && binary.exists() ? binary : findBinary("firefox3", "firefox2", "firefox"); } /** * Retrieve an env var; if no var is set, returns the default * * @param name the name of the variable * @param defaultValue the default value of the variable * @return the env var */ private static String getEnvVar(String name, String defaultValue) { final String value = System.getenv(name); if (value != null) { return value; } return defaultValue; } /** * Retrieves the platform specific env property name which contains the library path. */ private static String getLibraryPathPropertyName() { switch (Platform.getCurrent()) { case MAC: return "DYLD_LIBRARY_PATH"; case WINDOWS: case VISTA: case XP: return "PATH"; default: return "LD_LIBRARY_PATH"; } } /** * Walk a PATH to locate binaries with a specified name. Binaries will be searched for in the * order they are provided. * * @param binaryNames the binary names to search for * @return the first binary found matching that name. */ private static File findBinary(String... binaryNames) { final String[] paths = System.getenv("PATH").split(File.pathSeparator); for (String binaryName : binaryNames) { for (String path : paths) { File file = new File(path, binaryName); if (file.exists()) { return file; } if (Platform.getCurrent().is(Platform.WINDOWS)) { File exe = new File(path, binaryName + ".exe"); if (exe.exists()) { return exe; } } } } return null; } }
SimonStewart: Firefox binary now successfully found on 64 bit Windows. r6602
firefox/src/java/org/openqa/selenium/firefox/internal/Executable.java
SimonStewart: Firefox binary now successfully found on 64 bit Windows.
<ide><path>irefox/src/java/org/openqa/selenium/firefox/internal/Executable.java <ide> case XP: <ide> binary = new File(getEnvVar("PROGRAMFILES", "\\Program Files") + "\\Mozilla Firefox\\firefox.exe"); <ide> if (!binary.exists()) { <del> binary = new File("/Program Files (x64)/Mozilla Firefox/firefox.exe"); <add> binary = new File("/Program Files (x86)/Mozilla Firefox/firefox.exe"); <ide> } <ide> break; <ide>
JavaScript
mit
604846bb65549aa1d57db07fbdc2de7c77113365
0
OpenCollective/opencollective-api,OpenCollective/opencollective-api,OpenCollective/opencollective-api
import * as utils from './utils'; import { get, pick } from 'lodash'; const allTransactionsQuery = ` query allTransactions($collectiveSlug: String!, $limit: Int, $offset: Int, $type: String) { allTransactions(collectiveSlug: $collectiveSlug, limit: $limit, offset: $offset, type: $type) { id uuid type amount currency hostCurrency hostCurrencyFxRate hostFeeInHostCurrency platformFeeInHostCurrency paymentProcessorFeeInHostCurrency netAmountInCollectiveCurrency createdAt host { id slug } createdByUser { id email } fromCollective { id slug name image } collective { id slug name image } paymentMethod { id service name } } } `; const getTransactionQuery = ` query Transaction($id: Int, $uuid: String) { Transaction(id: $id, uuid: $uuid) { id uuid type createdAt description amount currency hostCurrency hostCurrencyFxRate netAmountInCollectiveCurrency hostFeeInHostCurrency platformFeeInHostCurrency paymentProcessorFeeInHostCurrency paymentMethod { id service name } fromCollective { id slug name image } collective { id slug name image } host { id slug name image } ... on Order { order { id status subscription { id interval } } } } } `; /** * Get array of all transactions of a collective given its slug */ export const getLatestTransactions = async (req, res) => { try { const args = pick(req.query, ['limit', 'offset', 'type']); args.collectiveSlug = get(req, 'params.collectiveSlug'); if (args.limit) { args.limit = Number(args.limit); } if (args.offset) { args.offset = Number(args.offset); } const response = await utils.graphqlQuery(allTransactionsQuery, args, req.remoteUser); if (response.errors) { throw new Error(response.errors[0]); } const result = get(response, 'data.allTransactions', []); res.send({ result }); } catch (error) { res.status(400).send({ error: error.toString() }); } }; /** * Get one transaction of a collective given its uuid */ export const getTransaction = async (req, res) => { try { const response = await utils.graphqlQuery(getTransactionQuery, pick(req.params, ['id', 'uuid']), req.remoteUser); if (response.errors) { throw new Error(response.errors[0]); } const result = get(response, 'data.Transaction'); if (req.params.collectiveSlug !== result.collective.slug) { res.status(404).send({ error: 'Not a collective transaction.' }); } else { res.send({ result }); } } catch (error) { res.status(400).send({ error: error.toString() }); } };
server/graphql/v1/restapi.js
import * as utils from './utils'; import { get, pick } from 'lodash'; const allTransactionsQuery = ` query allTransactions($collectiveSlug: String!, $limit: Int, $offset: Int, $type: String, $includeVirtualCards: Boolean ) { allTransactions(collectiveSlug: $collectiveSlug, limit: $limit, offset: $offset, type: $type, includeVirtualCards: $includeVirtualCards) { id uuid type amount currency hostCurrency hostCurrencyFxRate hostFeeInHostCurrency platformFeeInHostCurrency paymentProcessorFeeInHostCurrency netAmountInCollectiveCurrency createdAt host { id slug } createdByUser { id email } fromCollective { id slug name image } collective { id slug name image } paymentMethod { id service name } } } `; const getTransactionQuery = ` query Transaction($id: Int, $uuid: String) { Transaction(id: $id, uuid: $uuid) { id uuid type createdAt description amount currency hostCurrency hostCurrencyFxRate netAmountInCollectiveCurrency hostFeeInHostCurrency platformFeeInHostCurrency paymentProcessorFeeInHostCurrency paymentMethod { id service name } fromCollective { id slug name image } collective { id slug name image } host { id slug name image } ... on Order { order { id status subscription { id interval } } } } } `; /** * Get array of all transactions of a collective given its slug */ export const getLatestTransactions = async (req, res) => { try { const args = req.query; args.collectiveSlug = get(req, 'params.collectiveSlug'); const response = await utils.graphqlQuery(allTransactionsQuery, req.query, req.remoteUser); if (response.errors) { throw new Error(response.errors[0]); } const result = get(response, 'data.allTransactions', []); res.send({ result }); } catch (error) { res.status(400).send({ error: error.toString() }); } }; /** * Get one transaction of a collective given its uuid */ export const getTransaction = async (req, res) => { try { const response = await utils.graphqlQuery(getTransactionQuery, pick(req.params, ['id', 'uuid']), req.remoteUser); if (response.errors) { throw new Error(response.errors[0]); } const result = get(response, 'data.Transaction'); if (req.params.collectiveSlug !== result.collective.slug) { res.status(404).send({ error: 'Not a collective transaction.' }); } else { res.send({ result }); } } catch (error) { res.status(400).send({ error: error.toString() }); } };
fix: args in allTransactions query
server/graphql/v1/restapi.js
fix: args in allTransactions query
<ide><path>erver/graphql/v1/restapi.js <ide> import { get, pick } from 'lodash'; <ide> <ide> const allTransactionsQuery = ` <del>query allTransactions($collectiveSlug: String!, $limit: Int, $offset: Int, $type: String, $includeVirtualCards: Boolean ) { <del> allTransactions(collectiveSlug: $collectiveSlug, limit: $limit, offset: $offset, type: $type, includeVirtualCards: $includeVirtualCards) { <add>query allTransactions($collectiveSlug: String!, $limit: Int, $offset: Int, $type: String) { <add> allTransactions(collectiveSlug: $collectiveSlug, limit: $limit, offset: $offset, type: $type) { <ide> id <ide> uuid <ide> type <ide> */ <ide> export const getLatestTransactions = async (req, res) => { <ide> try { <del> const args = req.query; <add> const args = pick(req.query, ['limit', 'offset', 'type']); <ide> args.collectiveSlug = get(req, 'params.collectiveSlug'); <del> const response = await utils.graphqlQuery(allTransactionsQuery, req.query, req.remoteUser); <add> if (args.limit) { <add> args.limit = Number(args.limit); <add> } <add> if (args.offset) { <add> args.offset = Number(args.offset); <add> } <add> const response = await utils.graphqlQuery(allTransactionsQuery, args, req.remoteUser); <ide> if (response.errors) { <ide> throw new Error(response.errors[0]); <ide> }
Java
apache-2.0
6795ea5df65e967d3bc277218096d184acbb0018
0
ShortMap/ShortMap,squidsolutions/hadoop-common,sztanko/hadoop-common,ShortMap/ShortMap,sztanko/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,toddlipcon/hadoop,dhootha/hadoop-common,aseldawy/spatialhadoop,coderplay/hadoop-common,dongjiaqiang/hadoop-common,coderplay/hadoop-common,dongjiaqiang/hadoop-common,sztanko/hadoop-common,dhootha/hadoop-common,dhootha/hadoop-common,toddlipcon/hadoop,sztanko/hadoop-common,ShortMap/ShortMap,dongjiaqiang/hadoop-common,dhootha/hadoop-common,sztanko/hadoop-common,squidsolutions/hadoop-common,ShortMap/ShortMap,squidsolutions/hadoop-common,toddlipcon/hadoop,aseldawy/spatialhadoop,toddlipcon/hadoop,ShortMap/ShortMap,sztanko/hadoop-common,hn5092/hadoop-common,aseldawy/spatialhadoop,squidsolutions/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,hn5092/hadoop-common,coderplay/hadoop-common,aseldawy/spatialhadoop,ShortMap/ShortMap,aseldawy/spatialhadoop,aseldawy/spatialhadoop,squidsolutions/hadoop-common,hn5092/hadoop-common,sztanko/hadoop-common,coderplay/hadoop-common,aseldawy/spatialhadoop,hn5092/hadoop-common,toddlipcon/hadoop,dhootha/hadoop-common,hn5092/hadoop-common,squidsolutions/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,toddlipcon/hadoop,coderplay/hadoop-common,squidsolutions/hadoop-common,hn5092/hadoop-common,hn5092/hadoop-common,dongjiaqiang/hadoop-common,toddlipcon/hadoop,squidsolutions/hadoop-common,sztanko/hadoop-common,coderplay/hadoop-common,ShortMap/ShortMap,coderplay/hadoop-common,toddlipcon/hadoop,hn5092/hadoop-common,coderplay/hadoop-common,dongjiaqiang/hadoop-common,coderplay/hadoop-common,hn5092/hadoop-common,squidsolutions/hadoop-common,dongjiaqiang/hadoop-common,dongjiaqiang/hadoop-common,dhootha/hadoop-common,dongjiaqiang/hadoop-common,squidsolutions/hadoop-common,aseldawy/spatialhadoop,dhootha/hadoop-common,sztanko/hadoop-common,sztanko/hadoop-common,toddlipcon/hadoop,ShortMap/ShortMap,dhootha/hadoop-common,hn5092/hadoop-common
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testshell; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; /** * will be in an external jar and used for * test in TestJobShell.java. */ public class ExternalMapReduce implements Mapper<WritableComparable, Writable, WritableComparable, IntWritable>, Reducer<WritableComparable, Writable, WritableComparable, IntWritable> { public void configure(JobConf job) { // do nothing } public void close() throws IOException { } public void map(WritableComparable key, Writable value, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //check for classpath String classpath = System.getProperty("java.class.path"); if (classpath.indexOf("testjob.jar") == -1) { throw new IOException("failed to find in the library " + classpath); } File f = new File("files_tmp"); //check for files if (!f.exists()) { throw new IOException("file file_tmpfile not found"); } } public void reduce(WritableComparable key, Iterator<Writable> values, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //do nothing } public static int main(String[] argv) throws IOException { if (argv.length < 2) { System.out.println("ExternalMapReduce <input> <output>"); return -1; } Path outDir = new Path(argv[1]); Path input = new Path(argv[0]); Configuration commandConf = JobClient.getCommandLineConfig(); JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); testConf.setJobName("external job"); testConf.setInputPath(input); testConf.setOutputPath(outDir); testConf.setMapperClass(ExternalMapReduce.class); testConf.setReducerClass(ExternalMapReduce.class); testConf.setNumReduceTasks(1); JobClient.runJob(testConf); return 0; } }
src/test/testshell/ExternalMapReduce.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testshell; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; /** * will be in an external jar and used for * test in TestJobShell.java. */ public class ExternalMapReduce implements Mapper<WritableComparable, Writable, WritableComparable, IntWritable>, Reducer<WritableComparable, Writable, WritableComparable, IntWritable> { public void configure(JobConf job) { // do nothing } public void close() throws IOException { } public void map(WritableComparable key, Writable value, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //check for classpath String classpath = System.getProperty("java.class.path"); if (classpath.indexOf("testjob.jar") == -1) { throw new IOException("failed to find in the library " + classpath); } File f = new File("files_tmp"); //check for files if (!f.exists()) { throw new IOException("file file_tmpfile not found"); } } public void reduce(WritableComparable key, Iterator<Writable> values, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //do nothing } public static int main(String[] argv) throws IOException { if (argv.length < 2) { System.out.println("ExternalMapReduce <input> <output>"); return -1; } Path outDir = new Path(argv[1]); Path input = new Path(argv[0]); Configuration commandConf = JobClient.getCommandLineConfig(); JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); testConf.setJobName("external job"); testConf.setInputPath(input); testConf.setOutputPath(outDir); testConf.setMapperClass(ExternalMapReduce.class); testConf.setReducerClass(ExternalMapReduce.class); testConf.setNumReduceTasks(1); JobClient.runJob(testConf); return 0; } } /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testshell; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; /** * will be in an external jar and used for * test in TestJobShell.java. */ public class ExternalMapReduce implements Mapper<WritableComparable, Writable, WritableComparable, IntWritable>, Reducer<WritableComparable, Writable, WritableComparable, IntWritable> { public void configure(JobConf job) { // do nothing } public void close() throws IOException { } public void map(WritableComparable key, Writable value, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //check for classpath String classpath = System.getProperty("java.class.path"); if (classpath.indexOf("testjob.jar") == -1) { throw new IOException("failed to find in the library " + classpath); } File f = new File("files_tmp"); //check for files if (!f.exists()) { throw new IOException("file file_tmpfile not found"); } } public void reduce(WritableComparable key, Iterator<Writable> values, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //do nothing } public static int main(String[] argv) throws IOException { if (argv.length < 2) { System.out.println("ExternalMapReduce <input> <output>"); return -1; } Path outDir = new Path(argv[1]); Path input = new Path(argv[0]); Configuration commandConf = JobClient.getCommandLineConfig(); JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); testConf.setJobName("external job"); testConf.setInputPath(input); testConf.setOutputPath(outDir); testConf.setMapperClass(ExternalMapReduce.class); testConf.setReducerClass(ExternalMapReduce.class); testConf.setNumReduceTasks(1); JobClient.runJob(testConf); return 0; } } /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package testshell; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; /** * will be in an external jar and used for * test in TestJobShell.java. */ public class ExternalMapReduce implements Mapper<WritableComparable, Writable, WritableComparable, IntWritable>, Reducer<WritableComparable, Writable, WritableComparable, IntWritable> { public void configure(JobConf job) { // do nothing } public void close() throws IOException { } public void map(WritableComparable key, Writable value, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //check for classpath String classpath = System.getProperty("java.class.path"); if (classpath.indexOf("testjob.jar") == -1) { throw new IOException("failed to find in the library " + classpath); } File f = new File("files_tmp"); //check for files if (!f.exists()) { throw new IOException("file file_tmpfile not found"); } } public void reduce(WritableComparable key, Iterator<Writable> values, OutputCollector<WritableComparable, IntWritable> output, Reporter reporter) throws IOException { //do nothing } public static int main(String[] argv) throws IOException { if (argv.length < 2) { System.out.println("ExternalMapReduce <input> <output>"); return -1; } Path outDir = new Path(argv[1]); Path input = new Path(argv[0]); Configuration commandConf = JobClient.getCommandLineConfig(); JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); testConf.setJobName("external job"); testConf.setInputPath(input); testConf.setOutputPath(outDir); testConf.setMapperClass(ExternalMapReduce.class); testConf.setReducerClass(ExternalMapReduce.class); testConf.setNumReduceTasks(1); JobClient.runJob(testConf); return 0; } }
HADOOP-1622. Allow multiple jar files for map reduce. (Mahadev Konar via dhruba) git-svn-id: 5be3658b1da2303116c04834c161daea58df9cc4@641579 13f79535-47bb-0310-9956-ffa450edef68
src/test/testshell/ExternalMapReduce.java
HADOOP-1622. Allow multiple jar files for map reduce. (Mahadev Konar via dhruba)
<ide><path>rc/test/testshell/ExternalMapReduce.java <ide> return 0; <ide> } <ide> } <del>/** <del> * Licensed to the Apache Software Foundation (ASF) under one <del> * or more contributor license agreements. See the NOTICE file <del> * distributed with this work for additional information <del> * regarding copyright ownership. The ASF licenses this file <del> * to you under the Apache License, Version 2.0 (the <del> * "License"); you may not use this file except in compliance <del> * with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package testshell; <del> <del>import java.io.File; <del>import java.io.IOException; <del>import java.util.Iterator; <del> <del>import org.apache.hadoop.conf.Configuration; <del>import org.apache.hadoop.fs.Path; <del>import org.apache.hadoop.io.IntWritable; <del>import org.apache.hadoop.io.Text; <del>import org.apache.hadoop.io.Writable; <del>import org.apache.hadoop.io.WritableComparable; <del>import org.apache.hadoop.mapred.JobClient; <del>import org.apache.hadoop.mapred.JobConf; <del>import org.apache.hadoop.mapred.Mapper; <del>import org.apache.hadoop.mapred.OutputCollector; <del>import org.apache.hadoop.mapred.Reducer; <del>import org.apache.hadoop.mapred.Reporter; <del> <del>/** <del> * will be in an external jar and used for <del> * test in TestJobShell.java. <del> */ <del>public class ExternalMapReduce <del> implements Mapper<WritableComparable, Writable, <del> WritableComparable, IntWritable>, <del> Reducer<WritableComparable, Writable, <del> WritableComparable, IntWritable> { <del> <del> public void configure(JobConf job) { <del> // do nothing <del> } <del> <del> public void close() <del> throws IOException { <del> <del> } <del> <del> public void map(WritableComparable key, Writable value, <del> OutputCollector<WritableComparable, IntWritable> output, <del> Reporter reporter) <del> throws IOException { <del> //check for classpath <del> String classpath = System.getProperty("java.class.path"); <del> if (classpath.indexOf("testjob.jar") == -1) { <del> throw new IOException("failed to find in the library " + classpath); <del> } <del> File f = new File("files_tmp"); <del> //check for files <del> if (!f.exists()) { <del> throw new IOException("file file_tmpfile not found"); <del> } <del> } <del> <del> public void reduce(WritableComparable key, Iterator<Writable> values, <del> OutputCollector<WritableComparable, IntWritable> output, <del> Reporter reporter) <del> throws IOException { <del> //do nothing <del> } <del> <del> public static int main(String[] argv) throws IOException { <del> if (argv.length < 2) { <del> System.out.println("ExternalMapReduce <input> <output>"); <del> return -1; <del> } <del> Path outDir = new Path(argv[1]); <del> Path input = new Path(argv[0]); <del> Configuration commandConf = JobClient.getCommandLineConfig(); <del> JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); <del> testConf.setJobName("external job"); <del> testConf.setInputPath(input); <del> testConf.setOutputPath(outDir); <del> testConf.setMapperClass(ExternalMapReduce.class); <del> testConf.setReducerClass(ExternalMapReduce.class); <del> testConf.setNumReduceTasks(1); <del> JobClient.runJob(testConf); <del> return 0; <del> } <del>} <del>/** <del> * Licensed to the Apache Software Foundation (ASF) under one <del> * or more contributor license agreements. See the NOTICE file <del> * distributed with this work for additional information <del> * regarding copyright ownership. The ASF licenses this file <del> * to you under the Apache License, Version 2.0 (the <del> * "License"); you may not use this file except in compliance <del> * with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package testshell; <del> <del>import java.io.File; <del>import java.io.IOException; <del>import java.util.Iterator; <del> <del>import org.apache.hadoop.conf.Configuration; <del>import org.apache.hadoop.fs.Path; <del>import org.apache.hadoop.io.IntWritable; <del>import org.apache.hadoop.io.Text; <del>import org.apache.hadoop.io.Writable; <del>import org.apache.hadoop.io.WritableComparable; <del>import org.apache.hadoop.mapred.JobClient; <del>import org.apache.hadoop.mapred.JobConf; <del>import org.apache.hadoop.mapred.Mapper; <del>import org.apache.hadoop.mapred.OutputCollector; <del>import org.apache.hadoop.mapred.Reducer; <del>import org.apache.hadoop.mapred.Reporter; <del> <del>/** <del> * will be in an external jar and used for <del> * test in TestJobShell.java. <del> */ <del>public class ExternalMapReduce <del> implements Mapper<WritableComparable, Writable, <del> WritableComparable, IntWritable>, <del> Reducer<WritableComparable, Writable, <del> WritableComparable, IntWritable> { <del> <del> public void configure(JobConf job) { <del> // do nothing <del> } <del> <del> public void close() <del> throws IOException { <del> <del> } <del> <del> public void map(WritableComparable key, Writable value, <del> OutputCollector<WritableComparable, IntWritable> output, <del> Reporter reporter) <del> throws IOException { <del> //check for classpath <del> String classpath = System.getProperty("java.class.path"); <del> if (classpath.indexOf("testjob.jar") == -1) { <del> throw new IOException("failed to find in the library " + classpath); <del> } <del> File f = new File("files_tmp"); <del> //check for files <del> if (!f.exists()) { <del> throw new IOException("file file_tmpfile not found"); <del> } <del> } <del> <del> public void reduce(WritableComparable key, Iterator<Writable> values, <del> OutputCollector<WritableComparable, IntWritable> output, <del> Reporter reporter) <del> throws IOException { <del> //do nothing <del> } <del> <del> public static int main(String[] argv) throws IOException { <del> if (argv.length < 2) { <del> System.out.println("ExternalMapReduce <input> <output>"); <del> return -1; <del> } <del> Path outDir = new Path(argv[1]); <del> Path input = new Path(argv[0]); <del> Configuration commandConf = JobClient.getCommandLineConfig(); <del> JobConf testConf = new JobConf(commandConf, ExternalMapReduce.class); <del> testConf.setJobName("external job"); <del> testConf.setInputPath(input); <del> testConf.setOutputPath(outDir); <del> testConf.setMapperClass(ExternalMapReduce.class); <del> testConf.setReducerClass(ExternalMapReduce.class); <del> testConf.setNumReduceTasks(1); <del> JobClient.runJob(testConf); <del> return 0; <del> } <del>}
JavaScript
mit
26d395f06740e17e6262fa176a2b04d986cef053
0
javiercejudo/linear-converter,javiercejudo/linear-converter,javiercejudo/linear-converter
/*jshint node:true, mocha:true */ 'use strict'; var should = require('should'); var sinon = require('sinon'); var rescale = require('rescale'); var rescaleUtil = require('rescale-util'); var converter = require('../src/convert.js'); describe('converting', function() { describe('without a preset', function() { it('should be the identity', function() { converter.convert(1).should.be.exactly(1); converter.convert(Math.E).should.be.exactly(Math.E); }); }); describe('with a preset', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate its validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[0, 5], [0, 10]]).returns(true); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[-5, 1], [Math.E, 10.2]]).returns(true); converter.convert(2.5, [[0, 5], [0, 10]]); converter.convert(-3, [[-5, 1], [Math.E, 10.2]]); }); }); describe('with a valid preset', function() { var rescaleStub; beforeEach(function() { rescaleStub = sinon.stub(rescale, 'rescale'); rescaleStub.withArgs('anything', [0, 10], [10, 20]) .onFirstCall().returns(Math.PI) .onSecondCall().returns(34); }); afterEach(function() { rescaleStub.restore(); }); it('should delegate the conversion to rescale', function() { converter.convert('anything', [[0, 10], [10, 20]]).should.be.exactly(Math.PI); converter.convert('anything', [[0, 10], [10, 20]]).should.be.exactly(34); }); }); describe('with an invalid preset', function() { var isValidPresetStub, getLastErrorStub; beforeEach(function() { isValidPresetStub = sinon.stub(rescaleUtil, 'isValidPreset'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); isValidPresetStub.returns(false); getLastErrorStub.returns('an error'); }); afterEach(function() { isValidPresetStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.convert(2, 2); }).should.throw('an error'); }); }); }); describe('inverting', function() { describe('any preset', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate its validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[0, 5], [0, 10]]).returns(true); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[-5, 1], [Math.E, 10.2]]).returns(true); converter.invertPreset([[0, 5], [0, 10]]); converter.invertPreset([[-5, 1], [Math.E, 10.2]]); }); }); describe('with an invalid preset', function() { var isValidPresetStub, getLastErrorStub; beforeEach(function() { isValidPresetStub = sinon.stub(rescaleUtil, 'isValidPreset'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); isValidPresetStub.returns(false); getLastErrorStub.returns('some error'); }); afterEach(function() { isValidPresetStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.invertPreset(2, 2); }).should.throw('some error'); }); }); describe('with a valid preset', function() { it('should invert the preset', function() { converter.invertPreset([[0, 10], [10, 20]]).should.eql([[10, 20], [0, 10]]); converter.invertPreset([[-5, 4], [0.05, -5.4]]).should.eql([[0.05, -5.4], [-5, 4]]); }); }); }); describe('composing', function() { describe('with invalid input', function() { var getLastErrorStub; beforeEach(function() { getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); getLastErrorStub.returns('some other error'); }); afterEach(function() { getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.composePresets(2, 2); }).should.throw('some other error'); }); }); describe('any presets', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate their validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('areValidPresets') .withExactArgs([[[0, 5], [0, 10]], [[-5, 1], [Math.E, 10.2]]]).returns(true); converter.composePresets([[[0, 5], [0, 10]], [[-5, 1], [Math.E, 10.2]]]); }); }); describe('with invalid presets', function() { var areValidPresetsStub, getLastErrorStub; beforeEach(function() { areValidPresetsStub = sinon.stub(rescaleUtil, 'areValidPresets'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); areValidPresetsStub.returns(false); getLastErrorStub.returns('yet another error'); }); afterEach(function() { areValidPresetsStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.composePresets([[[0, 10], [10, Infinity]], [[10, 20], [50, 60]]]); }).should.throw('yet another error'); }); }); describe('with valid presets', function() { it('should compose the presets', function() { converter.composePresets([[[0, 10], [10, 20]], [[10, 20], [50, 60]]]) .should.eql([[0, 10], [50, 60]]); converter.composePresets([[[0, 1], [0, -2]], [[0, 3], [0, -9]]]) .should.eql([[0, 1], [0, 6]]); converter.composePresets([[[1, 2], [2, 4]], [[1, 3], [3, 9]], [[1000, Math.E], [999, Math.E - 1]]]) .should.eql([[1, 2], [5, 11]]); }); }); }); describe('built-in presets', function() { var presets = converter.PRESETS; var convert = converter.convert; var invert = converter.invertPreset; var compose = converter.composePresets; it('should include length', function() { var lengthPresets = presets.distance; (42195).should.be.exactly(convert(42.195, invert(lengthPresets.metreToKilometre)), 'metreToKilometre') .and.exactly(convert(4219500, invert(lengthPresets.metreToCentimetre)), 'metreToCentimetre') .and.exactly(convert(42195000, invert(lengthPresets.metreToMillimetre)), 'metreToMillimetre') .and.approximately(convert(26.218757, invert(lengthPresets.metreToMile)), 10e-4, 'metreToMile') .and.approximately(convert(46145.013, invert(lengthPresets.metreToYard)), 10e-4, 'metreToYard') .and.approximately(convert(138435.04, invert(lengthPresets.metreToFoot)), 10e-3, 'metreToFoot') .and.approximately(convert(1661220.5, invert(lengthPresets.metreToInch)), 10e-2, 'metreToInch') .and.approximately(convert(22.783477, invert(lengthPresets.metreToNauticalMile)), 10e-4, 'metreToNauticalMile'); }); it('should include mass', function() { var massPresets = presets.mass; (10).should.be.exactly(convert(0.01, invert(massPresets.kilogramToMetricTon)), 'kilogramToMetricTon') .and.exactly(convert(10000, invert(massPresets.kilogramToGram)), 'kilogramToGram') .and.exactly(convert(1e+7, invert(massPresets.kilogramToMilligram)), 'kilogramToMilligram') .and.exactly(convert(1e+10, invert(massPresets.kilogramToMicrogram)), 'kilogramToMicrogram') .and.approximately(convert(0.00984207, invert(massPresets.kilogramToLongTon)), 10e-6, 'kilogramToLongTon') .and.approximately(convert(0.0110231, invert(massPresets.kilogramToShortTon)), 10e-5, 'kilogramToShortTon') .and.approximately(convert(1.57473, invert(massPresets.kilogramToStone)), 10e-6, 'kilogramToStone') .and.approximately(convert(22.0462, invert(massPresets.kilogramToPound)), 10e-5, 'kilogramToPound') .and.approximately(convert(352.74, invert(massPresets.kilogramToOunce)), 10e-5, 'kilogramToOunce'); }); it.skip('should include time', function() { should(converter.PRESETS.time).be.an.Object.and.not.eql({}); }); it.skip('should include electric current', function() { should(converter.PRESETS.electricCurrent).be.an.Object.and.not.eql({}); }); it('should include temperature', function() { var temperaturePresets = presets.temperature; (40).should.be.exactly(convert(104, invert(temperaturePresets.celsiusToFahrenheit)), 'celsiusToFahrenheit') .and.exactly(convert(313.15, invert(temperaturePresets.celsiusToKelvin)), 'celsiusToKelvin') .and.approximately(convert(563.67, invert(temperaturePresets.celsiusToRankine)), 10e-14, 'celsiusToRankine') .and.exactly(convert(90, invert(temperaturePresets.celsiusToDelisle)), 'celsiusToDelisle') .and.exactly(convert(13.2, invert(temperaturePresets.celsiusToNewton)), 'celsiusToNewton') .and.exactly(convert(32, invert(temperaturePresets.celsiusToReaumur)), 'celsiusToReaumur') .and.exactly(convert(28.5, invert(temperaturePresets.celsiusToRomer)), 'celsiusToRomer'); }); it.skip('should include amount of substance', function() { should(converter.PRESETS.amountOfSubstance).be.an.Object.and.not.eql({}); }); it.skip('should include luminous intensity', function() { should(converter.PRESETS.luminousIntensity).be.an.Object.and.not.eql({}); }); it.skip('should include speed', function() { should(converter.PRESETS.speed).be.an.Object.and.not.eql({}); }); it.skip('should include volume', function() { should(converter.PRESETS.volume).be.an.Object.and.not.eql({}); }); it.skip('should include area', function() { should(converter.PRESETS.area).be.an.Object.and.not.eql({}); }); it.skip('should include fuel consumption', function() { should(converter.PRESETS.fuelConsumption).be.an.Object.and.not.eql({}); }); it.skip('should include digital storage', function() { should(converter.PRESETS.digitalStorage).be.an.Object.and.not.eql({}); }); });
test/spec.js
/*jshint node:true, mocha:true */ 'use strict'; var should = require('should'); var sinon = require('sinon'); var rescale = require('rescale'); var rescaleUtil = require('rescale-util'); var converter = require('../src/convert.js'); describe('converting', function() { describe('without a preset', function() { it('should be the identity', function() { converter.convert(1).should.be.exactly(1); converter.convert(Math.E).should.be.exactly(Math.E); }); }); describe('with a preset', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate its validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[0, 5], [0, 10]]).returns(true); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[-5, 1], [Math.E, 10.2]]).returns(true); converter.convert(2.5, [[0, 5], [0, 10]]); converter.convert(-3, [[-5, 1], [Math.E, 10.2]]); }); }); describe('with a valid preset', function() { var rescaleStub; beforeEach(function() { rescaleStub = sinon.stub(rescale, 'rescale'); rescaleStub.withArgs('anything', [0, 10], [10, 20]) .onFirstCall().returns(Math.PI) .onSecondCall().returns(34); }); afterEach(function() { rescaleStub.restore(); }); it('should delegate the conversion to rescale', function() { converter.convert('anything', [[0, 10], [10, 20]]).should.be.exactly(Math.PI); converter.convert('anything', [[0, 10], [10, 20]]).should.be.exactly(34); }); }); describe('with an invalid preset', function() { var isValidPresetStub, getLastErrorStub; beforeEach(function() { isValidPresetStub = sinon.stub(rescaleUtil, 'isValidPreset'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); isValidPresetStub.returns(false); getLastErrorStub.returns('an error'); }); afterEach(function() { isValidPresetStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.convert(2, 2); }).should.throw('an error'); }); }); }); describe('inverting', function() { describe('any preset', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate its validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[0, 5], [0, 10]]).returns(true); rescaleUtilMock.expects('isValidPreset') .withExactArgs([[-5, 1], [Math.E, 10.2]]).returns(true); converter.invertPreset([[0, 5], [0, 10]]); converter.invertPreset([[-5, 1], [Math.E, 10.2]]); }); }); describe('with an invalid preset', function() { var isValidPresetStub, getLastErrorStub; beforeEach(function() { isValidPresetStub = sinon.stub(rescaleUtil, 'isValidPreset'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); isValidPresetStub.returns(false); getLastErrorStub.returns('some error'); }); afterEach(function() { isValidPresetStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.invertPreset(2, 2); }).should.throw('some error'); }); }); describe('with a valid preset', function() { it('should invert the preset', function() { converter.invertPreset([[0, 10], [10, 20]]).should.eql([[10, 20], [0, 10]]); converter.invertPreset([[-5, 4], [0.05, -5.4]]).should.eql([[0.05, -5.4], [-5, 4]]); }); }); }); describe('composing', function() { describe('with invalid input', function() { var getLastErrorStub; beforeEach(function() { getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); getLastErrorStub.returns('some other error'); }); afterEach(function() { getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.composePresets(2, 2); }).should.throw('some other error'); }); }); describe('any presets', function() { var rescaleUtilMock; afterEach(function() { rescaleUtilMock.verify(); }); it('should delegate their validation to rescale-util', function() { rescaleUtilMock = sinon.mock(rescaleUtil); rescaleUtilMock.expects('areValidPresets') .withExactArgs([[[0, 5], [0, 10]], [[-5, 1], [Math.E, 10.2]]]).returns(true); converter.composePresets([[[0, 5], [0, 10]], [[-5, 1], [Math.E, 10.2]]]); }); }); describe('with invalid presets', function() { var areValidPresetsStub, getLastErrorStub; beforeEach(function() { areValidPresetsStub = sinon.stub(rescaleUtil, 'areValidPresets'); getLastErrorStub = sinon.stub(rescaleUtil, 'getLastError'); areValidPresetsStub.returns(false); getLastErrorStub.returns('yet another error'); }); afterEach(function() { areValidPresetsStub.restore(); getLastErrorStub.restore(); }); it('should throw an error', function() { (function() { converter.composePresets([[[0, 10], [10, Infinity]], [[10, 20], [50, 60]]]); }).should.throw('yet another error'); }); }); describe('with valid presets', function() { it('should compose the presets', function() { converter.composePresets([[[0, 10], [10, 20]], [[10, 20], [50, 60]]]) .should.eql([[0, 10], [50, 60]]); converter.composePresets([[[0, 1], [0, -2]], [[0, 3], [0, -9]]]) .should.eql([[0, 1], [0, 6]]); converter.composePresets([[[1, 2], [2, 4]], [[1, 3], [3, 9]], [[1000, Math.E], [999, Math.E - 1]]]) .should.eql([[1, 2], [5, 11]]); }); }); }); describe('built-in presets', function() { var presets = converter.PRESETS; var convert = converter.convert; var invert = converter.invertPreset; var compose = converter.composePresets; it('should include length', function() { var lengthPresets = presets.distance; (42195).should.be.exactly(convert(42.195, invert(lengthPresets.metreToKilometre)), 'metreToKilometre') .and.exactly(convert(4219500, invert(lengthPresets.metreToCentimetre)), 'metreToCentimetre') .and.exactly(convert(42195000, invert(lengthPresets.metreToMillimetre)), 'metreToMillimetre') .and.approximately(convert(26.218757, invert(lengthPresets.metreToMile)), 10e-4, 'metreToMile') .and.approximately(convert(46145.013, invert(lengthPresets.metreToYard)), 10e-4, 'metreToYard') .and.approximately(convert(138435.04, invert(lengthPresets.metreToFoot)), 10e-3, 'metreToFoot') .and.approximately(convert(1661220.5, invert(lengthPresets.metreToInch)), 10e-2, 'metreToInch') .and.approximately(convert(22.783477, invert(lengthPresets.metreToNauticalMile)), 10e-4, 'metreToNauticalMile'); }); it('should include mass', function() { var massPresets = presets.mass; (10).should.be.exactly(convert(0.01, invert(massPresets.kilogramToMetricTon)), 'kilogramToMetricTon') .and.exactly(convert(10000, invert(massPresets.kilogramToGram)), 'kilogramToGram') .and.exactly(convert(1e+7, invert(massPresets.kilogramToMilligram)), 'kilogramToMilligram') .and.exactly(convert(1e+10, invert(massPresets.kilogramToMicrogram))) .and.approximately(convert(0.00984207, invert(massPresets.kilogramToLongTon)), 10e-6) .and.approximately(convert(0.0110231, invert(massPresets.kilogramToShortTon)), 10e-5, 'kilogramToShortTon') .and.approximately(convert(1.57473, invert(massPresets.kilogramToStone)), 10e-6, 'kilogramToStone') .and.approximately(convert(22.0462, invert(massPresets.kilogramToPound)), 10e-5, 'kilogramToPound') .and.approximately(convert(352.74, invert(massPresets.kilogramToOunce)), 10e-5, 'kilogramToOunce'); }); it.skip('should include time', function() { should(converter.PRESETS.time).be.an.Object.and.not.eql({}); }); it.skip('should include electric current', function() { should(converter.PRESETS.electricCurrent).be.an.Object.and.not.eql({}); }); it('should include temperature', function() { var temperaturePresets = presets.temperature; (40).should.be.exactly(convert(104, invert(temperaturePresets.celsiusToFahrenheit)), 'celsiusToFahrenheit') .and.exactly(convert(313.15, invert(temperaturePresets.celsiusToKelvin)), 'celsiusToKelvin') .and.approximately(convert(563.67, invert(temperaturePresets.celsiusToRankine)), 10e-14, 'celsiusToRankine') .and.exactly(convert(90, invert(temperaturePresets.celsiusToDelisle)), 'celsiusToDelisle') .and.exactly(convert(13.2, invert(temperaturePresets.celsiusToNewton)), 'celsiusToNewton') .and.exactly(convert(32, invert(temperaturePresets.celsiusToReaumur)), 'celsiusToReaumur') .and.exactly(convert(28.5, invert(temperaturePresets.celsiusToRomer)), 'celsiusToRomer'); }); it.skip('should include amount of substance', function() { should(converter.PRESETS.amountOfSubstance).be.an.Object.and.not.eql({}); }); it.skip('should include luminous intensity', function() { should(converter.PRESETS.luminousIntensity).be.an.Object.and.not.eql({}); }); it.skip('should include speed', function() { should(converter.PRESETS.speed).be.an.Object.and.not.eql({}); }); it.skip('should include volume', function() { should(converter.PRESETS.volume).be.an.Object.and.not.eql({}); }); it.skip('should include area', function() { should(converter.PRESETS.area).be.an.Object.and.not.eql({}); }); it.skip('should include fuel consumption', function() { should(converter.PRESETS.fuelConsumption).be.an.Object.and.not.eql({}); }); it.skip('should include digital storage', function() { should(converter.PRESETS.digitalStorage).be.an.Object.and.not.eql({}); }); });
chore(presets): add custom message
test/spec.js
chore(presets): add custom message
<ide><path>est/spec.js <ide> (10).should.be.exactly(convert(0.01, invert(massPresets.kilogramToMetricTon)), 'kilogramToMetricTon') <ide> .and.exactly(convert(10000, invert(massPresets.kilogramToGram)), 'kilogramToGram') <ide> .and.exactly(convert(1e+7, invert(massPresets.kilogramToMilligram)), 'kilogramToMilligram') <del> .and.exactly(convert(1e+10, invert(massPresets.kilogramToMicrogram))) <del> .and.approximately(convert(0.00984207, invert(massPresets.kilogramToLongTon)), 10e-6) <add> .and.exactly(convert(1e+10, invert(massPresets.kilogramToMicrogram)), 'kilogramToMicrogram') <add> .and.approximately(convert(0.00984207, invert(massPresets.kilogramToLongTon)), 10e-6, 'kilogramToLongTon') <ide> .and.approximately(convert(0.0110231, invert(massPresets.kilogramToShortTon)), 10e-5, 'kilogramToShortTon') <ide> .and.approximately(convert(1.57473, invert(massPresets.kilogramToStone)), 10e-6, 'kilogramToStone') <ide> .and.approximately(convert(22.0462, invert(massPresets.kilogramToPound)), 10e-5, 'kilogramToPound')
Java
apache-2.0
11be9d0d59cc4d5cef658d0ac1df8448a43bada0
0
shevek/spring-rich-client,shevek/spring-rich-client
/* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.richclient.application; import javax.swing.SwingUtilities; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.richclient.application.splash.SplashScreen; import org.springframework.richclient.progress.ProgressMonitor; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * The main driver for a Spring Rich Client application. This class displays a * configurable splash screen and instantiates the rich client <code>Application</code> * instance. * * @author Keith Donald * @see Application */ public class ApplicationLauncher { public static final String SPLASH_SCREEN_BEAN_ID = "splashScreen"; public static final String APPLICATION_BEAN_ID = "application"; private final Log logger = LogFactory.getLog(getClass()); private ApplicationContext startupContext; private SplashScreen splashScreen; private ApplicationContext rootApplicationContext; /** * Launch the application using the spring application context at the provided path * for configuration. * * @param rootContextPath the classpath application context path */ public ApplicationLauncher(String rootContextPath) { this(new String[] {rootContextPath}); } /** * Launch the application using the spring application context at the provided paths * for configuration. * * @param rootContextPath the classpath application context paths */ public ApplicationLauncher(String[] rootContextPath) { this(null, rootContextPath); } /** * Launch the application using the spring application context at the provided paths * for configuration. The startup context path is loaded first to allow for quick * loading of the application splash screen. * * @param startupContext the startup context classpath * @param contextPaths the classpath application context paths */ public ApplicationLauncher(String startupContext, String rootContextPath) { this(startupContext, new String[] {rootContextPath}); } /** * Launch the application using the spring application context at the provided paths * for configuration. The startup context path is loaded first to allow for quick * loading of the application splash screen. * * @param startupContextPath the startup context classpath * @param rootContextPath the classpath application context paths */ public ApplicationLauncher(String startupContextPath, String[] rootContextPath) { Assert.notEmpty(rootContextPath, "One or more root rich client application context paths must be provided"); this.startupContext = loadStartupContext(startupContextPath); if (startupContext != null) { displaySplashScreen(startupContext); } setRootApplicationContext(loadRootApplicationContext(rootContextPath)); launchMyRichClient(); } private ApplicationContext loadRootApplicationContext(String[] contextPaths) { try { final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextPaths, false); final ProgressMonitor tracker = splashScreen.getProgressMonitor(); applicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.addBeanPostProcessor(new BeanPostProcessor() { private int max = -1; public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (max == -1) { max = 0; String[] beanNames = applicationContext.getBeanDefinitionNames(); for (int i = 0; i < beanNames.length; i++) { if (applicationContext.isSingleton(beanNames[i])) max++; } tracker.taskStarted("Loading Application Context ...", max); } if (applicationContext.containsLocalBean(beanName)) { tracker.subTaskStarted("Loading " + beanName + " ..."); tracker.worked(1); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }); } }); applicationContext.refresh(); return applicationContext; } catch (Exception e) { logger.warn("Exception occured initializing application startup context.", e); destroySplashScreen(); // when app context fails to load, destroy // splashscreen throw new ApplicationException("Unable to start rich client application", e); } } /** * Launch the application from the pre-loaded application context. * * @param context the application context. */ public ApplicationLauncher(String startupContextPath, ApplicationContext rootApplicationContext) { this.startupContext = loadStartupContext(startupContextPath); if (startupContext != null) { displaySplashScreen(startupContext); } setRootApplicationContext(rootApplicationContext); launchMyRichClient(); } /** * Launch the application from the pre-loaded application context. * * @param context the application context. */ public ApplicationLauncher(ApplicationContext rootApplicationContext) { setRootApplicationContext(rootApplicationContext); launchMyRichClient(); } private void setRootApplicationContext(ApplicationContext context) { Assert.notNull(context, "The root rich client application context is required"); this.rootApplicationContext = context; } private ApplicationContext loadStartupContext(String startupContextPath) { logger.info("Loading startup context..."); try { if (StringUtils.hasText(startupContextPath)) { return new ClassPathXmlApplicationContext(startupContextPath); } } catch (Exception e) { logger.warn("Exception occured initializing startup context.", e); } return null; } /** * Launch this rich client application; with the startup context loading first, built * from the <code>startupContextPath</code> location in the classpath. * <p> * It is recommended that the startup context contain contain a splash screen * definition for quick loading & display. * <p> * Once the splash screen is displayed, the main application context is then * initialized, built from the <code>contextPaths</code> location(s) in the * classpath. The root application bean is retrieved and the startup lifecycle begins. */ private void launchMyRichClient() { if (startupContext == null) { displaySplashScreen(rootApplicationContext); } try { Application application = (Application)rootApplicationContext.getBean(APPLICATION_BEAN_ID, Application.class); application.start(); } catch (NoSuchBeanDefinitionException e) { logger.error("A single org.springframework.richclient.Application bean definition must be defined " + "in the main application context", e); throw e; } catch (RuntimeException e) { logger.error("Exception occured initializing Application bean", e); throw new ApplicationException("Unable to start rich client application", e); } finally { destroySplashScreen(); logger.debug("Launcher thread exiting..."); } } private void displaySplashScreen(BeanFactory beanFactory) { try { if (beanFactory.containsBean(SPLASH_SCREEN_BEAN_ID)) { this.splashScreen = (SplashScreen)beanFactory.getBean(SPLASH_SCREEN_BEAN_ID, SplashScreen.class); logger.info("Displaying application splash screen..."); this.splashScreen.splash(); } else { logger.info("No splash screen bean found to display--continuing..."); } } catch (Exception e) { logger.warn("Unable to load and display startup splash screen.", e); } } private void destroySplashScreen() { if (splashScreen != null) { logger.debug("Closing splash screen..."); SwingUtilities.invokeLater(new Runnable() { public void run() { splashScreen.dispose(); splashScreen = null; } }); } } }
support/src/main/java/org/springframework/richclient/application/ApplicationLauncher.java
/* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.richclient.application; import javax.swing.SwingUtilities; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.richclient.application.splash.SplashScreen; import org.springframework.richclient.progress.ProgressMonitor; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * The main driver for a Spring Rich Client application. This class displays a * configurable splash screen and instantiates the rich client <code>Application</code> * instance. * * @author Keith Donald * @see Application */ public class ApplicationLauncher { public static final String SPLASH_SCREEN_BEAN_ID = "splashScreen"; public static final String APPLICATION_BEAN_ID = "application"; private final Log logger = LogFactory.getLog(getClass()); private ApplicationContext startupContext; private SplashScreen splashScreen; private ApplicationContext rootApplicationContext; /** * Launch the application using the spring application context at the provided path * for configuration. * * @param rootContextPath the classpath application context path */ public ApplicationLauncher(String rootContextPath) { this(new String[] {rootContextPath}); } /** * Launch the application using the spring application context at the provided paths * for configuration. * * @param rootContextPath the classpath application context paths */ public ApplicationLauncher(String[] rootContextPath) { this(null, rootContextPath); } /** * Launch the application using the spring application context at the provided paths * for configuration. The startup context path is loaded first to allow for quick * loading of the application splash screen. * * @param startupContext the startup context classpath * @param contextPaths the classpath application context paths */ public ApplicationLauncher(String startupContext, String rootContextPath) { this(startupContext, new String[] {rootContextPath}); } /** * Launch the application using the spring application context at the provided paths * for configuration. The startup context path is loaded first to allow for quick * loading of the application splash screen. * * @param startupContextPath the startup context classpath * @param rootContextPath the classpath application context paths */ public ApplicationLauncher(String startupContextPath, String[] rootContextPath) { Assert.notEmpty(rootContextPath, "One or more root rich client application context paths must be provided"); this.startupContext = loadStartupContext(startupContextPath); if (startupContext != null) { displaySplashScreen(startupContext); } setRootApplicationContext(loadRootApplicationContext(rootContextPath)); launchMyRichClient(); } private ApplicationContext loadRootApplicationContext(String[] contextPaths) { try { final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextPaths, false); final ProgressMonitor tracker = splashScreen.getProgressMonitor(); applicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.addBeanPostProcessor(new BeanPostProcessor() { private int max = -1; public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (max == -1) { String[] beanNames = applicationContext.getBeanDefinitionNames(); for (int i = 0; i < beanNames.length; i++) { if (applicationContext.isSingleton(beanNames[i])) max++; } tracker.taskStarted("Loading Application Context ...", max + 1); } if (applicationContext.containsLocalBean(beanName)) { tracker.subTaskStarted("Loading " + beanName + " ..."); tracker.worked(1); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }); } }); applicationContext.refresh(); return applicationContext; } catch (Exception e) { logger.warn("Exception occured initializing application startup context.", e); destroySplashScreen(); // when app context fails to load, destroy // splashscreen throw new ApplicationException("Unable to start rich client application", e); } } /** * Launch the application from the pre-loaded application context. * * @param context the application context. */ public ApplicationLauncher(String startupContextPath, ApplicationContext rootApplicationContext) { this.startupContext = loadStartupContext(startupContextPath); if (startupContext != null) { displaySplashScreen(startupContext); } setRootApplicationContext(rootApplicationContext); launchMyRichClient(); } /** * Launch the application from the pre-loaded application context. * * @param context the application context. */ public ApplicationLauncher(ApplicationContext rootApplicationContext) { setRootApplicationContext(rootApplicationContext); launchMyRichClient(); } private void setRootApplicationContext(ApplicationContext context) { Assert.notNull(context, "The root rich client application context is required"); this.rootApplicationContext = context; } private ApplicationContext loadStartupContext(String startupContextPath) { logger.info("Loading startup context..."); try { if (StringUtils.hasText(startupContextPath)) { return new ClassPathXmlApplicationContext(startupContextPath); } } catch (Exception e) { logger.warn("Exception occured initializing startup context.", e); } return null; } /** * Launch this rich client application; with the startup context loading first, built * from the <code>startupContextPath</code> location in the classpath. * <p> * It is recommended that the startup context contain contain a splash screen * definition for quick loading & display. * <p> * Once the splash screen is displayed, the main application context is then * initialized, built from the <code>contextPaths</code> location(s) in the * classpath. The root application bean is retrieved and the startup lifecycle begins. */ private void launchMyRichClient() { if (startupContext == null) { displaySplashScreen(rootApplicationContext); } try { Application application = (Application)rootApplicationContext.getBean(APPLICATION_BEAN_ID, Application.class); application.start(); } catch (NoSuchBeanDefinitionException e) { logger.error("A single org.springframework.richclient.Application bean definition must be defined " + "in the main application context", e); throw e; } catch (RuntimeException e) { logger.error("Exception occured initializing Application bean", e); throw new ApplicationException("Unable to start rich client application", e); } finally { destroySplashScreen(); logger.debug("Launcher thread exiting..."); } } private void displaySplashScreen(BeanFactory beanFactory) { try { if (beanFactory.containsBean(SPLASH_SCREEN_BEAN_ID)) { this.splashScreen = (SplashScreen)beanFactory.getBean(SPLASH_SCREEN_BEAN_ID, SplashScreen.class); logger.info("Displaying application splash screen..."); this.splashScreen.splash(); } else { logger.info("No splash screen bean found to display--continuing..."); } } catch (Exception e) { logger.warn("Unable to load and display startup splash screen.", e); } } private void destroySplashScreen() { if (splashScreen != null) { logger.debug("Closing splash screen..."); SwingUtilities.invokeLater(new Runnable() { public void run() { splashScreen.dispose(); splashScreen = null; } }); } } }
when there are no singleton beans, the max was calculated for every bean git-svn-id: 789609e278efc0cd74c84a9bb7abaca0738de801@1398 817809c7-9d0e-0410-b92d-a7ac8b8adc13
support/src/main/java/org/springframework/richclient/application/ApplicationLauncher.java
when there are no singleton beans, the max was calculated for every bean
<ide><path>upport/src/main/java/org/springframework/richclient/application/ApplicationLauncher.java <ide> public Object postProcessBeforeInitialization(Object bean, String beanName) <ide> throws BeansException { <ide> if (max == -1) { <add> max = 0; <ide> String[] beanNames = applicationContext.getBeanDefinitionNames(); <ide> for (int i = 0; i < beanNames.length; i++) { <ide> if (applicationContext.isSingleton(beanNames[i])) <ide> max++; <ide> } <del> tracker.taskStarted("Loading Application Context ...", max + 1); <add> tracker.taskStarted("Loading Application Context ...", max); <ide> } <ide> <ide> if (applicationContext.containsLocalBean(beanName)) {
Java
epl-1.0
1f7684265377c16d0be024d2a393b85a3ea8a2f2
0
LorenzoBettini/jbase,LorenzoBettini/jbase,LorenzoBettini/jbase
/** * */ package jbase.compiler; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.xtext.EcoreUtil2; import org.eclipse.xtext.common.types.JvmField; import org.eclipse.xtext.common.types.JvmFormalParameter; import org.eclipse.xtext.common.types.JvmIdentifiableElement; import org.eclipse.xtext.common.types.JvmOperation; import org.eclipse.xtext.common.types.JvmType; import org.eclipse.xtext.common.types.JvmTypeReference; import org.eclipse.xtext.common.types.TypesPackage; import org.eclipse.xtext.generator.trace.ILocationData; import org.eclipse.xtext.util.Strings; import org.eclipse.xtext.xbase.XAbstractFeatureCall; import org.eclipse.xtext.xbase.XAssignment; import org.eclipse.xtext.xbase.XBasicForLoopExpression; import org.eclipse.xtext.xbase.XCasePart; import org.eclipse.xtext.xbase.XExpression; import org.eclipse.xtext.xbase.XForLoopExpression; import org.eclipse.xtext.xbase.XNumberLiteral; import org.eclipse.xtext.xbase.XSwitchExpression; import org.eclipse.xtext.xbase.XUnaryOperation; import org.eclipse.xtext.xbase.XVariableDeclaration; import org.eclipse.xtext.xbase.XbasePackage; import org.eclipse.xtext.xbase.compiler.output.ITreeAppendable; import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; import com.google.common.base.Joiner; import com.google.inject.Inject; import jbase.controlflow.JbaseBranchingStatementDetector; import jbase.jbase.XJArrayAccess; import jbase.jbase.XJArrayAccessExpression; import jbase.jbase.XJArrayConstructorCall; import jbase.jbase.XJArrayLiteral; import jbase.jbase.XJBranchingStatement; import jbase.jbase.XJBreakStatement; import jbase.jbase.XJCharLiteral; import jbase.jbase.XJClassObject; import jbase.jbase.XJContinueStatement; import jbase.jbase.XJJvmFormalParameter; import jbase.jbase.XJPrefixOperation; import jbase.jbase.XJSemicolonStatement; import jbase.jbase.XJVariableDeclaration; import jbase.util.JbaseExpressionHelper; import jbase.util.JbaseExpressionHelper.BaseCase; import jbase.util.JbaseExpressionHelper.StepCase; import jbase.util.JbaseModelUtil; /** * @author Lorenzo Bettini * */ public class JbaseXbaseCompiler extends PatchedXbaseCompiler { private static final String ASSIGNED_TRUE = " = true;"; @Inject private JbaseModelUtil modelUtil; @Inject private JbaseBranchingStatementDetector branchingStatementDetector; @Inject private JbaseExpressionHelper expressionHelper; @Override protected void doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) { if (obj instanceof XJArrayConstructorCall) { _toJavaStatement((XJArrayConstructorCall) obj, appendable, isReferenced); } else if (obj instanceof XJArrayAccessExpression) { _toJavaStatement((XJArrayAccessExpression) obj, appendable, isReferenced); } else if (obj instanceof XJContinueStatement) { _toJavaStatement((XJContinueStatement) obj, appendable, isReferenced); } else if (obj instanceof XJBreakStatement) { _toJavaStatement((XJBreakStatement) obj, appendable, isReferenced); } else if (obj instanceof XJClassObject) { _toJavaStatement((XJClassObject) obj, appendable, isReferenced); } else if (obj instanceof XJSemicolonStatement) { _toJavaStatement((XJSemicolonStatement) obj, appendable, isReferenced); } else { super.doInternalToJavaStatement(obj, appendable, isReferenced); } } public void _toJavaStatement(XJArrayConstructorCall call, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(XJArrayAccessExpression access, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(XJContinueStatement st, ITreeAppendable b, boolean isReferenced) { XBasicForLoopExpression basicForLoop = EcoreUtil2.getContainerOfType(st, XBasicForLoopExpression.class); if (basicForLoop != null && !canCompileToJavaBasicForStatement(basicForLoop, b)) { // the for loop is translated into a while statement, so, before // the continue; we must perform the update expressions and then // check the while condition. EList<XExpression> updateExpressions = basicForLoop.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, b, false); } final String varName = b.getName(basicForLoop); XExpression expression = basicForLoop.getExpression(); if (expression != null) { internalToJavaStatement(expression, b, true); b.newLine().append(varName).append(" = "); internalToJavaExpression(expression, b); b.append(";"); } else { b.newLine().append(varName).append(ASSIGNED_TRUE); } } compileBranchingStatement(st, b, "continue"); } public void _toJavaStatement(XJBreakStatement st, ITreeAppendable b, boolean isReferenced) { compileBranchingStatement(st, b, "break"); } public void _toJavaStatement(XJClassObject e, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } private void compileClassObject(XJClassObject e, ITreeAppendable b) { XAbstractFeatureCall featureCall = (XAbstractFeatureCall) e.getTypeExpression(); // we must append it as a JvmType so that the corresponding import statement // is generated in the Java code b.append((JvmType) featureCall.getFeature()). append(Joiner.on("").join(e.getArrayDimensions())).append(".class"); } private void compileBranchingStatement(XJBranchingStatement st, ITreeAppendable b, String instruction) { b.newLine().append(instruction).append(";"); } public void _toJavaStatement(XJSemicolonStatement st, ITreeAppendable b, boolean isReferenced) { XExpression expression = st.getExpression(); if (expression != null) { doInternalToJavaStatement(expression, b, isReferenced); } else { b.append(";"); } } @Override protected void internalToConvertedExpression(XExpression obj, ITreeAppendable appendable) { if (obj instanceof XJArrayConstructorCall) { _toJavaExpression((XJArrayConstructorCall) obj, appendable); } else if (obj instanceof XJArrayAccessExpression) { _toJavaExpression((XJArrayAccessExpression) obj, appendable); } else if (obj instanceof XJCharLiteral) { _toJavaExpression((XJCharLiteral) obj, appendable); } else if (obj instanceof XJClassObject) { _toJavaExpression((XJClassObject) obj, appendable); } else { super.internalToConvertedExpression(obj, appendable); } } public void _toJavaExpression(XJArrayConstructorCall call, ITreeAppendable b) { if (call.getArrayLiteral() == null) { // otherwise we simply compile the array literal // assuming that no dimension expression has been specified // (checked by the validator) b.append("new "); b.append(call.getType()); } compileArrayAccess(call, b); } public void _toJavaExpression(XJArrayAccessExpression arrayAccess, ITreeAppendable b) { internalToConvertedExpression(arrayAccess.getArray(), b); compileArrayAccess(arrayAccess, b); } public void _toJavaExpression(XJClassObject e, ITreeAppendable b) { compileClassObject(e, b); } /** * Always compile into a char literal (we've already type checked that, and we * can assign it also to numeric variables as in Java). * * @param literal * @param appendable */ public void _toJavaExpression(XJCharLiteral literal, ITreeAppendable appendable) { String javaString = Strings.convertToJavaString(literal.getValue(), true); appendable.append("'").append(javaString).append("'"); } @Override protected void assignmentToJavaExpression(XAssignment expr, ITreeAppendable b, boolean isExpressionContext) { final JvmIdentifiableElement feature = expr.getFeature(); if (!(feature instanceof JvmOperation)) { boolean isArgument = expr.eContainer() instanceof XAbstractFeatureCall; if (isArgument) { EStructuralFeature containingFeature = expr.eContainingFeature(); if (containingFeature == XbasePackage.Literals.XFEATURE_CALL__FEATURE_CALL_ARGUMENTS || containingFeature == XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_ARGUMENTS) { isArgument = false; } else { b.append("("); } } if (feature instanceof JvmField) { appendReceiver(expr, b, isExpressionContext); b.append("."); appendFeatureCall(expr, b); } else { String name = b.getName(expr.getFeature()); b.append(name); } // custom implementation starts here compileArrayAccess(expr, b); // custom implementation ends here b.append(" = "); internalToJavaExpression(expr.getValue(), b); if (isArgument) { b.append(")"); } return; } super.assignmentToJavaExpression(expr, b, isExpressionContext); } /** * Overridden to deal with several variable declarations. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaBasicForStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaBasicForStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); loopAppendable.openPseudoScope(); loopAppendable.newLine().append("for ("); EList<XExpression> initExpressions = expr.getInitExpressions(); XExpression firstInitExpression = IterableExtensions.head(initExpressions); if (firstInitExpression instanceof XJVariableDeclaration) { XJVariableDeclaration variableDeclaration = (XJVariableDeclaration) firstInitExpression; LightweightTypeReference type = appendVariableTypeAndName(variableDeclaration, loopAppendable); loopAppendable.append(" = "); if (variableDeclaration.getRight() != null) { compileAsJavaExpression(variableDeclaration.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } // custom implementation since possible additional declarations are contained (i.e., parsed) // in JavamXVariableDeclaration EList<XVariableDeclaration> additionalVariables = variableDeclaration.getAdditionalVariables(); for (int i = 0; i < additionalVariables.size(); i++) { loopAppendable.append(", "); XVariableDeclaration initExpression = additionalVariables.get(i); loopAppendable.append(loopAppendable.declareVariable(initExpression, makeJavaIdentifier(initExpression.getName()))); loopAppendable.append(" = "); if (initExpression.getRight() != null) { compileAsJavaExpression(initExpression.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } } } else { for (int i = 0; i < initExpressions.size(); i++) { if (i != 0) { loopAppendable.append(", "); } XExpression initExpression = initExpressions.get(i); compileAsJavaExpression(initExpression, loopAppendable, getLightweightType(initExpression)); } } loopAppendable.append(";"); XExpression expression = expr.getExpression(); if (expression != null) { loopAppendable.append(" "); internalToJavaExpression(expression, loopAppendable); } loopAppendable.append(";"); EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (int i = 0; i < updateExpressions.size(); i++) { if (i != 0) { loopAppendable.append(","); } loopAppendable.append(" "); XExpression updateExpression = updateExpressions.get(i); internalToJavaExpression(updateExpression, loopAppendable); } loopAppendable.append(") {").increaseIndentation(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); loopAppendable.decreaseIndentation().newLine().append("}"); loopAppendable.closeScope(); } /** * Overridden to deal with branching instructions. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaWhileStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaWhileStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); boolean needBraces = !bracesAreAddedByOuterStructure(expr); if (needBraces) { loopAppendable.newLine().increaseIndentation().append("{"); loopAppendable.openPseudoScope(); } EList<XExpression> initExpressions = expr.getInitExpressions(); for (int i = 0; i < initExpressions.size(); i++) { XExpression initExpression = initExpressions.get(i); // custom implementation // since a for statement cannot be used as expression we don't need // any special treatment for the last expression internalToJavaStatement(initExpression, loopAppendable, false); } final String varName = loopAppendable.declareSyntheticVariable(expr, "_while"); XExpression expression = expr.getExpression(); if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append("boolean ").append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append("boolean ").append(varName).append(ASSIGNED_TRUE); } loopAppendable.newLine(); loopAppendable.append("while ("); loopAppendable.append(varName); loopAppendable.append(") {").increaseIndentation(); loopAppendable.openPseudoScope(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); // custom implementation: // if the each expression contains sure branching statements then // we must not generate the update expression and the check expression // not that we don't check if eachExpression is early exit: if it was, // then we'd get a validation error for unreachable statement, // see jbase.tests.JbaseValidatorTest.testDeadCodeInForLoopTranslatedToJavaWhileEarlyExit if (!branchingStatementDetector.isSureBranchStatement(eachExpression)) { EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, loopAppendable, false); } if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append(varName).append(ASSIGNED_TRUE); } } loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); if (needBraces) { loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); } } /** * In our Java-like switch statement we can always compile into Java switch. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { _toJavaSwitchStatement(expr, b, isReferenced); } /** * Since we want Java switch statement, the compilation is simpler and does * not append break automatically. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaSwitchStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaSwitchStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { final String switchResultName = declareSwitchResultVariable(expr, b, isReferenced); internalToJavaStatement(expr.getSwitch(), b, true); final String variableName = declareLocalVariable(expr, b); b.newLine().append("switch (").append(variableName).append(") {").increaseIndentation(); for (XCasePart casePart : expr.getCases()) { ITreeAppendable caseAppendable = b.trace(casePart, true); caseAppendable.newLine().increaseIndentation().append("case "); ITreeAppendable conditionAppendable = caseAppendable.trace(casePart.getCase(), true); internalToJavaExpression(casePart.getCase(), conditionAppendable); caseAppendable.append(":"); XExpression then = casePart.getThen(); executeThenPart(expr, switchResultName, then, caseAppendable, isReferenced); caseAppendable.decreaseIndentation(); } if (expr.getDefault() != null) { ILocationData location = getLocationOfDefault(expr); ITreeAppendable defaultAppendable = b.trace(location); defaultAppendable.newLine().increaseIndentation().append("default:"); defaultAppendable.openPseudoScope(); executeThenPart(expr, switchResultName, expr.getDefault(), defaultAppendable, isReferenced); defaultAppendable.closeScope(); defaultAppendable.decreaseIndentation(); } b.decreaseIndentation().newLine().append("}"); } @Override protected void _toJavaStatement(XVariableDeclaration varDeclaration, ITreeAppendable b, boolean isReferenced) { super._toJavaStatement(varDeclaration, b, isReferenced); if (varDeclaration instanceof XJVariableDeclaration) { XJVariableDeclaration customVar = (XJVariableDeclaration) varDeclaration; for (XVariableDeclaration additional : customVar.getAdditionalVariables()) { _toJavaStatement(additional, b, isReferenced); } } } /** * Specialized for prefix operator and unary expression * * @see org.eclipse.xtext.xbase.compiler.FeatureCallCompiler#featureCalltoJavaExpression(org.eclipse.xtext.xbase.XAbstractFeatureCall, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void featureCalltoJavaExpression(XAbstractFeatureCall call, ITreeAppendable b, boolean isExpressionContext) { if (call instanceof XJPrefixOperation) { // we can't simply retrieve the inline annotations as it is done // for postfix operations, since postfix operations are already mapped to // postfix methods operator_plusPlus and operator_minusMinus JvmIdentifiableElement feature = call.getFeature(); if (feature.getSimpleName().endsWith("plusPlus")) { b.append("++"); } else { // the only other possibility is minus minus b.append("--"); } appendArgument(((XJPrefixOperation) call).getOperand(), b); return; } else if (call instanceof XUnaryOperation) { XUnaryOperation unaryOperation = (XUnaryOperation) call; final StringBuilder builder = new StringBuilder(); boolean specialHandling = expressionHelper.specialHandling(unaryOperation, new BaseCase() { @Override public Boolean apply(XUnaryOperation op, XNumberLiteral lit) { builder.append(op.getConcreteSyntaxFeatureName() + lit.getValue()); return true; } }, new StepCase() { @Override public void accept(XUnaryOperation op) { builder.insert(0, op.getConcreteSyntaxFeatureName() + "(").append(')'); } } ); if (specialHandling) { b.append(builder); return; } } super.featureCalltoJavaExpression(call, b, isExpressionContext); } /** * Customized for our special treatment of some unary operations * * @param expr * @param b * @return */ @Override protected boolean isVariableDeclarationRequired(XExpression expr, ITreeAppendable b) { if (expr instanceof XUnaryOperation) { return !expressionHelper.specialHandling((XUnaryOperation) expr); } return super.isVariableDeclarationRequired(expr, b); } private void compileArrayAccess(XExpression expr, ITreeAppendable b) { if (expr instanceof XJArrayAccess) { XJArrayAccess access = (XJArrayAccess) expr; for (XExpression index : access.getIndexes()) { b.append("["); internalToJavaExpression(index, b); b.append("]"); } } } /** * Specialization for {@link XJArrayConstructorCall} since it can * have dimensions without dimension expression (index). * * @param cons * @param b */ private void compileArrayAccess(XJArrayConstructorCall cons, ITreeAppendable b) { XJArrayLiteral arrayLiteral = cons.getArrayLiteral(); if (arrayLiteral != null) { internalToJavaExpression(arrayLiteral, b); } else { Iterable<XExpression> dimensionsAndIndexes = modelUtil.arrayDimensionIndexAssociations(cons); for (XExpression e : dimensionsAndIndexes) { b.append("["); if (e != null) { internalToJavaExpression(e, b); } b.append("]"); } } } /** * Overridden because our parameters, like in Java, can be final or non final by default */ @Override protected void appendForLoopParameter(XForLoopExpression expr, ITreeAppendable appendable) { JvmFormalParameter declaredParam = expr.getDeclaredParam(); if (((XJJvmFormalParameter) declaredParam).isFinal()) { appendable.append("final "); } // this is the original code JvmTypeReference paramType = getForLoopParameterType(expr); serialize(paramType, expr, appendable); appendable.append(" "); final String name = makeJavaIdentifier(declaredParam.getName()); String varName = appendable.declareVariable(declaredParam, name); appendable.trace(declaredParam, TypesPackage.Literals.JVM_FORMAL_PARAMETER__NAME, 0).append(varName); } }
jbase/src/jbase/compiler/JbaseXbaseCompiler.java
/** * */ package jbase.compiler; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.xtext.EcoreUtil2; import org.eclipse.xtext.common.types.JvmField; import org.eclipse.xtext.common.types.JvmFormalParameter; import org.eclipse.xtext.common.types.JvmIdentifiableElement; import org.eclipse.xtext.common.types.JvmOperation; import org.eclipse.xtext.common.types.JvmTypeReference; import org.eclipse.xtext.common.types.TypesPackage; import org.eclipse.xtext.generator.trace.ILocationData; import org.eclipse.xtext.util.Strings; import org.eclipse.xtext.xbase.XAbstractFeatureCall; import org.eclipse.xtext.xbase.XAssignment; import org.eclipse.xtext.xbase.XBasicForLoopExpression; import org.eclipse.xtext.xbase.XCasePart; import org.eclipse.xtext.xbase.XExpression; import org.eclipse.xtext.xbase.XForLoopExpression; import org.eclipse.xtext.xbase.XNumberLiteral; import org.eclipse.xtext.xbase.XSwitchExpression; import org.eclipse.xtext.xbase.XUnaryOperation; import org.eclipse.xtext.xbase.XVariableDeclaration; import org.eclipse.xtext.xbase.XbasePackage; import org.eclipse.xtext.xbase.compiler.output.ITreeAppendable; import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; import com.google.common.base.Joiner; import com.google.inject.Inject; import jbase.controlflow.JbaseBranchingStatementDetector; import jbase.jbase.XJArrayAccess; import jbase.jbase.XJArrayAccessExpression; import jbase.jbase.XJArrayConstructorCall; import jbase.jbase.XJArrayLiteral; import jbase.jbase.XJBranchingStatement; import jbase.jbase.XJBreakStatement; import jbase.jbase.XJCharLiteral; import jbase.jbase.XJClassObject; import jbase.jbase.XJContinueStatement; import jbase.jbase.XJJvmFormalParameter; import jbase.jbase.XJPrefixOperation; import jbase.jbase.XJSemicolonStatement; import jbase.jbase.XJVariableDeclaration; import jbase.util.JbaseExpressionHelper; import jbase.util.JbaseExpressionHelper.BaseCase; import jbase.util.JbaseExpressionHelper.StepCase; import jbase.util.JbaseModelUtil; /** * @author Lorenzo Bettini * */ public class JbaseXbaseCompiler extends PatchedXbaseCompiler { private static final String ASSIGNED_TRUE = " = true;"; @Inject private JbaseModelUtil modelUtil; @Inject private JbaseBranchingStatementDetector branchingStatementDetector; @Inject private JbaseExpressionHelper expressionHelper; @Override protected void doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) { if (obj instanceof XJArrayConstructorCall) { _toJavaStatement((XJArrayConstructorCall) obj, appendable, isReferenced); } else if (obj instanceof XJArrayAccessExpression) { _toJavaStatement((XJArrayAccessExpression) obj, appendable, isReferenced); } else if (obj instanceof XJContinueStatement) { _toJavaStatement((XJContinueStatement) obj, appendable, isReferenced); } else if (obj instanceof XJBreakStatement) { _toJavaStatement((XJBreakStatement) obj, appendable, isReferenced); } else if (obj instanceof XJClassObject) { _toJavaStatement((XJClassObject) obj, appendable, isReferenced); } else if (obj instanceof XJSemicolonStatement) { _toJavaStatement((XJSemicolonStatement) obj, appendable, isReferenced); } else { super.doInternalToJavaStatement(obj, appendable, isReferenced); } } public void _toJavaStatement(XJArrayConstructorCall call, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(XJArrayAccessExpression access, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(XJContinueStatement st, ITreeAppendable b, boolean isReferenced) { XBasicForLoopExpression basicForLoop = EcoreUtil2.getContainerOfType(st, XBasicForLoopExpression.class); if (basicForLoop != null && !canCompileToJavaBasicForStatement(basicForLoop, b)) { // the for loop is translated into a while statement, so, before // the continue; we must perform the update expressions and then // check the while condition. EList<XExpression> updateExpressions = basicForLoop.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, b, false); } final String varName = b.getName(basicForLoop); XExpression expression = basicForLoop.getExpression(); if (expression != null) { internalToJavaStatement(expression, b, true); b.newLine().append(varName).append(" = "); internalToJavaExpression(expression, b); b.append(";"); } else { b.newLine().append(varName).append(ASSIGNED_TRUE); } } compileBranchingStatement(st, b, "continue"); } public void _toJavaStatement(XJBreakStatement st, ITreeAppendable b, boolean isReferenced) { compileBranchingStatement(st, b, "break"); } public void _toJavaStatement(XJClassObject e, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } private void compileClassObject(XJClassObject e, ITreeAppendable b) { b.append(e.getTypeExpression().toString()). append(Joiner.on("").join(e.getArrayDimensions())).append(".class"); } private void compileBranchingStatement(XJBranchingStatement st, ITreeAppendable b, String instruction) { b.newLine().append(instruction).append(";"); } public void _toJavaStatement(XJSemicolonStatement st, ITreeAppendable b, boolean isReferenced) { XExpression expression = st.getExpression(); if (expression != null) { doInternalToJavaStatement(expression, b, isReferenced); } else { b.append(";"); } } @Override protected void internalToConvertedExpression(XExpression obj, ITreeAppendable appendable) { if (obj instanceof XJArrayConstructorCall) { _toJavaExpression((XJArrayConstructorCall) obj, appendable); } else if (obj instanceof XJArrayAccessExpression) { _toJavaExpression((XJArrayAccessExpression) obj, appendable); } else if (obj instanceof XJCharLiteral) { _toJavaExpression((XJCharLiteral) obj, appendable); } else if (obj instanceof XJClassObject) { _toJavaExpression((XJClassObject) obj, appendable); } else { super.internalToConvertedExpression(obj, appendable); } } public void _toJavaExpression(XJArrayConstructorCall call, ITreeAppendable b) { if (call.getArrayLiteral() == null) { // otherwise we simply compile the array literal // assuming that no dimension expression has been specified // (checked by the validator) b.append("new "); b.append(call.getType()); } compileArrayAccess(call, b); } public void _toJavaExpression(XJArrayAccessExpression arrayAccess, ITreeAppendable b) { internalToConvertedExpression(arrayAccess.getArray(), b); compileArrayAccess(arrayAccess, b); } public void _toJavaExpression(XJClassObject e, ITreeAppendable b) { compileClassObject(e, b); } /** * Always compile into a char literal (we've already type checked that, and we * can assign it also to numeric variables as in Java). * * @param literal * @param appendable */ public void _toJavaExpression(XJCharLiteral literal, ITreeAppendable appendable) { String javaString = Strings.convertToJavaString(literal.getValue(), true); appendable.append("'").append(javaString).append("'"); } @Override protected void assignmentToJavaExpression(XAssignment expr, ITreeAppendable b, boolean isExpressionContext) { final JvmIdentifiableElement feature = expr.getFeature(); if (!(feature instanceof JvmOperation)) { boolean isArgument = expr.eContainer() instanceof XAbstractFeatureCall; if (isArgument) { EStructuralFeature containingFeature = expr.eContainingFeature(); if (containingFeature == XbasePackage.Literals.XFEATURE_CALL__FEATURE_CALL_ARGUMENTS || containingFeature == XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_ARGUMENTS) { isArgument = false; } else { b.append("("); } } if (feature instanceof JvmField) { appendReceiver(expr, b, isExpressionContext); b.append("."); appendFeatureCall(expr, b); } else { String name = b.getName(expr.getFeature()); b.append(name); } // custom implementation starts here compileArrayAccess(expr, b); // custom implementation ends here b.append(" = "); internalToJavaExpression(expr.getValue(), b); if (isArgument) { b.append(")"); } return; } super.assignmentToJavaExpression(expr, b, isExpressionContext); } /** * Overridden to deal with several variable declarations. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaBasicForStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaBasicForStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); loopAppendable.openPseudoScope(); loopAppendable.newLine().append("for ("); EList<XExpression> initExpressions = expr.getInitExpressions(); XExpression firstInitExpression = IterableExtensions.head(initExpressions); if (firstInitExpression instanceof XJVariableDeclaration) { XJVariableDeclaration variableDeclaration = (XJVariableDeclaration) firstInitExpression; LightweightTypeReference type = appendVariableTypeAndName(variableDeclaration, loopAppendable); loopAppendable.append(" = "); if (variableDeclaration.getRight() != null) { compileAsJavaExpression(variableDeclaration.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } // custom implementation since possible additional declarations are contained (i.e., parsed) // in JavamXVariableDeclaration EList<XVariableDeclaration> additionalVariables = variableDeclaration.getAdditionalVariables(); for (int i = 0; i < additionalVariables.size(); i++) { loopAppendable.append(", "); XVariableDeclaration initExpression = additionalVariables.get(i); loopAppendable.append(loopAppendable.declareVariable(initExpression, makeJavaIdentifier(initExpression.getName()))); loopAppendable.append(" = "); if (initExpression.getRight() != null) { compileAsJavaExpression(initExpression.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } } } else { for (int i = 0; i < initExpressions.size(); i++) { if (i != 0) { loopAppendable.append(", "); } XExpression initExpression = initExpressions.get(i); compileAsJavaExpression(initExpression, loopAppendable, getLightweightType(initExpression)); } } loopAppendable.append(";"); XExpression expression = expr.getExpression(); if (expression != null) { loopAppendable.append(" "); internalToJavaExpression(expression, loopAppendable); } loopAppendable.append(";"); EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (int i = 0; i < updateExpressions.size(); i++) { if (i != 0) { loopAppendable.append(","); } loopAppendable.append(" "); XExpression updateExpression = updateExpressions.get(i); internalToJavaExpression(updateExpression, loopAppendable); } loopAppendable.append(") {").increaseIndentation(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); loopAppendable.decreaseIndentation().newLine().append("}"); loopAppendable.closeScope(); } /** * Overridden to deal with branching instructions. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaWhileStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaWhileStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); boolean needBraces = !bracesAreAddedByOuterStructure(expr); if (needBraces) { loopAppendable.newLine().increaseIndentation().append("{"); loopAppendable.openPseudoScope(); } EList<XExpression> initExpressions = expr.getInitExpressions(); for (int i = 0; i < initExpressions.size(); i++) { XExpression initExpression = initExpressions.get(i); // custom implementation // since a for statement cannot be used as expression we don't need // any special treatment for the last expression internalToJavaStatement(initExpression, loopAppendable, false); } final String varName = loopAppendable.declareSyntheticVariable(expr, "_while"); XExpression expression = expr.getExpression(); if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append("boolean ").append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append("boolean ").append(varName).append(ASSIGNED_TRUE); } loopAppendable.newLine(); loopAppendable.append("while ("); loopAppendable.append(varName); loopAppendable.append(") {").increaseIndentation(); loopAppendable.openPseudoScope(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); // custom implementation: // if the each expression contains sure branching statements then // we must not generate the update expression and the check expression // not that we don't check if eachExpression is early exit: if it was, // then we'd get a validation error for unreachable statement, // see jbase.tests.JbaseValidatorTest.testDeadCodeInForLoopTranslatedToJavaWhileEarlyExit if (!branchingStatementDetector.isSureBranchStatement(eachExpression)) { EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, loopAppendable, false); } if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append(varName).append(ASSIGNED_TRUE); } } loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); if (needBraces) { loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); } } /** * In our Java-like switch statement we can always compile into Java switch. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { _toJavaSwitchStatement(expr, b, isReferenced); } /** * Since we want Java switch statement, the compilation is simpler and does * not append break automatically. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaSwitchStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaSwitchStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { final String switchResultName = declareSwitchResultVariable(expr, b, isReferenced); internalToJavaStatement(expr.getSwitch(), b, true); final String variableName = declareLocalVariable(expr, b); b.newLine().append("switch (").append(variableName).append(") {").increaseIndentation(); for (XCasePart casePart : expr.getCases()) { ITreeAppendable caseAppendable = b.trace(casePart, true); caseAppendable.newLine().increaseIndentation().append("case "); ITreeAppendable conditionAppendable = caseAppendable.trace(casePart.getCase(), true); internalToJavaExpression(casePart.getCase(), conditionAppendable); caseAppendable.append(":"); XExpression then = casePart.getThen(); executeThenPart(expr, switchResultName, then, caseAppendable, isReferenced); caseAppendable.decreaseIndentation(); } if (expr.getDefault() != null) { ILocationData location = getLocationOfDefault(expr); ITreeAppendable defaultAppendable = b.trace(location); defaultAppendable.newLine().increaseIndentation().append("default:"); defaultAppendable.openPseudoScope(); executeThenPart(expr, switchResultName, expr.getDefault(), defaultAppendable, isReferenced); defaultAppendable.closeScope(); defaultAppendable.decreaseIndentation(); } b.decreaseIndentation().newLine().append("}"); } @Override protected void _toJavaStatement(XVariableDeclaration varDeclaration, ITreeAppendable b, boolean isReferenced) { super._toJavaStatement(varDeclaration, b, isReferenced); if (varDeclaration instanceof XJVariableDeclaration) { XJVariableDeclaration customVar = (XJVariableDeclaration) varDeclaration; for (XVariableDeclaration additional : customVar.getAdditionalVariables()) { _toJavaStatement(additional, b, isReferenced); } } } /** * Specialized for prefix operator and unary expression * * @see org.eclipse.xtext.xbase.compiler.FeatureCallCompiler#featureCalltoJavaExpression(org.eclipse.xtext.xbase.XAbstractFeatureCall, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void featureCalltoJavaExpression(XAbstractFeatureCall call, ITreeAppendable b, boolean isExpressionContext) { if (call instanceof XJPrefixOperation) { // we can't simply retrieve the inline annotations as it is done // for postfix operations, since postfix operations are already mapped to // postfix methods operator_plusPlus and operator_minusMinus JvmIdentifiableElement feature = call.getFeature(); if (feature.getSimpleName().endsWith("plusPlus")) { b.append("++"); } else { // the only other possibility is minus minus b.append("--"); } appendArgument(((XJPrefixOperation) call).getOperand(), b); return; } else if (call instanceof XUnaryOperation) { XUnaryOperation unaryOperation = (XUnaryOperation) call; final StringBuilder builder = new StringBuilder(); boolean specialHandling = expressionHelper.specialHandling(unaryOperation, new BaseCase() { @Override public Boolean apply(XUnaryOperation op, XNumberLiteral lit) { builder.append(op.getConcreteSyntaxFeatureName() + lit.getValue()); return true; } }, new StepCase() { @Override public void accept(XUnaryOperation op) { builder.insert(0, op.getConcreteSyntaxFeatureName() + "(").append(')'); } } ); if (specialHandling) { b.append(builder); return; } } super.featureCalltoJavaExpression(call, b, isExpressionContext); } /** * Customized for our special treatment of some unary operations * * @param expr * @param b * @return */ @Override protected boolean isVariableDeclarationRequired(XExpression expr, ITreeAppendable b) { if (expr instanceof XUnaryOperation) { return !expressionHelper.specialHandling((XUnaryOperation) expr); } return super.isVariableDeclarationRequired(expr, b); } private void compileArrayAccess(XExpression expr, ITreeAppendable b) { if (expr instanceof XJArrayAccess) { XJArrayAccess access = (XJArrayAccess) expr; for (XExpression index : access.getIndexes()) { b.append("["); internalToJavaExpression(index, b); b.append("]"); } } } /** * Specialization for {@link XJArrayConstructorCall} since it can * have dimensions without dimension expression (index). * * @param cons * @param b */ private void compileArrayAccess(XJArrayConstructorCall cons, ITreeAppendable b) { XJArrayLiteral arrayLiteral = cons.getArrayLiteral(); if (arrayLiteral != null) { internalToJavaExpression(arrayLiteral, b); } else { Iterable<XExpression> dimensionsAndIndexes = modelUtil.arrayDimensionIndexAssociations(cons); for (XExpression e : dimensionsAndIndexes) { b.append("["); if (e != null) { internalToJavaExpression(e, b); } b.append("]"); } } } /** * Overridden because our parameters, like in Java, can be final or non final by default */ @Override protected void appendForLoopParameter(XForLoopExpression expr, ITreeAppendable appendable) { JvmFormalParameter declaredParam = expr.getDeclaredParam(); if (((XJJvmFormalParameter) declaredParam).isFinal()) { appendable.append("final "); } // this is the original code JvmTypeReference paramType = getForLoopParameterType(expr); serialize(paramType, expr, appendable); appendable.append(" "); final String name = makeJavaIdentifier(declaredParam.getName()); String varName = appendable.declareVariable(declaredParam, name); appendable.trace(declaredParam, TypesPackage.Literals.JVM_FORMAL_PARAMETER__NAME, 0).append(varName); } }
40: Compilation of .class expressions Task-Url: https://github.com/LorenzoBettini/jbase/issues/40
jbase/src/jbase/compiler/JbaseXbaseCompiler.java
40: Compilation of .class expressions
<ide><path>base/src/jbase/compiler/JbaseXbaseCompiler.java <ide> import org.eclipse.xtext.common.types.JvmFormalParameter; <ide> import org.eclipse.xtext.common.types.JvmIdentifiableElement; <ide> import org.eclipse.xtext.common.types.JvmOperation; <add>import org.eclipse.xtext.common.types.JvmType; <ide> import org.eclipse.xtext.common.types.JvmTypeReference; <ide> import org.eclipse.xtext.common.types.TypesPackage; <ide> import org.eclipse.xtext.generator.trace.ILocationData; <ide> } <ide> <ide> private void compileClassObject(XJClassObject e, ITreeAppendable b) { <del> b.append(e.getTypeExpression().toString()). <add> XAbstractFeatureCall featureCall = (XAbstractFeatureCall) e.getTypeExpression(); <add> // we must append it as a JvmType so that the corresponding import statement <add> // is generated in the Java code <add> b.append((JvmType) featureCall.getFeature()). <ide> append(Joiner.on("").join(e.getArrayDimensions())).append(".class"); <ide> } <ide>
Java
apache-2.0
6e13494b887f971cb86942d8248d5c6563ffaa97
0
j-coll/datastore,opencb/datastore
package org.opencb.datastore.mongodb; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import com.mongodb.*; import org.junit.*; import org.junit.rules.ExpectedException; import org.opencb.datastore.core.ComplexTypeConverter; import org.opencb.datastore.core.QueryOptions; import org.opencb.datastore.core.QueryResult; import org.opencb.datastore.core.QueryResultWriter; import static org.junit.Assert.*; /** * Created by imedina on 29/03/14. */ public class MongoDBCollectionTest { private static MongoDataStoreManager mongoDataStoreManager; private static MongoDataStore mongoDataStore; private static MongoDBCollection mongoDBCollection; private static MongoDBCollection mongoDBCollectionInsertTest; private static MongoDBCollection mongoDBCollectionUpdateTest; private static MongoDBCollection mongoDBCollectionRemoveTest; private static int N = 1000; @Rule public ExpectedException thrown = ExpectedException.none(); @BeforeClass public static void beforeClass() throws Exception { mongoDataStoreManager = new MongoDataStoreManager("localhost", 27017); mongoDataStore = mongoDataStoreManager.get("datastore_test"); mongoDBCollection = createTestCollection("test", N); mongoDBCollectionInsertTest = createTestCollection("insert_test", 50); mongoDBCollectionUpdateTest = createTestCollection("update_test", 50); mongoDBCollectionRemoveTest = createTestCollection("remove_test", 50); } @AfterClass public static void afterClass() throws Exception { mongoDataStoreManager.drop("datastore_test"); mongoDataStore.close(); } private static MongoDBCollection createTestCollection(String test, int size) { MongoDBCollection mongoDBCollection = mongoDataStore.getCollection(test); DBObject dbObject; for(int i = 0; i < size; i++) { dbObject = new BasicDBObject("id", i); dbObject.put("name", "John"); dbObject.put("surname", "Doe"); dbObject.put("age", i % 5); mongoDBCollection.nativeQuery().insert(dbObject, null); } return mongoDBCollection; } @Ignore @Test public void testQueryResultWriter() throws Exception { for (int i = 0; i < 100; i++) { mongoDBCollection.insert(new BasicDBObject("id", i), null); } BasicQueryResultWriter queryResultWriter = new BasicQueryResultWriter(); mongoDBCollection.setQueryResultWriter(queryResultWriter); QueryResult<DBObject> dbObjectQueryResult = mongoDBCollection.find(new BasicDBObject("id", new BasicDBObject("$gt", 50)), null); System.out.println(dbObjectQueryResult); assert (dbObjectQueryResult.getResult().isEmpty()); mongoDBCollection.setQueryResultWriter(null); dbObjectQueryResult = mongoDBCollection.find(new BasicDBObject("id", new BasicDBObject("$gt", 50)), null); System.out.println(dbObjectQueryResult); assert (!dbObjectQueryResult.getResult().isEmpty()); } @Test public void testDistinct() throws Exception { QueryResult<Object> id1 = mongoDBCollection.distinct("id", null); QueryResult<Integer> id2 = mongoDBCollection.distinct("id", null, new ComplexTypeConverter<Integer, Object>() { @Override public Integer convertToDataModelType(Object object) { if(object instanceof Integer) { return (Integer) object; } else { System.out.println("Non integer result : " + object); return 0; } } @Override public Object convertToStorageType(Integer object) { return null; } }); // System.out.println(mongoDBCollection.distinct("name", null).getNumResults()); // System.out.println(mongoDBCollection.nativeQuery().distinct("name")); } @Test public void testCount() throws Exception { QueryResult<Long> queryResult = mongoDBCollection.count(); assertEquals("The number of documents must be equals", new Long(N), queryResult.getResult().get(0)); } @Test public void testCount1() throws Exception { QueryResult<Long> queryResult = mongoDBCollection.count(); assertEquals("The number must be equals", new Long(N), queryResult.first()); } @Test public void testDistinct1() throws Exception { QueryResult<Object> queryResult = mongoDBCollection.distinct("age", null); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.Integer'", "java.lang.Integer", queryResult.getResultType()); } @Test public void testDistinct2() throws Exception { QueryResult<String> queryResult = mongoDBCollection.distinct("name", null, String.class); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.String'", "java.lang.String", queryResult.getResultType()); } @Test public void testDistinct3() throws Exception { QueryResult<Integer> queryResult = mongoDBCollection.distinct("age", null, new ComplexTypeConverter<Integer, Object>() { @Override public Integer convertToDataModelType(Object object) { return Integer.parseInt(object.toString()); } @Override public Object convertToStorageType(Integer object) { return null; } }); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.Integer'", "java.lang.Integer", queryResult.getResultType()); } @Test public void testFind() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); QueryOptions queryOptions = new QueryOptions("include", Arrays.asList("id")); QueryResult<DBObject> queryResult = mongoDBCollection.find(dbObject, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertEquals("Returned Id does not match", 4, queryResult.first().get("id")); // System.out.println("queryResult 'include' = " + queryResult); } @Test public void testFind1() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<DBObject> queryResult = mongoDBCollection.find(dbObject, returnFields, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertNull("Field 'name' must not exist", queryResult.first().get("name")); // System.out.println("queryResult 'projection' = " + queryResult); } @Test public void testFind2() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<HashMap> queryResult = mongoDBCollection.find(dbObject, returnFields, HashMap.class, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertTrue("Returned field must instance of Hashmap", queryResult.first() instanceof HashMap); } @Test public void testFind3() throws Exception { final DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<HashMap> queryResult = mongoDBCollection.find(dbObject, returnFields, new ComplexTypeConverter<HashMap, DBObject>() { @Override public HashMap convertToDataModelType(DBObject object) { return new HashMap(dbObject.toMap()); } @Override public DBObject convertToStorageType(HashMap object) { return null; } }, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertTrue("Returned field must instance of Hashmap", queryResult.first() instanceof HashMap); } @Test public void testFind4() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } QueryOptions queryOptions = new QueryOptions("include", Arrays.asList("id")); List<QueryResult<DBObject>> queryResultList = mongoDBCollection.find(dbObjectList, queryOptions); assertEquals("List must contain 10 results", 10, queryResultList.size()); assertNotNull("Object cannot be null", queryResultList.get(0).getResult()); assertEquals("Returned Id does not match", 9, queryResultList.get(9).first().get("id")); } @Test public void testFind5() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<DBObject>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, queryOptions); assertEquals("List must contain 10 results", 10, queryResultList.size()); assertNotNull("Object cannot be null", queryResultList.get(0).getResult()); assertNull("Field 'name' must not exist", queryResultList.get(0).first().get("name")); assertEquals("resultType must be 'com.mongodb.BasicDBObject'", "com.mongodb.BasicDBObject", queryResultList.get(0).getResultType()); } @Test public void testFind6() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<HashMap>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, HashMap.class, queryOptions); assertNotNull("Object queryResultList cannot be null", queryResultList); assertNotNull("Object queryResultList.get(0) cannot be null", queryResultList.get(0).getResult()); assertTrue("Returned field must instance of HashMap", queryResultList.get(0).first() instanceof HashMap); assertEquals("resultType must 'java.util.HashMap'", "java.util.HashMap", queryResultList.get(0).getResultType()); } @Test public void testFind7() throws Exception { final List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<HashMap>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, new ComplexTypeConverter<HashMap, DBObject>() { @Override public HashMap convertToDataModelType(DBObject object) { return new HashMap(object.toMap()); } @Override public DBObject convertToStorageType(HashMap object) { return null; } }, queryOptions); assertNotNull("Object queryResultList cannot be null", queryResultList); assertNotNull("Object queryResultList.get(0) cannot be null", queryResultList.get(0).getResult()); assertTrue("Returned field must instance of Hashmap", queryResultList.get(0).first() instanceof HashMap); assertEquals("resultType must 'java.util.HashMap'", "java.util.HashMap", queryResultList.get(0).getResultType()); } @Test public void testAggregate() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(); DBObject match = new BasicDBObject("$match", new BasicDBObject("age", new BasicDBObject("$gt", 2))); DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$age")); dbObjectList.add(match); dbObjectList.add(group); QueryResult queryResult = mongoDBCollection.aggregate(dbObjectList, null); assertNotNull("Object queryResult cannot be null", queryResult); assertNotNull("Object queryResult.getResult() cannot be null", queryResult.getResult()); assertEquals("There must be 2 results", 2, queryResult.getResult().size()); } @Test public void testInsert() throws Exception { Long countBefore = mongoDBCollectionInsertTest.count().first(); for (int i = 1; i < 50; i++) { mongoDBCollectionInsertTest.insert(new BasicDBObject("insertedObject", i), null); assertEquals("Insert operation must insert 1 element each time.", countBefore + i, mongoDBCollectionInsertTest.count().first().longValue() ); } } @Test public void testInsert1() throws Exception { BasicDBObject uniqueObject = new BasicDBObject("_id", "myUniqueId"); mongoDBCollectionInsertTest.insert(uniqueObject, null); thrown.expect(DuplicateKeyException.class); mongoDBCollectionInsertTest.insert(uniqueObject, null); } @Test public void testInsert2() throws Exception { Long countBefore = mongoDBCollectionInsertTest.count().first(); int numBulkInsertions = 50; int bulkInsertSize = 100; for (int b = 1; b < numBulkInsertions; b++) { ArrayList<DBObject> list = new ArrayList<>(bulkInsertSize); for (int i = 0; i < bulkInsertSize; i++) { list.add(new BasicDBObject("bulkInsertedObject", i)); } mongoDBCollectionInsertTest.insert(list, null); assertEquals("Bulk insert operation must insert " + bulkInsertSize + " elements each time.", countBefore + bulkInsertSize * b, mongoDBCollectionInsertTest.count().first().longValue()); } } @Test public void testInsert3() throws Exception { BasicDBObject uniqueObject = new BasicDBObject("_id", "myUniqueId"); ArrayList<DBObject> list = new ArrayList<>(10); for (int i = 0; i < 10; i++) { list.add(uniqueObject); } thrown.expect(BulkWriteException.class); mongoDBCollectionInsertTest.insert(list, null); } @Test public void testUpdate() throws Exception { BasicDBObject query = new BasicDBObject("name", "John"); long count = mongoDBCollectionUpdateTest.count(query).first(); WriteResult writeResult = mongoDBCollectionUpdateTest.update(query, new BasicDBObject("$set", new BasicDBObject("modified", true)), new QueryOptions("multi", true) ).first(); assertEquals("All the objects are named \"John\", so all objects should be modified", count, writeResult.getN()); } @Test public void testUpdate1() throws Exception { WriteResult writeResult = mongoDBCollectionUpdateTest.update(new BasicDBObject("surname", "Johnson"), new BasicDBObject("$set", new BasicDBObject("modifiedAgain", true)), new QueryOptions("multi", true) ).first(); assertEquals("Any objects have the surname \"Johnson\", so any objects should be modified", 0, writeResult.getN()); } @Test public void testUpdate2() throws Exception { WriteResult writeResult = mongoDBCollectionUpdateTest.update(new BasicDBObject("surname", "Johnson"), new BasicDBObject("$set", new BasicDBObject("modifiedAgain", true)), new QueryOptions("upsert", true) ).first(); assertEquals("Any objects have the surname \"Johnson\", so one object should be inserted", 1, writeResult.getN()); } @Test public void testUpdate3() throws Exception { int count = mongoDBCollectionUpdateTest.count().first().intValue(); int modifiedDocuments = count / 2; ArrayList<DBObject> queries = new ArrayList<>(modifiedDocuments); ArrayList<DBObject> updates = new ArrayList<>(modifiedDocuments); for (int i = 0; i < modifiedDocuments; i++) { queries.add(new BasicDBObject("id", i)); updates.add(new BasicDBObject("$set", new BasicDBObject("bulkUpdated", i))); } BulkWriteResult bulkWriteResult = mongoDBCollectionUpdateTest.update(queries, updates, new QueryOptions("multi", false)).first(); assertEquals("", modifiedDocuments, bulkWriteResult.getModifiedCount()); } @Test public void testUpdate4() throws Exception { int count = mongoDBCollectionUpdateTest.count().first().intValue(); int modifiedDocuments = count / 2; ArrayList<DBObject> queries = new ArrayList<>(modifiedDocuments); ArrayList<DBObject> updates = new ArrayList<>(modifiedDocuments); for (int i = 0; i < modifiedDocuments; i++) { queries.add(new BasicDBObject("id", i)); updates.add(new BasicDBObject("$set", new BasicDBObject("bulkUpdated", i))); } updates.remove(updates.size()-1); thrown.expect(IndexOutOfBoundsException.class); mongoDBCollectionUpdateTest.update(queries, updates, new QueryOptions("multi", false)); } @Test public void testRemove() throws Exception { int count = mongoDBCollectionRemoveTest.count().first().intValue(); BasicDBObject query = new BasicDBObject("age", 1); int numDeletions = mongoDBCollectionRemoveTest.count(query).first().intValue(); WriteResult writeResult = mongoDBCollectionRemoveTest.remove(query, null).first(); assertEquals(numDeletions, writeResult.getN()); assertEquals(mongoDBCollectionRemoveTest.count().first().intValue(), count - numDeletions); } @Test public void testRemove1() throws Exception { int count = mongoDBCollectionRemoveTest.count().first().intValue(); int numDeletions = 10; List<DBObject> remove = new ArrayList<>(numDeletions); for (int i = 0; i < numDeletions; i++) { remove.add(new BasicDBObject("name", "John")); } BulkWriteResult bulkWriteResult = mongoDBCollectionRemoveTest.remove(remove, null).first(); assertEquals(numDeletions, bulkWriteResult.getRemovedCount()); assertEquals(mongoDBCollectionRemoveTest.count().first().intValue(), count - numDeletions); } @Test public void testFindAndModify() throws Exception { } @Test public void testFindAndModify1() throws Exception { } @Test public void testFindAndModify2() throws Exception { } @Test public void testCreateIndex() throws Exception { } @Test public void testDropIndex() throws Exception { } @Test public void testGetIndex() throws Exception { } class BasicQueryResultWriter implements QueryResultWriter<DBObject> { int i = 0; String outfile = "/tmp/queryResultWriter.log"; DataOutputStream fileOutputStream; @Override public void open() throws IOException { System.out.println("Opening!"); this.fileOutputStream = new DataOutputStream(new FileOutputStream(outfile)); } @Override public void write(DBObject elem) throws IOException { String s = String.format("Result %d : %s\n", i++, elem.toString()); System.out.printf(s); fileOutputStream.writeBytes(s); } @Override public void close() throws IOException { System.out.println("Closing!"); fileOutputStream.close(); } } }
datastore-mongodb/src/test/java/org/opencb/datastore/mongodb/MongoDBCollectionTest.java
package org.opencb.datastore.mongodb; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import org.junit.*; import org.opencb.datastore.core.ComplexTypeConverter; import org.opencb.datastore.core.QueryOptions; import org.opencb.datastore.core.QueryResult; import org.opencb.datastore.core.QueryResultWriter; import static org.junit.Assert.*; /** * Created by imedina on 29/03/14. */ public class MongoDBCollectionTest { private static MongoDataStoreManager mongoDataStoreManager; private static MongoDataStore mongoDataStore; private static MongoDBCollection mongoDBCollection; private static MongoDBCollection mongoDBCollectionInsertTest; private static MongoDBCollection mongoDBCollectionRemoveTest; private static int N = 1000; @BeforeClass public static void beforeClass() throws Exception { mongoDataStoreManager = new MongoDataStoreManager("localhost", 27017); mongoDataStore = mongoDataStoreManager.get("datastore_test"); mongoDBCollection = createTestCollection("test", N); mongoDBCollectionInsertTest = createTestCollection("insert_test", 50); mongoDBCollectionRemoveTest = createTestCollection("remove_test", 50); } @AfterClass public static void afterClass() throws Exception { mongoDataStoreManager.drop("datastore_test"); mongoDataStore.close(); } private static MongoDBCollection createTestCollection(String test, int size) { MongoDBCollection mongoDBCollection = mongoDataStore.getCollection(test); DBObject dbObject = new BasicDBObject(); for(int i = 0; i < size; i++) { dbObject = new BasicDBObject("id", i); dbObject.put("name", "John"); dbObject.put("surname", "Doe"); dbObject.put("age", i % 5); mongoDBCollection.nativeQuery().insert(dbObject, null); } return mongoDBCollection; } @Ignore @Test public void testQueryResultWriter() throws Exception { for (int i = 0; i < 100; i++) { mongoDBCollection.insert(new BasicDBObject("id", i), null); } BasicQueryResultWriter queryResultWriter = new BasicQueryResultWriter(); mongoDBCollection.setQueryResultWriter(queryResultWriter); QueryResult<DBObject> dbObjectQueryResult = mongoDBCollection.find(new BasicDBObject("id", new BasicDBObject("$gt", 50)), null); System.out.println(dbObjectQueryResult); assert (dbObjectQueryResult.getResult().isEmpty()); mongoDBCollection.setQueryResultWriter(null); dbObjectQueryResult = mongoDBCollection.find(new BasicDBObject("id", new BasicDBObject("$gt", 50)), null); System.out.println(dbObjectQueryResult); assert (!dbObjectQueryResult.getResult().isEmpty()); } @Test public void testDistinct() throws Exception { QueryResult<Object> id1 = mongoDBCollection.distinct("id", null); QueryResult<Integer> id2 = mongoDBCollection.distinct("id", null, new ComplexTypeConverter<Integer, Object>() { @Override public Integer convertToDataModelType(Object object) { if(object instanceof Integer) { return (Integer) object; } else { System.out.println("Non integer result : " + object); return 0; } } @Override public Object convertToStorageType(Integer object) { return null; } }); // System.out.println(mongoDBCollection.distinct("name", null).getNumResults()); // System.out.println(mongoDBCollection.nativeQuery().distinct("name")); } @Test public void testCount() throws Exception { QueryResult<Long> queryResult = mongoDBCollection.count(); assertEquals("The number of documents must be equals", new Long(N), queryResult.getResult().get(0)); } @Test public void testCount1() throws Exception { QueryResult<Long> queryResult = mongoDBCollection.count(); assertEquals("The number must be equals", new Long(N), queryResult.first()); } @Test public void testDistinct1() throws Exception { QueryResult<Object> queryResult = mongoDBCollection.distinct("age", null); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.Integer'", "java.lang.Integer", queryResult.getResultType()); } @Test public void testDistinct2() throws Exception { QueryResult<String> queryResult = mongoDBCollection.distinct("name", null, String.class); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.String'", "java.lang.String", queryResult.getResultType()); } @Test public void testDistinct3() throws Exception { QueryResult<Integer> queryResult = mongoDBCollection.distinct("age", null, new ComplexTypeConverter<Integer, Object>() { @Override public Integer convertToDataModelType(Object object) { return Integer.parseInt(object.toString()); } @Override public Object convertToStorageType(Integer object) { return null; } }); assertNotNull("Object cannot be null", queryResult); assertEquals("ResultType must be 'java.lang.Integer'", "java.lang.Integer", queryResult.getResultType()); } @Test public void testFind() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); QueryOptions queryOptions = new QueryOptions("include", Arrays.asList("id")); QueryResult<DBObject> queryResult = mongoDBCollection.find(dbObject, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertEquals("Returned Id does not match", 4, queryResult.first().get("id")); // System.out.println("queryResult 'include' = " + queryResult); } @Test public void testFind1() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<DBObject> queryResult = mongoDBCollection.find(dbObject, returnFields, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertNull("Field 'name' must not exist", queryResult.first().get("name")); // System.out.println("queryResult 'projection' = " + queryResult); } @Test public void testFind2() throws Exception { DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<HashMap> queryResult = mongoDBCollection.find(dbObject, returnFields, HashMap.class, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertTrue("Returned field must instance of Hashmap", queryResult.first() instanceof HashMap); } @Test public void testFind3() throws Exception { final DBObject dbObject = new BasicDBObject("id", 4); DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); QueryResult<HashMap> queryResult = mongoDBCollection.find(dbObject, returnFields, new ComplexTypeConverter<HashMap, DBObject>() { @Override public HashMap convertToDataModelType(DBObject object) { return new HashMap(dbObject.toMap()); } @Override public DBObject convertToStorageType(HashMap object) { return null; } }, queryOptions); assertNotNull("Object cannot be null", queryResult.getResult()); assertTrue("Returned field must instance of Hashmap", queryResult.first() instanceof HashMap); } @Test public void testFind4() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } QueryOptions queryOptions = new QueryOptions("include", Arrays.asList("id")); List<QueryResult<DBObject>> queryResultList = mongoDBCollection.find(dbObjectList, queryOptions); assertEquals("List must contain 10 results", 10, queryResultList.size()); assertNotNull("Object cannot be null", queryResultList.get(0).getResult()); assertEquals("Returned Id does not match", 9, queryResultList.get(9).first().get("id")); } @Test public void testFind5() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<DBObject>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, queryOptions); assertEquals("List must contain 10 results", 10, queryResultList.size()); assertNotNull("Object cannot be null", queryResultList.get(0).getResult()); assertNull("Field 'name' must not exist", queryResultList.get(0).first().get("name")); assertEquals("resultType must be 'com.mongodb.BasicDBObject'", "com.mongodb.BasicDBObject", queryResultList.get(0).getResultType()); } @Test public void testFind6() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<HashMap>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, HashMap.class, queryOptions); assertNotNull("Object queryResultList cannot be null", queryResultList); assertNotNull("Object queryResultList.get(0) cannot be null", queryResultList.get(0).getResult()); assertTrue("Returned field must instance of HashMap", queryResultList.get(0).first() instanceof HashMap); assertEquals("resultType must 'java.util.HashMap'", "java.util.HashMap", queryResultList.get(0).getResultType()); } @Test public void testFind7() throws Exception { final List<DBObject> dbObjectList = new ArrayList<>(10); for (int i = 0; i < 10; i++) { dbObjectList.add(new BasicDBObject("id", i)); } DBObject returnFields = new BasicDBObject("id", 1); QueryOptions queryOptions = new QueryOptions("exclude", Arrays.asList("id")); List<QueryResult<HashMap>> queryResultList = mongoDBCollection.find(dbObjectList, returnFields, new ComplexTypeConverter<HashMap, DBObject>() { @Override public HashMap convertToDataModelType(DBObject object) { return new HashMap(object.toMap()); } @Override public DBObject convertToStorageType(HashMap object) { return null; } }, queryOptions); assertNotNull("Object queryResultList cannot be null", queryResultList); assertNotNull("Object queryResultList.get(0) cannot be null", queryResultList.get(0).getResult()); assertTrue("Returned field must instance of Hashmap", queryResultList.get(0).first() instanceof HashMap); assertEquals("resultType must 'java.util.HashMap'", "java.util.HashMap", queryResultList.get(0).getResultType()); } @Test public void testAggregate() throws Exception { List<DBObject> dbObjectList = new ArrayList<>(); DBObject match = new BasicDBObject("$match", new BasicDBObject("age", new BasicDBObject("$gt", 2))); DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$age")); dbObjectList.add(match); dbObjectList.add(group); QueryResult queryResult = mongoDBCollection.aggregate(dbObjectList, null); assertNotNull("Object queryResult cannot be null", queryResult); assertNotNull("Object queryResult.getResult() cannot be null", queryResult.getResult()); assertEquals("There must be 2 results", 2, queryResult.getResult().size()); } @Test public void testInsert() throws Exception { } @Test public void testInsert1() throws Exception { } @Test public void testUpdate() throws Exception { } @Test public void testUpdate1() throws Exception { } @Test public void testRemove() throws Exception { } @Test public void testFindAndModify() throws Exception { } @Test public void testFindAndModify1() throws Exception { } @Test public void testFindAndModify2() throws Exception { } @Test public void testCreateIndex() throws Exception { } @Test public void testDropIndex() throws Exception { } @Test public void testGetIndex() throws Exception { } class BasicQueryResultWriter implements QueryResultWriter<DBObject> { int i = 0; String outfile = "/tmp/queryResultWriter.log"; DataOutputStream fileOutputStream; @Override public void open() throws IOException { System.out.println("Opening!"); this.fileOutputStream = new DataOutputStream(new FileOutputStream(outfile)); } @Override public void write(DBObject elem) throws IOException { String s = String.format("Result %d : %s\n", i++, elem.toString()); System.out.printf(s); fileOutputStream.writeBytes(s); } @Override public void close() throws IOException { System.out.println("Closing!"); fileOutputStream.close(); } } }
mongodb: MongoDBCollection insert, update and remove tests implemented.
datastore-mongodb/src/test/java/org/opencb/datastore/mongodb/MongoDBCollectionTest.java
mongodb: MongoDBCollection insert, update and remove tests implemented.
<ide><path>atastore-mongodb/src/test/java/org/opencb/datastore/mongodb/MongoDBCollectionTest.java <ide> import java.io.IOException; <ide> import java.util.*; <ide> <del>import com.mongodb.BasicDBObject; <del>import com.mongodb.DBObject; <add>import com.mongodb.*; <ide> import org.junit.*; <add>import org.junit.rules.ExpectedException; <ide> import org.opencb.datastore.core.ComplexTypeConverter; <ide> import org.opencb.datastore.core.QueryOptions; <ide> import org.opencb.datastore.core.QueryResult; <ide> private static MongoDataStore mongoDataStore; <ide> private static MongoDBCollection mongoDBCollection; <ide> private static MongoDBCollection mongoDBCollectionInsertTest; <add> private static MongoDBCollection mongoDBCollectionUpdateTest; <ide> private static MongoDBCollection mongoDBCollectionRemoveTest; <ide> <ide> private static int N = 1000; <add> <add> @Rule <add> public ExpectedException thrown = ExpectedException.none(); <ide> <ide> @BeforeClass <ide> public static void beforeClass() throws Exception { <ide> <ide> mongoDBCollection = createTestCollection("test", N); <ide> mongoDBCollectionInsertTest = createTestCollection("insert_test", 50); <add> mongoDBCollectionUpdateTest = createTestCollection("update_test", 50); <ide> mongoDBCollectionRemoveTest = createTestCollection("remove_test", 50); <ide> } <ide> <ide> <ide> private static MongoDBCollection createTestCollection(String test, int size) { <ide> MongoDBCollection mongoDBCollection = mongoDataStore.getCollection(test); <del> DBObject dbObject = new BasicDBObject(); <add> DBObject dbObject; <ide> for(int i = 0; i < size; i++) { <ide> dbObject = new BasicDBObject("id", i); <ide> dbObject.put("name", "John"); <ide> <ide> @Test <ide> public void testInsert() throws Exception { <del> <add> Long countBefore = mongoDBCollectionInsertTest.count().first(); <add> for (int i = 1; i < 50; i++) { <add> mongoDBCollectionInsertTest.insert(new BasicDBObject("insertedObject", i), null); <add> assertEquals("Insert operation must insert 1 element each time.", countBefore + i, mongoDBCollectionInsertTest.count().first().longValue() ); <add> } <ide> } <ide> <ide> @Test <ide> public void testInsert1() throws Exception { <del> <add> BasicDBObject uniqueObject = new BasicDBObject("_id", "myUniqueId"); <add> mongoDBCollectionInsertTest.insert(uniqueObject, null); <add> <add> thrown.expect(DuplicateKeyException.class); <add> mongoDBCollectionInsertTest.insert(uniqueObject, null); <add> } <add> <add> @Test <add> public void testInsert2() throws Exception { <add> Long countBefore = mongoDBCollectionInsertTest.count().first(); <add> int numBulkInsertions = 50; <add> int bulkInsertSize = 100; <add> <add> for (int b = 1; b < numBulkInsertions; b++) { <add> ArrayList<DBObject> list = new ArrayList<>(bulkInsertSize); <add> for (int i = 0; i < bulkInsertSize; i++) { <add> list.add(new BasicDBObject("bulkInsertedObject", i)); <add> } <add> mongoDBCollectionInsertTest.insert(list, null); <add> assertEquals("Bulk insert operation must insert " + bulkInsertSize + " elements each time.", countBefore + bulkInsertSize * b, mongoDBCollectionInsertTest.count().first().longValue()); <add> } <add> } <add> <add> @Test <add> public void testInsert3() throws Exception { <add> BasicDBObject uniqueObject = new BasicDBObject("_id", "myUniqueId"); <add> <add> ArrayList<DBObject> list = new ArrayList<>(10); <add> for (int i = 0; i < 10; i++) { <add> list.add(uniqueObject); <add> } <add> <add> thrown.expect(BulkWriteException.class); <add> mongoDBCollectionInsertTest.insert(list, null); <ide> } <ide> <ide> @Test <ide> public void testUpdate() throws Exception { <del> <add> BasicDBObject query = new BasicDBObject("name", "John"); <add> long count = mongoDBCollectionUpdateTest.count(query).first(); <add> WriteResult writeResult = mongoDBCollectionUpdateTest.update(query, <add> new BasicDBObject("$set", new BasicDBObject("modified", true)), <add> new QueryOptions("multi", true) <add> ).first(); <add> assertEquals("All the objects are named \"John\", so all objects should be modified", count, writeResult.getN()); <ide> } <ide> <ide> @Test <ide> public void testUpdate1() throws Exception { <del> <add> WriteResult writeResult = mongoDBCollectionUpdateTest.update(new BasicDBObject("surname", "Johnson"), <add> new BasicDBObject("$set", new BasicDBObject("modifiedAgain", true)), <add> new QueryOptions("multi", true) <add> ).first(); <add> assertEquals("Any objects have the surname \"Johnson\", so any objects should be modified", 0, writeResult.getN()); <add> } <add> <add> @Test <add> public void testUpdate2() throws Exception { <add> WriteResult writeResult = mongoDBCollectionUpdateTest.update(new BasicDBObject("surname", "Johnson"), <add> new BasicDBObject("$set", new BasicDBObject("modifiedAgain", true)), <add> new QueryOptions("upsert", true) <add> ).first(); <add> assertEquals("Any objects have the surname \"Johnson\", so one object should be inserted", 1, writeResult.getN()); <add> } <add> <add> @Test <add> public void testUpdate3() throws Exception { <add> int count = mongoDBCollectionUpdateTest.count().first().intValue(); <add> int modifiedDocuments = count / 2; <add> ArrayList<DBObject> queries = new ArrayList<>(modifiedDocuments); <add> ArrayList<DBObject> updates = new ArrayList<>(modifiedDocuments); <add> <add> for (int i = 0; i < modifiedDocuments; i++) { <add> queries.add(new BasicDBObject("id", i)); <add> updates.add(new BasicDBObject("$set", new BasicDBObject("bulkUpdated", i))); <add> } <add> BulkWriteResult bulkWriteResult = mongoDBCollectionUpdateTest.update(queries, updates, new QueryOptions("multi", false)).first(); <add> assertEquals("", modifiedDocuments, bulkWriteResult.getModifiedCount()); <add> } <add> <add> @Test <add> public void testUpdate4() throws Exception { <add> int count = mongoDBCollectionUpdateTest.count().first().intValue(); <add> int modifiedDocuments = count / 2; <add> ArrayList<DBObject> queries = new ArrayList<>(modifiedDocuments); <add> ArrayList<DBObject> updates = new ArrayList<>(modifiedDocuments); <add> <add> for (int i = 0; i < modifiedDocuments; i++) { <add> queries.add(new BasicDBObject("id", i)); <add> updates.add(new BasicDBObject("$set", new BasicDBObject("bulkUpdated", i))); <add> } <add> updates.remove(updates.size()-1); <add> <add> thrown.expect(IndexOutOfBoundsException.class); <add> mongoDBCollectionUpdateTest.update(queries, updates, new QueryOptions("multi", false)); <ide> } <ide> <ide> @Test <ide> public void testRemove() throws Exception { <del> <add> int count = mongoDBCollectionRemoveTest.count().first().intValue(); <add> BasicDBObject query = new BasicDBObject("age", 1); <add> int numDeletions = mongoDBCollectionRemoveTest.count(query).first().intValue(); <add> WriteResult writeResult = mongoDBCollectionRemoveTest.remove(query, null).first(); <add> assertEquals(numDeletions, writeResult.getN()); <add> assertEquals(mongoDBCollectionRemoveTest.count().first().intValue(), count - numDeletions); <add> } <add> <add> @Test <add> public void testRemove1() throws Exception { <add> int count = mongoDBCollectionRemoveTest.count().first().intValue(); <add> <add> int numDeletions = 10; <add> List<DBObject> remove = new ArrayList<>(numDeletions); <add> for (int i = 0; i < numDeletions; i++) { <add> remove.add(new BasicDBObject("name", "John")); <add> } <add> <add> BulkWriteResult bulkWriteResult = mongoDBCollectionRemoveTest.remove(remove, null).first(); <add> assertEquals(numDeletions, bulkWriteResult.getRemovedCount()); <add> assertEquals(mongoDBCollectionRemoveTest.count().first().intValue(), count - numDeletions); <ide> } <ide> <ide> @Test
JavaScript
agpl-3.0
f7643bff194fd7cd1350c6bf81717c7ad4ce2ab9
0
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
var apiurl = "api.py"; var loadedtransactions = []; var accountsearches = [ {} ]; var showing = -1; var showtrans = {}; var editedfields = [] var limit = 25; var skip = 0; var query = accountsearches[0]; var sessioncheckinterval = null; var categories = {}; var allcategories = []; var centers = []; var tags = []; var linkparent = ""; var linkchildren = []; // "nice" jQueryUI popup message function showerror(err) { $("#errormsg").text(err); $("#errormsg").dialog("open"); } // After login, reset everything function loginsuccess() { $("#login").hide(); $("#searchoptions").show(); $("#linktransactions").show(); $("#linktransactions").width($("#searchoptions").width()) $("#linktransactions").css("top", $("#searchoptions").offset().top+$("#searchoptions").height()+10) $("#searchoptions .searchoption").each(function () { $(this).val(""); }); $("#searchoptions .queryoption").each(function () { $(this).val(""); }); clearlink(); loadedtransactions = []; showing = -1; limit = 25; skip = 0; loadaccounts(); // Get user's categories and configure everywhere $.ajax({ type: "POST", url: apiurl, data: { "action": "getcategories" }, success: function (data) { categories = data; allcategories = [] for (cat in categories) { allcategories.push(cat); allcategories = allcategories.concat(categories[cat]); } allcategories.sort(); keys = Object.keys(categories); keys.sort(); $(".category").autocomplete({ source: keys, delay: 0, minLength: 0, select: function(event, ui) { if ($(this).hasClass("transdataval")) { $("#transactiondetail .savebutton").button("enable"); if (editedfields.indexOf("category") == -1) editedfields.push("category"); } $(this).parent().children(".subcategory").autocomplete("option", "source", categories[ui.item.value]); }, change: function(event, ui) { var newauto = categories[$(this).val()]; if (newauto == undefined) newauto = allcategories; $(this).parent().children(".subcategory").autocomplete("option", "source", newauto); } }); $(".subcategory").autocomplete({ source: allcategories, delay: 0, minLength: 0, select: function(event, ui) { if ($(this).hasClass("transdataval")) { if (editedfields.indexOf("subcategory") == -1) editedfields.push("subcategory"); $("#transactiondetail .savebutton").button("enable"); } catval = $(this).parent().children(".category").val(); if ((catval == "") || (categories[catval] == undefined) || (categories[catval].indexOf(ui.item.value) == -1)) { if (categories[ui.item.value] != undefined) { $(this).parent().children(".category").val(ui.item.value); $(this).val(""); return false; } for (cat in categories) { if (categories[cat].indexOf(ui.item.value) != -1) { $(this).parent().children(".category").val(cat); if ($(this).hasClass("transdataval")) { if (editedfields.indexOf("category") == -1) editedfields.push("category"); $("#transactiondetail .savebutton").button("enable"); } break; } } } } }); }, error: function () { showerr("Error loading categories!"); } }); // Get user's cost centers, load up elements. $.ajax({ type: "POST", url: apiurl, data: { "action": "getcenters" }, success: function(data) { centers = data; $(".centersel").each(function() { $(this).html(""); $(this).append("<option value=''>All</option>"); for (i = 0; i<centers.length; i++) { $(this).append("<option value='"+centers[i]+"'>"+centers[i]+"</option>"); } }); }, error: function() { showerr("Error loading cost centers!"); } }); $.ajax({ type: "POST", url: apiurl, data: { "action": "gettags" }, success: function(data) { tags = data; tags.sort(); $("#tagslist").html(""); for (t in tags) $("#tagslist").append("<li>"+tags[t]+"</li>"); $("#tagslist").selectable({ selected: function(event, ui) { if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); }, unselected: function(event, ui) { if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); } }); $("#tagslist li").addClass("ui-widget-content"); } }); // Every minute, make sure session is still good. Logout if bad. if (!sessioncheckinterval) sessioncheckinterval = setInterval(checksession, 60000); } // Clear everything, then check if we have a good session. function clearpage() { $("#login").hide(); $("#transactions").hide(); $("#transactiondetail").dialog("close"); $("#accounts").hide(); $("#errormsg").hide(); $("#searchoptions").hide(); $("#newaccount").hide(); $("#tagselect").hide(); $("#linktransactions").hide(); $("#username").val(""); $("#password").val(""); if (sessioncheckinterval) { clearInterval(sessioncheckinterval); sessioncheckinterval = null; } $.ajax({ type: "POST", url: apiurl, data: { "action": "checklogin" }, success: function(data) { if (data) { loginsuccess(); } else { $("#login").show(); $("#login").center(); $("#username").focus(); } }, error: function() { $("#login").show(); $("#login").center(); $("#username").focus(); } }); } // Clear page if our session is bad. function checksession() { $.ajax({ type: "POST", url: apiurl, data: { "action": "checklogin" }, success: function(data) { if (data) { } else { clearpage(); } }, error: function() { clearpage(); } }); } // Convert amount in positive/negative cents to human-readable format function decoratedollar() { if ($(this).text().substring(0,1) == "$") return; amount = parseInt($(this).text()); if (amount > 0) $(this).addClass("posnum"); else $(this).removeClass("posnum"); $(this).text("$"+Math.abs(amount/100).toFixed(2)); } // Get accounts and balances, load up table and search options function loadaccounts() { $.ajax({ type: "POST", url: apiurl, data: { "action": "accounts" }, success: function(data) { accountsearches = accountsearches.slice(0,1); $("#accounts > #bankaccounts").html(""); for (i in data) { if (data[i]["subaccounts"].length == 0) data[i]["subaccounts"] = [{"name":"", "date": "", "amount": "0"}] for (j in data[i]["subaccounts"]) { newaccount = "<div class='account useraccount' id='account"+accountsearches.length+"'>"; newaccount += "<span class='accountname'>"+data[i]["name"]+"</span> / "; newaccount += "<span class='subname'>"+data[i]["subaccounts"][j]["name"]+"</span>"; newaccount += "<div class='dollar accountbalance'>"+data[i]["subaccounts"][j]["amount"]+"</div>"; newaccount += "<div class='accountupdate'>"+data[i]["subaccounts"][j]["date"]+"</div>"; newaccount += "</div>"; $("#accounts > #bankaccounts").append(newaccount); accountsearches.push({"account":data[i]["name"], "subaccount": data[i]["subaccounts"][j]["name"]}); } } $(".dollar").each(decoratedollar); $(".account").click(function() { skip = 0; query = accountsearches[parseInt($(this).attr("id").substring(7))]; $(".account").removeClass("ui-state-active"); $(this).addClass("ui-state-active"); loadtransactions(); }); $("#accounts").show(); $("#account0").addClass("ui-state-active"); query = accountsearches[0]; loadtransactions(); }, error: function() { showerror("Error loading accounts"); } }); } // Store our saved fields for this transaction function savetransaction() { if (editedfields.length > 0) { updatejson = new Object(); for (f in editedfields) { newval = $("#transactiondetail #"+editedfields[f]).val(); if (newval == "") newval = $("#transactiondetail #"+editedfields[f]).text(); updatejson[editedfields[f]] = newval; } if (editedfields.indexOf("amount") != -1) { newamount = $("#transactiondetail #amount").text().replace("$","").replace(",",""); if (newamount.indexOf(".") == -1) { newamount += ".00"; } else if (newamount.indexOf(".") != (newamount.length-3)) { showerror("Bad amount"); return; } newamount = newamount.replace(".",""); if (showtrans["amount"] > 0) updatejson["amount"] = parseInt(newamount); else updatejson["amount"] = -parseInt(newamount); } if (editedfields.indexOf("tags") != -1) { updatejson["tags"] = showtrans["tags"]; } $.ajax({ type: "POST", url: apiurl, data: { "action": "updatetransaction", "id": showtrans["id"], "data" : JSON.stringify(updatejson) }, success: function(data) { if (data) { showtransaction(showing); loadtransactions(); } else { showerror("Error saving transaction"); } }, error: function() { showerror("HTTP Error saving transaction"); } }); } } // Show transaction detail, either index of loadedtransactions array, or object of a transaction. function showtransaction(t) { if (typeof(t) == "number") { if (showing == t) { $("#transactiondetail").dialog("close"); showing = -1; return; } showing = t; showtrans = loadedtransactions[t]; } else { showtrans = t; } editedfields = []; $("#transactiondetail #save").button("disable"); $("#transactiondetail #saveclose").button("enable"); $("#transactiondetail > #file").hide(); $("#transactiondetail .transdata").each(function () { name = $(this).attr("id"); $(this).text(""); if (showtrans[name] != undefined) $(this).text(showtrans[name]); }); $("#transactiondetail .transdataval").each(function () { name = $(this).attr("id"); $(this).val(""); if (showtrans[name] != undefined) $(this).val(showtrans[name]); }); $("#transactiondetail > #attr").html(""); for (key in showtrans) { if ((key.indexOf("attr_") == 0) && (showtrans[key] != "")) { $("#transactiondetail > #attr").append(key.substr(5) + ": " + showtrans[key] + "<br>"); } } if (showtrans["file"] != undefined) { $("#transactiondetail > #file").attr("src",apiurl+"?image="+showtrans["id"]); $("#transactiondetail > #file").show(); } $(".dollar").each(decoratedollar); if (categories[showtrans["category"]] != undefined) $("#transactiondetail #subcategory").autocomplete("option", "source", categories[showtrans["category"]]); else $("#transactiondetail #subcategory").autocomplete("option", "source", allcategories); $("#transactiondetail #linked").html(""); if (showtrans["parent"] != undefined) { $("#transactiondetail #linked").append("Linked Transactions:<br>"); $("#transactiondetail #linked").append("<a href='#' class='translink'>"+showtrans["parent"]+"</a><br>"); } if (showtrans["children"] != undefined) { $("#transactiondetail #linked").append("Linked Transactions:<br>"); for (i=0; i<showtrans["children"].length; i++) $("#transactiondetail #linked").append("<a href='#' class='translink'>"+showtrans["children"][i]+"</a><br>"); } $("#transactiondetail #tags").html(""); if (showtrans["tags"] != undefined) { for (var tag in showtrans["tags"]) $("#transactiondetail #tags").append(showtrans["tags"][tag] + " "); } $(".translink").click(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "search", "query": JSON.stringify({"id": "$eq:" + $(this).text()}) }, success: function(data) { if (data && data.length) { showtransaction(data[0]); } else { showerror("Bad transaction data"); } }, error: function(data) { showerror("Error getting transaction"); } }); }); $("#transactiondetail").dialog("open"); } // Search, load transactions to main table function loadtransactions() { // hack to duplicate the existing query transquery = JSON.parse(JSON.stringify(query)) for (i=0; i<$("#searchoptions .queryoption").length; i++) { if ($("#searchoptions .queryoption").eq(i).val()) transquery[$("#searchoptions .queryoption").eq(i).attr("id")] = $("#searchoptions .queryoption").eq(i).val() } postdata = { "action": "search", "limit": limit, "skip": skip, "query": JSON.stringify(transquery) } for (i=0; i<$("#searchoptions .searchoption").length; i++) { if ($("#searchoptions .searchoption").eq(i).val() != "") postdata[$("#searchoptions .searchoption").eq(i).attr("id")] = $("#searchoptions .searchoption").eq(i).val() } $.ajax({ type: "POST", url: apiurl, data: postdata, success: function(data) { total = 0; loadedtransactions = data; for (t=0; t<data.length; t++) { if ($("#transtablebody > #trans"+t).length == 0) { $("#transtablebody").append("<tr class='transaction' id='trans"+t+"'>"+ "<td class='date'></td>"+ "<td class='description'></td>"+ "<td class='category'></td>"+ "<td class='centertd'></td>"+ "<td class='dollar'></td>"+ "<td><button class='close'>Close</button></tr>"); $("#trans"+t).click(function() { showtransaction(parseInt($(this).attr("id").substring(5))); }); $("#trans"+t+" .close").button(); $("#trans"+t+" .close").click(function() { transid = parseInt($(this).parent().parent().attr("id").substring(5)); $.ajax({ type: "POST", url: apiurl, data: { "action": "updatetransaction", "id": loadedtransactions[transid]["id"], "data" : JSON.stringify({"state": "closed"}) }, context: this, success: function(data) { if (data) { $(this).button("disable"); if (($("#searchoptions #state").val() != "") && ($("#searchoptions #state").val() != "closed")) $(this).parent().parent().slideUp(200); } else showerror("Error closing transaction"); }, error: function(data) { showerror("HTTP error closing transaction"); } }); return false; }); } $("#transtablebody > #trans"+t+" .date").text(data[t]["date"]); $("#transtablebody > #trans"+t+" .description").text(data[t]["desc"]); $("#transtablebody > #trans"+t+" .dollar").text(data[t]["amount"]); $("#transtablebody > #trans"+t+" .centertd").text(data[t]["center"]); $("#transtablebody > #trans"+t+" .category").text(""); if (data[t]["subcategory"] != undefined) $("#transtablebody > #trans"+t+" .category").text(data[t]["subcategory"]); else if (data[t]["category"] != undefined) $("#transtablebody > #trans"+t+" .category").text(data[t]["category"]); if (data[t]["state"] != "closed") $("#trans"+t+" .close").button("enable"); else $("#trans"+t+" .close").button("disable"); $("#transtablebody > #trans"+t).show(); total += data[t]["amount"]; } for (t=data.length; $("#transtablebody > #trans"+t).length > 0; t++) $("#transtablebody > #trans"+t).remove(); $("#transactionsum").text(total); $(".dollar").each(decoratedollar); $("#transtablebody td").addClass("ui-widget-content"); $("#transtablebody td").removeClass("ui-state-hover"); $("#transtablebody button").removeClass("ui-state-hover"); $("#transtablebody tr").hover( function() { $(this).children("td").addClass("ui-state-hover"); }, function() { $(this).children("td").removeClass("ui-state-hover"); } ); $("#transtablebody tr").draggable({ revert: true, helper: "clone" }); $("#transactions").show(); $("#transtable").width($("#searchoptions").offset().left-$("#transtable").offset().left-5); }, error: function() { showerror("Transaction loading error"); } }); } function clearlink() { linkparent = ""; linkchildren = []; $("#linktransactions div").html(""); } $(document).ready(function () { $('[contenteditable]').live('focus', function() { var $this = $(this); $this.data('before', $this.text()); return $this; }).live('blur keyup paste', function() { var $this = $(this); if ($this.data('before') !== $this.text()) { $this.data('before', $this.text()); if (editedfields.indexOf($(this).attr("id")) == -1) { editedfields.push($(this).attr("id")); $("#transactiondetail .savebutton").button("enable"); } } return $this; }); $("#transactiondetail .savebutton").button(); $("#transactiondetail #save").click(savetransaction); $("#transactiondetail #saveclose").click(function() { $("#transactiondetail #state").val("closed") editedfields.push("state"); savetransaction(); }); $("#transactiondetail > #dateselect").datepicker({ dateFormat: "yy-mm-dd", altField: "#transactiondetail > #date", onSelect: function(dateText, inst) { $("#transactiondetail > #date").text(dateText); if (editedfields.indexOf("date") == -1) { editedfields.push("date"); $("#transactiondetail .savebutton").button("enable"); } } }); $("#transactiondetail > #date").click(function() { $("#transactiondetail > #dateselect").datepicker("show"); }); $("#transactiondetail select").change(function () { if (editedfields.indexOf($(this).attr("id")) == -1) { editedfields.push($(this).attr("id")); $("#transactiondetail .savebutton").button("enable"); } if (($(this).attr("id") == "state") && ($(this).val() != "closed")) $("#transactiondetail #saveclose").button("disable"); }); $("#transactiondetail #addtag").button({ icons: { primary: "ui-icon-circle-plus" }, text: false }); $("#transactiondetail #addtag").click(function () { $("#tagselect").show(); $("#tagselect").center(); $("#tagselect ol").removeClass("ui-selected"); if (showtrans["tags"] != undefined) $("#tagselect ol").each(function () { if (showtrans["tags"].indexOf($(this).text()) != -1) $(this).addClass("ui-selected"); }); }); $("#tagselect button").button(); $("#tagselect button").click(function () { showtrans["tags"] = []; $("#transactiondetail #tags").html(""); $("#tagselect ol .ui-selected").each(function () { showtrans["tags"].push($(this).text()); $("#transactiondetail #tags").append($(this).text() + " "); if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); $("#transactiondetail .savebutton").button("enable"); }); $("#tagselect").hide(); }); $("#transactiondetail").dialog({ modal: true, autoOpen: false, title: "Edit Transaction", minWidth: 600, close: function() { showing = -1; } }); $("#searchoptions .date").datepicker({ dateFormat: "yy-mm-dd", onClose: function(dateText, inst) { loadtransactions(); } }); $("#searchoptions #center").change(function() { loadtransactions(); }); $("#searchoptions #executesearch").button(); $("#searchoptions #executesearch").click(function () { skip = 0; loadtransactions(); }); $("#searchoptions #clearsearch").button(); $("#searchoptions #clearsearch").click(function () { $("#searchoptions .searchoption").each(function () { $(this).val(""); }); $("#searchoptions .queryoption").each(function () { $(this).val(""); }); loadtransactions(); }); $("#errormsg").dialog({ modal: true, autoOpen: false, title: "Error", minWidth: 250, buttons: { Ok: function() { $(this).dialog("close"); } } }); $(".limit").click(function(event) { event.preventDefault(); if ($(this).text() == "all") limit = Number.MAX_VALUE; else limit = parseInt($(this).text()); loadtransactions(); }); $(".page").click(function(event) { event.preventDefault(); if ($(this).html() == "&lt;&lt;") { if (skip == 0) return; skip -= limit; if (skip < 0) skip = 0; loadtransactions(); } else { if (loadedtransactions.length < limit) return; skip += limit; loadtransactions(); } }); $("#logout").click(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "logout" }, success: function() { clearpage(); }, error: function() { clearpage(); } }); }); $("#loginsubmit").click(function () { $("#loginform").submit(); }); $("#loginform").keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#loginform").submit(); return false; } else { return true; } }); $("#loginform").submit(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "login", "username": $("#username").val(), "password": $("#password").val() }, success: function(data) { if (data) { loginsuccess(); } else { showerror("Login Failed"); } }, error: function() { showerror("Login Error"); } }); }); $("#newuser").click(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "newuser", "username": $("#username").val(), "password": $("#password").val() }, success: function(data) { if (data) { $("#loginsubmit").click(); } else { showerror("Username already exists"); } }, error: function() { showerror("Error making new user"); } }); }); $("#newaccount").dialog({ modal: true, autoOpen: false, title: "Add/Edit Account" }); $("#addaccount").click(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "getbanks" }, success: function(data) { newhtml = "<option value=''>Select a bank</option>"; for (i=0; i<data.length; i++) newhtml += "<option value='"+data[i]+"'>"+data[i]+"</option>"; $("#newaccount #bankname").html(newhtml); } }); $("#newaccount > #createaccount").button("disable"); $("#newaccount input").each(function() { $(this).val(""); }); $("#newaccount").dialog("open"); }); $("#newaccount .required").keyup(function () { ready = true; for (var i=0; i<$("#newaccount .required").length; i++) { if ($("#newaccount .required").eq(i).val() == "") ready = false; } if (ready) $("#newaccount > #createaccount").button("enable"); }); $("#newaccount > #createaccount").button(); $("#newaccount > #createaccount").click(function () { account = {} $("#newaccount input,select").each(function() { if ($(this).val() != "") account[$(this).attr("id")] = $(this).val(); }); $.ajax({ type: "POST", url: apiurl, data: { "action": "editaccount", "account": JSON.stringify(account) }, success: function(data) { if (data) { $("#newaccount").dialog("close"); loadaccounts(); } else { showerror("Could not add/edit account"); } }, error: function() { showerror("HTTP Error editing account"); } }); }); $("#linktransactions div").droppable({ drop: function (event, ui) { var t = parseInt($(ui.draggable).attr("id").substring(5)); if ($(this).attr("id") == "parent") { $(this).html(""); linkparent = loadedtransactions[t]["id"]; // If this already has children, clear out any new one // Then append new ones to the current list if (loadedtransactions[t]["children"]) { linkchildren = loadedtransactions[t]["children"]; $("#linktransactions #children").html(""); } } else { // Can only have one parent! if (loadedtransactions[t]["parent"]) return; linkchildren.push(loadedtransactions[t]["id"]) } $(this).append(loadedtransactions[t]["date"] + " " + loadedtransactions[t]["amount"] + " " + loadedtransactions[t]["desc"] + "<br>"); }, tolerance: "touch", hoverClass: "ui-state-active" }); $("#linktransactions button").button(); $("#linktransactions #clear").click(clearlink); $("#linktransactions #combine,#split,#dup").click(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "link", "parent": linkparent, "children": JSON.stringify(linkchildren), "linktype": $(this).attr("id") }, success: function(data) { if (data) { clearlink(); loadtransactions(); } else { showerror("Error linking transactions"); } }, error: function() { showerror("HTTP error linking transactions"); } }); }); clearpage(); $("body").addClass("ui-widget"); $("th").addClass("ui-state-default"); }); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; }
web/ui.js
var apiurl = "api.py"; var loadedtransactions = []; var accountsearches = [ {} ]; var showing = -1; var showtrans = {}; var editedfields = [] var limit = 25; var skip = 0; var query = accountsearches[0]; var sessioncheckinterval = null; var categories = {}; var allcategories = []; var centers = []; var tags = []; var linkparent = ""; var linkchildren = []; // "nice" jQueryUI popup message function showerror(err) { $("#errormsg").text(err); $("#errormsg").dialog("open"); } // After login, reset everything function loginsuccess() { $("#login").hide(); $("#searchoptions").show(); $("#linktransactions").show(); $("#linktransactions").width($("#searchoptions").width()) $("#linktransactions").css("top", $("#searchoptions").offset().top+$("#searchoptions").height()+10) $("#searchoptions .searchoption").each(function () { $(this).val(""); }); $("#searchoptions .queryoption").each(function () { $(this).val(""); }); clearlink(); loadedtransactions = []; showing = -1; limit = 25; skip = 0; loadaccounts(); // Get user's categories and configure everywhere $.ajax({ type: "POST", url: apiurl, data: { "action": "getcategories" }, success: function (data) { categories = data; allcategories = [] for (cat in categories) { allcategories.push(cat); allcategories = allcategories.concat(categories[cat]); } allcategories.sort(); keys = Object.keys(categories); keys.sort(); $(".category").autocomplete({ source: keys, delay: 0, minLength: 0, select: function(event, ui) { if ($(this).hasClass("transdataval")) { $("#transactiondetail .savebutton").button("enable"); if (editedfields.indexOf("category") == -1) editedfields.push("category"); } $(this).parent().children(".subcategory").autocomplete("option", "source", categories[ui.item.value]); }, change: function(event, ui) { var newauto = categories[$(this).val()]; if (newauto == undefined) newauto = allcategories; $(this).parent().children(".subcategory").autocomplete("option", "source", newauto); } }); $(".subcategory").autocomplete({ source: allcategories, delay: 0, minLength: 0, select: function(event, ui) { if ($(this).hasClass("transdataval")) { if (editedfields.indexOf("subcategory") == -1) editedfields.push("subcategory"); $("#transactiondetail .savebutton").button("enable"); } catval = $(this).parent().children(".category").val(); if ((catval == "") || (categories[catval] == undefined) || (categories[catval].indexOf(ui.item.value) == -1)) { if (categories[ui.item.value] != undefined) { $(this).parent().children(".category").val(ui.item.value); $(this).val(""); return false; } for (cat in categories) { if (categories[cat].indexOf(ui.item.value) != -1) { $(this).parent().children(".category").val(cat); if ($(this).hasClass("transdataval")) { if (editedfields.indexOf("category") == -1) editedfields.push("category"); $("#transactiondetail .savebutton").button("enable"); } break; } } } } }); }, error: function () { showerr("Error loading categories!"); } }); // Get user's cost centers, load up elements. $.ajax({ type: "POST", url: apiurl, data: { "action": "getcenters" }, success: function(data) { centers = data; $(".centersel").each(function() { $(this).html(""); $(this).append("<option value=''>All</option>"); for (i = 0; i<centers.length; i++) { $(this).append("<option value='"+centers[i]+"'>"+centers[i]+"</option>"); } }); }, error: function() { showerr("Error loading cost centers!"); } }); $.ajax({ type: "POST", url: apiurl, data: { "action": "gettags" }, success: function(data) { tags = data; tags.sort(); $("#tagslist").html(""); for (t in tags) $("#tagslist").append("<li>"+tags[t]+"</li>"); $("#tagslist").selectable({ selected: function(event, ui) { if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); }, unselected: function(event, ui) { if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); } }); $("#tagslist li").addClass("ui-widget-content"); } }); // Every minute, make sure session is still good. Logout if bad. if (!sessioncheckinterval) sessioncheckinterval = setInterval(checksession, 60000); } // Clear everything, then check if we have a good session. function clearpage() { $("#login").hide(); $("#transactions").hide(); $("#transactiondetail").dialog("close"); $("#accounts").hide(); $("#errormsg").hide(); $("#searchoptions").hide(); $("#newaccount").hide(); $("#tagselect").hide(); $("#linktransactions").hide(); $("#username").val(""); $("#password").val(""); if (sessioncheckinterval) { clearInterval(sessioncheckinterval); sessioncheckinterval = null; } $.ajax({ type: "POST", url: apiurl, data: { "action": "checklogin" }, success: function(data) { if (data) { loginsuccess(); } else { $("#login").show(); $("#login").center(); $("#username").focus(); } }, error: function() { $("#login").show(); $("#login").center(); $("#username").focus(); } }); } // Clear page if our session is bad. function checksession() { $.ajax({ type: "POST", url: apiurl, data: { "action": "checklogin" }, success: function(data) { if (data) { } else { clearpage(); } }, error: function() { clearpage(); } }); } // Convert amount in positive/negative cents to human-readable format function decoratedollar() { if ($(this).text().substring(0,1) == "$") return; amount = parseInt($(this).text()); if (amount > 0) $(this).addClass("posnum"); else $(this).removeClass("posnum"); $(this).text("$"+Math.abs(amount/100).toFixed(2)); } // Get accounts and balances, load up table and search options function loadaccounts() { $.ajax({ type: "POST", url: apiurl, data: { "action": "accounts" }, success: function(data) { accountsearches = accountsearches.slice(0,1); $("#accounts > #bankaccounts").html(""); for (i in data) { for (j in data[i]["subaccounts"]) { newaccount = "<div class='account useraccount' id='account"+accountsearches.length+"'>"; newaccount += "<span class='accountname'>"+data[i]["name"]+"</span> / "; newaccount += "<span class='subname'>"+data[i]["subaccounts"][j]["name"]+"</span>"; newaccount += "<div class='dollar accountbalance'>"+data[i]["subaccounts"][j]["amount"]+"</div>"; newaccount += "<div class='accountupdate'>"+data[i]["subaccounts"][j]["date"]+"</div>"; newaccount += "</div>"; $("#accounts > #bankaccounts").append(newaccount); accountsearches.push({"account":data[i]["name"], "subaccount": data[i]["subaccounts"][j]["name"]}); } } $(".dollar").each(decoratedollar); $(".account").click(function() { skip = 0; query = accountsearches[parseInt($(this).attr("id").substring(7))]; $(".account").removeClass("ui-state-active"); $(this).addClass("ui-state-active"); loadtransactions(); }); $("#accounts").show(); $("#account0").addClass("ui-state-active"); query = accountsearches[0]; loadtransactions(); }, error: function() { showerror("Error loading accounts"); } }); } // Store our saved fields for this transaction function savetransaction() { if (editedfields.length > 0) { updatejson = new Object(); for (f in editedfields) { newval = $("#transactiondetail #"+editedfields[f]).val(); if (newval == "") newval = $("#transactiondetail #"+editedfields[f]).text(); updatejson[editedfields[f]] = newval; } if (editedfields.indexOf("amount") != -1) { newamount = $("#transactiondetail #amount").text().replace("$","").replace(",",""); if (newamount.indexOf(".") == -1) { newamount += ".00"; } else if (newamount.indexOf(".") != (newamount.length-3)) { showerror("Bad amount"); return; } newamount = newamount.replace(".",""); if (showtrans["amount"] > 0) updatejson["amount"] = parseInt(newamount); else updatejson["amount"] = -parseInt(newamount); } if (editedfields.indexOf("tags") != -1) { updatejson["tags"] = showtrans["tags"]; } $.ajax({ type: "POST", url: apiurl, data: { "action": "updatetransaction", "id": showtrans["id"], "data" : JSON.stringify(updatejson) }, success: function(data) { if (data) { showtransaction(showing); loadtransactions(); } else { showerror("Error saving transaction"); } }, error: function() { showerror("HTTP Error saving transaction"); } }); } } // Show transaction detail, either index of loadedtransactions array, or object of a transaction. function showtransaction(t) { if (typeof(t) == "number") { if (showing == t) { $("#transactiondetail").dialog("close"); showing = -1; return; } showing = t; showtrans = loadedtransactions[t]; } else { showtrans = t; } editedfields = []; $("#transactiondetail #save").button("disable"); $("#transactiondetail #saveclose").button("enable"); $("#transactiondetail > #file").hide(); $("#transactiondetail .transdata").each(function () { name = $(this).attr("id"); $(this).text(""); if (showtrans[name] != undefined) $(this).text(showtrans[name]); }); $("#transactiondetail .transdataval").each(function () { name = $(this).attr("id"); $(this).val(""); if (showtrans[name] != undefined) $(this).val(showtrans[name]); }); $("#transactiondetail > #attr").html(""); for (key in showtrans) { if ((key.indexOf("attr_") == 0) && (showtrans[key] != "")) { $("#transactiondetail > #attr").append(key.substr(5) + ": " + showtrans[key] + "<br>"); } } if (showtrans["file"] != undefined) { $("#transactiondetail > #file").attr("src",apiurl+"?image="+showtrans["id"]); $("#transactiondetail > #file").show(); } $(".dollar").each(decoratedollar); if (categories[showtrans["category"]] != undefined) $("#transactiondetail #subcategory").autocomplete("option", "source", categories[showtrans["category"]]); else $("#transactiondetail #subcategory").autocomplete("option", "source", allcategories); $("#transactiondetail #linked").html(""); if (showtrans["parent"] != undefined) { $("#transactiondetail #linked").append("Linked Transactions:<br>"); $("#transactiondetail #linked").append("<a href='#' class='translink'>"+showtrans["parent"]+"</a><br>"); } if (showtrans["children"] != undefined) { $("#transactiondetail #linked").append("Linked Transactions:<br>"); for (i=0; i<showtrans["children"].length; i++) $("#transactiondetail #linked").append("<a href='#' class='translink'>"+showtrans["children"][i]+"</a><br>"); } $("#transactiondetail #tags").html(""); if (showtrans["tags"] != undefined) { for (var tag in showtrans["tags"]) $("#transactiondetail #tags").append(showtrans["tags"][tag] + " "); } $(".translink").click(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "search", "query": JSON.stringify({"id": "$eq:" + $(this).text()}) }, success: function(data) { if (data && data.length) { showtransaction(data[0]); } else { showerror("Bad transaction data"); } }, error: function(data) { showerror("Error getting transaction"); } }); }); $("#transactiondetail").dialog("open"); } // Search, load transactions to main table function loadtransactions() { // hack to duplicate the existing query transquery = JSON.parse(JSON.stringify(query)) for (i=0; i<$("#searchoptions .queryoption").length; i++) { if ($("#searchoptions .queryoption").eq(i).val()) transquery[$("#searchoptions .queryoption").eq(i).attr("id")] = $("#searchoptions .queryoption").eq(i).val() } postdata = { "action": "search", "limit": limit, "skip": skip, "query": JSON.stringify(transquery) } for (i=0; i<$("#searchoptions .searchoption").length; i++) { if ($("#searchoptions .searchoption").eq(i).val() != "") postdata[$("#searchoptions .searchoption").eq(i).attr("id")] = $("#searchoptions .searchoption").eq(i).val() } $.ajax({ type: "POST", url: apiurl, data: postdata, success: function(data) { total = 0; loadedtransactions = data; for (t=0; t<data.length; t++) { if ($("#transtablebody > #trans"+t).length == 0) { $("#transtablebody").append("<tr class='transaction' id='trans"+t+"'>"+ "<td class='date'></td>"+ "<td class='description'></td>"+ "<td class='category'></td>"+ "<td class='centertd'></td>"+ "<td class='dollar'></td>"+ "<td><button class='close'>Close</button></tr>"); $("#trans"+t).click(function() { showtransaction(parseInt($(this).attr("id").substring(5))); }); $("#trans"+t+" .close").button(); $("#trans"+t+" .close").click(function() { transid = parseInt($(this).parent().parent().attr("id").substring(5)); $.ajax({ type: "POST", url: apiurl, data: { "action": "updatetransaction", "id": loadedtransactions[transid]["id"], "data" : JSON.stringify({"state": "closed"}) }, context: this, success: function(data) { if (data) { $(this).button("disable"); if (($("#searchoptions #state").val() != "") && ($("#searchoptions #state").val() != "closed")) $(this).parent().parent().slideUp(200); } else showerror("Error closing transaction"); }, error: function(data) { showerror("HTTP error closing transaction"); } }); return false; }); } $("#transtablebody > #trans"+t+" .date").text(data[t]["date"]); $("#transtablebody > #trans"+t+" .description").text(data[t]["desc"]); $("#transtablebody > #trans"+t+" .dollar").text(data[t]["amount"]); $("#transtablebody > #trans"+t+" .centertd").text(data[t]["center"]); $("#transtablebody > #trans"+t+" .category").text(""); if (data[t]["subcategory"] != undefined) $("#transtablebody > #trans"+t+" .category").text(data[t]["subcategory"]); else if (data[t]["category"] != undefined) $("#transtablebody > #trans"+t+" .category").text(data[t]["category"]); if (data[t]["state"] != "closed") $("#trans"+t+" .close").button("enable"); else $("#trans"+t+" .close").button("disable"); $("#transtablebody > #trans"+t).show(); total += data[t]["amount"]; } for (t=data.length; $("#transtablebody > #trans"+t).length > 0; t++) $("#transtablebody > #trans"+t).remove(); $("#transactionsum").text(total); $(".dollar").each(decoratedollar); $("#transtablebody td").addClass("ui-widget-content"); $("#transtablebody td").removeClass("ui-state-hover"); $("#transtablebody button").removeClass("ui-state-hover"); $("#transtablebody tr").hover( function() { $(this).children("td").addClass("ui-state-hover"); }, function() { $(this).children("td").removeClass("ui-state-hover"); } ); $("#transtablebody tr").draggable({ revert: true, helper: "clone" }); $("#transactions").show(); $("#transtable").width($("#searchoptions").offset().left-$("#transtable").offset().left-5); }, error: function() { showerror("Transaction loading error"); } }); } function clearlink() { linkparent = ""; linkchildren = []; $("#linktransactions div").html(""); } $(document).ready(function () { $('[contenteditable]').live('focus', function() { var $this = $(this); $this.data('before', $this.text()); return $this; }).live('blur keyup paste', function() { var $this = $(this); if ($this.data('before') !== $this.text()) { $this.data('before', $this.text()); if (editedfields.indexOf($(this).attr("id")) == -1) { editedfields.push($(this).attr("id")); $("#transactiondetail .savebutton").button("enable"); } } return $this; }); $("#transactiondetail .savebutton").button(); $("#transactiondetail #save").click(savetransaction); $("#transactiondetail #saveclose").click(function() { $("#transactiondetail #state").val("closed") editedfields.push("state"); savetransaction(); }); $("#transactiondetail > #dateselect").datepicker({ dateFormat: "yy-mm-dd", altField: "#transactiondetail > #date", onSelect: function(dateText, inst) { $("#transactiondetail > #date").text(dateText); if (editedfields.indexOf("date") == -1) { editedfields.push("date"); $("#transactiondetail .savebutton").button("enable"); } } }); $("#transactiondetail > #date").click(function() { $("#transactiondetail > #dateselect").datepicker("show"); }); $("#transactiondetail select").change(function () { if (editedfields.indexOf($(this).attr("id")) == -1) { editedfields.push($(this).attr("id")); $("#transactiondetail .savebutton").button("enable"); } if (($(this).attr("id") == "state") && ($(this).val() != "closed")) $("#transactiondetail #saveclose").button("disable"); }); $("#transactiondetail #addtag").button({ icons: { primary: "ui-icon-circle-plus" }, text: false }); $("#transactiondetail #addtag").click(function () { $("#tagselect").show(); $("#tagselect").center(); $("#tagselect ol").removeClass("ui-selected"); if (showtrans["tags"] != undefined) $("#tagselect ol").each(function () { if (showtrans["tags"].indexOf($(this).text()) != -1) $(this).addClass("ui-selected"); }); }); $("#tagselect button").button(); $("#tagselect button").click(function () { showtrans["tags"] = []; $("#transactiondetail #tags").html(""); $("#tagselect ol .ui-selected").each(function () { showtrans["tags"].push($(this).text()); $("#transactiondetail #tags").append($(this).text() + " "); if (editedfields.indexOf("tags") == -1) editedfields.push("tags"); $("#transactiondetail .savebutton").button("enable"); }); $("#tagselect").hide(); }); $("#transactiondetail").dialog({ modal: true, autoOpen: false, title: "Edit Transaction", minWidth: 600, close: function() { showing = -1; } }); $("#searchoptions .date").datepicker({ dateFormat: "yy-mm-dd", onClose: function(dateText, inst) { loadtransactions(); } }); $("#searchoptions #center").change(function() { loadtransactions(); }); $("#searchoptions #executesearch").button(); $("#searchoptions #executesearch").click(function () { skip = 0; loadtransactions(); }); $("#searchoptions #clearsearch").button(); $("#searchoptions #clearsearch").click(function () { $("#searchoptions .searchoption").each(function () { $(this).val(""); }); $("#searchoptions .queryoption").each(function () { $(this).val(""); }); loadtransactions(); }); $("#errormsg").dialog({ modal: true, autoOpen: false, title: "Error", minWidth: 250, buttons: { Ok: function() { $(this).dialog("close"); } } }); $(".limit").click(function(event) { event.preventDefault(); if ($(this).text() == "all") limit = Number.MAX_VALUE; else limit = parseInt($(this).text()); loadtransactions(); }); $(".page").click(function(event) { event.preventDefault(); if ($(this).html() == "&lt;&lt;") { if (skip == 0) return; skip -= limit; if (skip < 0) skip = 0; loadtransactions(); } else { if (loadedtransactions.length < limit) return; skip += limit; loadtransactions(); } }); $("#logout").click(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "logout" }, success: function() { clearpage(); }, error: function() { clearpage(); } }); }); $("#loginsubmit").click(function () { $("#loginform").submit(); }); $("#loginform").keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#loginform").submit(); return false; } else { return true; } }); $("#loginform").submit(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "login", "username": $("#username").val(), "password": $("#password").val() }, success: function(data) { if (data) { loginsuccess(); } else { showerror("Login Failed"); } }, error: function() { showerror("Login Error"); } }); }); $("#newuser").click(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "newuser", "username": $("#username").val(), "password": $("#password").val() }, success: function(data) { if (data) { $("#loginsubmit").click(); } else { showerror("Username already exists"); } }, error: function() { showerror("Error making new user"); } }); }); $("#newaccount").dialog({ modal: true, autoOpen: false, title: "Add/Edit Account" }); $("#addaccount").click(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: apiurl, data: { "action": "getbanks" }, success: function(data) { newhtml = "<option value=''>Select a bank</option>"; for (i=0; i<data.length; i++) newhtml += "<option value='"+data[i]+"'>"+data[i]+"</option>"; $("#newaccount #bankname").html(newhtml); } }); $("#newaccount > #createaccount").button("disable"); $("#newaccount input").each(function() { $(this).val(""); }); $("#newaccount").dialog("open"); }); $("#newaccount .required").keyup(function () { ready = true; for (var i=0; i<$("#newaccount .required").length; i++) { if ($("#newaccount .required").eq(i).val() == "") ready = false; } if (ready) $("#newaccount > #createaccount").button("enable"); }); $("#newaccount > #createaccount").button(); $("#newaccount > #createaccount").click(function () { account = {} $("#newaccount input,select").each(function() { if ($(this).val() != "") account[$(this).attr("id")] = $(this).val(); }); $.ajax({ type: "POST", url: apiurl, data: { "action": "editaccount", "account": JSON.stringify(account) }, success: function(data) { if (data) { $("#newaccount").dialog("close"); loadaccounts(); } else { showerror("Could not add/edit account"); } }, error: function() { showerror("HTTP Error editing account"); } }); }); $("#linktransactions div").droppable({ drop: function (event, ui) { var t = parseInt($(ui.draggable).attr("id").substring(5)); if ($(this).attr("id") == "parent") { $(this).html(""); linkparent = loadedtransactions[t]["id"]; // If this already has children, clear out any new one // Then append new ones to the current list if (loadedtransactions[t]["children"]) { linkchildren = loadedtransactions[t]["children"]; $("#linktransactions #children").html(""); } } else { // Can only have one parent! if (loadedtransactions[t]["parent"]) return; linkchildren.push(loadedtransactions[t]["id"]) } $(this).append(loadedtransactions[t]["date"] + " " + loadedtransactions[t]["amount"] + " " + loadedtransactions[t]["desc"] + "<br>"); }, tolerance: "touch", hoverClass: "ui-state-active" }); $("#linktransactions button").button(); $("#linktransactions #clear").click(clearlink); $("#linktransactions #combine,#split,#dup").click(function () { $.ajax({ type: "POST", url: apiurl, data: { "action": "link", "parent": linkparent, "children": JSON.stringify(linkchildren), "linktype": $(this).attr("id") }, success: function(data) { if (data) { clearlink(); loadtransactions(); } else { showerror("Error linking transactions"); } }, error: function() { showerror("HTTP error linking transactions"); } }); }); clearpage(); $("body").addClass("ui-widget"); $("th").addClass("ui-state-default"); }); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; }
If account has no subaccounts, print it out anyway so it can be searched.
web/ui.js
If account has no subaccounts, print it out anyway so it can be searched.
<ide><path>eb/ui.js <ide> accountsearches = accountsearches.slice(0,1); <ide> $("#accounts > #bankaccounts").html(""); <ide> for (i in data) { <add> if (data[i]["subaccounts"].length == 0) <add> data[i]["subaccounts"] = [{"name":"", "date": "", "amount": "0"}] <ide> for (j in data[i]["subaccounts"]) { <ide> newaccount = "<div class='account useraccount' id='account"+accountsearches.length+"'>"; <ide> newaccount += "<span class='accountname'>"+data[i]["name"]+"</span> / ";
JavaScript
mit
3543f864797ec2e73b6e47a12d31afb4c88b5945
0
erikdstock/force,damassi/force,joeyAghion/force,erikdstock/force,artsy/force-public,xtina-starr/force,damassi/force,anandaroop/force,yuki24/force,artsy/force,artsy/force,eessex/force,izakp/force,izakp/force,cavvia/force-1,oxaudo/force,mzikherman/force,anandaroop/force,artsy/force-public,xtina-starr/force,oxaudo/force,mzikherman/force,yuki24/force,damassi/force,eessex/force,cavvia/force-1,erikdstock/force,xtina-starr/force,mzikherman/force,izakp/force,cavvia/force-1,anandaroop/force,yuki24/force,joeyAghion/force,eessex/force,artsy/force,oxaudo/force,yuki24/force,artsy/force,anandaroop/force,izakp/force,joeyAghion/force,joeyAghion/force,mzikherman/force,eessex/force,damassi/force,oxaudo/force,xtina-starr/force,cavvia/force-1,erikdstock/force
// // Analytics for the main layout. This includes buttons in the header, footer // or any other actions that occur on each page. // import { data as sd } from "sharify" import { reportLoadTimeToVolley } from "lib/volley" // Track pageview const pageType = window.sd.PAGE_TYPE || window.location.pathname.split("/")[1] var properties = { path: location.pathname } if (pageType == "artwork") { properties["acquireable"] = sd.ARTWORK.is_acquireable properties["availability"] = sd.ARTWORK.availability properties["price_listed"] = sd.ARTWORK.price && sd.ARTWORK.price.length > 0 } // We exclude 'orders' routes from analytics.page calls because they're already // taken care of in another place. const excludedRoutes = ["orders"] if (!excludedRoutes.includes(pageType)) { analytics.page(properties, { integrations: { Marketo: false } }) } // Track pageload speed if ( window.performance && window.performance.timing && sd.TRACK_PAGELOAD_PATHS ) { window.addEventListener("load", function() { if (sd.TRACK_PAGELOAD_PATHS.split("|").includes(pageType)) { window.setTimeout(function() { const { requestStart, loadEventEnd, domComplete, } = window.performance.timing reportLoadTimeToVolley( requestStart, loadEventEnd, domComplete, pageType, "desktop" ) }, 0) } }) } class PageTimeTracker { constructor(path, delay, description) { this.path = path this.delay = delay this.description = description this.timer = null this.track() } setPath(newPath) { this.path = newPath } track() { this.timer = setTimeout(() => { window.analytics.track("Time on page", { category: this.description, message: this.path, }) }, this.delay) } clear() { if (this.timer) clearTimeout(this.timer) } reset(newPath = null) { this.clear() if (newPath) this.setPath(newPath) this.track() } } window.desktopPageTimeTrackers = [ new PageTimeTracker(sd.CURRENT_PATH, 15000, "15 seconds"), new PageTimeTracker(sd.CURRENT_PATH, 30000, "30 seconds"), new PageTimeTracker(sd.CURRENT_PATH, 60000, "1 minute"), new PageTimeTracker(sd.CURRENT_PATH, 180000, "3 minutes"), ] // debug tracking calls if (sd.SHOW_ANALYTICS_CALLS) { analytics.on("track", function() { console.info("TRACKED: ", arguments[0], JSON.stringify(arguments[1])) }) } if (sd.SHOW_ANALYTICS_CALLS) { analyticsHooks.on("all", function(name, data) { console.info("ANALYTICS HOOK: ", name, data) }) }
src/desktop/analytics/main_layout.js
// // Analytics for the main layout. This includes buttons in the header, footer // or any other actions that occur on each page. // import { data as sd } from "sharify" import { reportLoadTimeToVolley } from "lib/volley" // Track pageview const pageType = window.sd.PAGE_TYPE || window.location.pathname.split("/")[1] var properties = { path: location.pathname } if (pageType == "artwork") { properties["acquireable"] = sd.ARTWORK.is_acquireable properties["availability"] = sd.ARTWORK.availability properties["price_listed"] = sd.ARTWORK.price && sd.ARTWORK.price.length > 0 } analytics.page(properties, { integrations: { Marketo: false } }) // Track pageload speed if ( window.performance && window.performance.timing && sd.TRACK_PAGELOAD_PATHS ) { window.addEventListener("load", function() { if (sd.TRACK_PAGELOAD_PATHS.split("|").includes(pageType)) { window.setTimeout(function() { const { requestStart, loadEventEnd, domComplete, } = window.performance.timing reportLoadTimeToVolley( requestStart, loadEventEnd, domComplete, pageType, "desktop" ) }, 0) } }) } class PageTimeTracker { constructor(path, delay, description) { this.path = path this.delay = delay this.description = description this.timer = null this.track() } setPath(newPath) { this.path = newPath } track() { this.timer = setTimeout(() => { window.analytics.track("Time on page", { category: this.description, message: this.path, }) }, this.delay) } clear() { if (this.timer) clearTimeout(this.timer) } reset(newPath = null) { this.clear() if (newPath) this.setPath(newPath) this.track() } } window.desktopPageTimeTrackers = [ new PageTimeTracker(sd.CURRENT_PATH, 15000, "15 seconds"), new PageTimeTracker(sd.CURRENT_PATH, 30000, "30 seconds"), new PageTimeTracker(sd.CURRENT_PATH, 60000, "1 minute"), new PageTimeTracker(sd.CURRENT_PATH, 180000, "3 minutes"), ] // debug tracking calls if (sd.SHOW_ANALYTICS_CALLS) { analytics.on("track", function() { console.info("TRACKED: ", arguments[0], JSON.stringify(arguments[1])) }) } if (sd.SHOW_ANALYTICS_CALLS) { analyticsHooks.on("all", function(name, data) { console.info("ANALYTICS HOOK: ", name, data) }) }
Excluede 'orders' routes from analytics.page calls because they're taken care of in order app client.js
src/desktop/analytics/main_layout.js
Excluede 'orders' routes from analytics.page calls because they're taken care of in order app client.js
<ide><path>rc/desktop/analytics/main_layout.js <ide> properties["price_listed"] = sd.ARTWORK.price && sd.ARTWORK.price.length > 0 <ide> } <ide> <del>analytics.page(properties, { integrations: { Marketo: false } }) <add>// We exclude 'orders' routes from analytics.page calls because they're already <add>// taken care of in another place. <add>const excludedRoutes = ["orders"] <add>if (!excludedRoutes.includes(pageType)) { <add> analytics.page(properties, { integrations: { Marketo: false } }) <add>} <ide> <ide> // Track pageload speed <ide> if (
Java
apache-2.0
bb0370dd2d803c489ca7fb6b3748d4b3632fe492
0
chr78rm/tracelogger
/** * <div style="text-align: justify"> * Provides the basic tracing faclitities. The most important class is {@link de.christofreichardt.diagnosis.AbstractTracer AbstractTracer} which is the root * of the tracer hierarchy. The {@link de.christofreichardt.diagnosis.TracerFactory TracerFactory} can be feed with an appropriate configuration and thereupon can be used * to access tracers by name, by thread or from a blocking, bounded queue. * </div> */ package de.christofreichardt.diagnosis;
src/main/java/de/christofreichardt/diagnosis/package-info.java
/** * <div style="text-align: justify"> * Provides the basic tracing faclitities. The most important class is {@link AbstractTracer} which is the root * of the tracer hierarchy. The {@link TracerFactory} can be feed with an appropriate configuration and thereupon can be used * to access tracers by name, by thread or from a blocking, bounded queue. * </div> */ package de.christofreichardt.diagnosis;
Javadoc warnings corrected.
src/main/java/de/christofreichardt/diagnosis/package-info.java
Javadoc warnings corrected.
<ide><path>rc/main/java/de/christofreichardt/diagnosis/package-info.java <ide> /** <ide> * <div style="text-align: justify"> <del> * Provides the basic tracing faclitities. The most important class is {@link AbstractTracer} which is the root <del> * of the tracer hierarchy. The {@link TracerFactory} can be feed with an appropriate configuration and thereupon can be used <add> * Provides the basic tracing faclitities. The most important class is {@link de.christofreichardt.diagnosis.AbstractTracer AbstractTracer} which is the root <add> * of the tracer hierarchy. The {@link de.christofreichardt.diagnosis.TracerFactory TracerFactory} can be feed with an appropriate configuration and thereupon can be used <ide> * to access tracers by name, by thread or from a blocking, bounded queue. <ide> * </div> <ide> */
JavaScript
isc
416dc44d05244b77a9c60f549dbfd574ab2f0fb9
0
wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,darkdarkdragon/ripple-lib
var util = require('util'); var url = require('url'); var EventEmitter = require('events').EventEmitter; var Amount = require('./amount').Amount; var Transaction = require('./transaction').Transaction; var log = require('./log').internal.sub('server'); /** * @constructor Server * * @param {Remote} Reference to a Remote object * @param {Object} Options * @param {String} host * @param {Number|String} port * @param [Boolean] securec */ function Server(remote, opts) { EventEmitter.call(this); var self = this; if (typeof opts === 'string') { var parsedUrl = url.parse(opts); opts = { host: parsedUrl.hostname, port: parsedUrl.port, secure: (parsedUrl.protocol === 'ws:') ? false : true }; } if (typeof opts !== 'object') { throw new TypeError('Server configuration is not an Object'); } if (!Server.domainRE.test(opts.host)) { throw new Error('Server host is malformed, use "host" and "port" server configuration'); } // We want to allow integer strings as valid port numbers for backward compatibility if (!(opts.port = Number(opts.port))) { throw new TypeError('Server port must be a number'); } if (opts.port < 1 || opts.port > 65535) { throw new TypeError('Server "port" must be an integer in range 1-65535'); } if (typeof opts.secure !== 'boolean') { opts.secure = true; } this._remote = remote; this._opts = opts; this._ws = void(0); this._connected = false; this._shouldConnect = false; this._state = 'offline'; this._id = 0; this._retry = 0; this._requests = { }; this._load_base = 256; this._load_factor = 256; this._fee = 10; this._fee_ref = 10; this._fee_base = 10; this._reserve_base = void(0); this._reserve_inc = void(0); this._fee_cushion = this._remote.fee_cushion; this._lastLedgerIndex = NaN; this._lastLedgerClose = NaN; this._score = 0; this._scoreWeights = { ledgerclose: 5, response: 1 }; this._url = this._opts.url = (this._opts.secure ? 'wss://' : 'ws://') + this._opts.host + ':' + this._opts.port; this._hostid = ''; function onMessage(message) { self._handleMessage(message); }; this.on('message', onMessage); function onSubscribeResponse(message) { self._handleResponseSubscribe(message); }; this.on('response_subscribe', onSubscribeResponse); function setActivityInterval() { var interval = self._checkActivity.bind(self); self._activityInterval = setInterval(interval, 1000); }; this.on('disconnect', function onDisconnect() { clearInterval(self._activityInterval); self.once('ledger_closed', setActivityInterval); }); this.once('ledger_closed', setActivityInterval); this._remote.on('ledger_closed', function(ledger) { self._updateScore('ledgerclose', ledger); }); this.on('response_ping', function(message, request) { self._updateScore('response', request); }); this.on('load_changed', function(load) { self._updateScore('loadchange', load); }); this.on('response_server_info', function(message) { try { self._hostid = '(' + message.info.pubkey_node + ')'; } catch (e) { } }); this.on('connect', function() { self._request(self._remote.requestServerInfo()); }); }; util.inherits(Server, EventEmitter); Server.domainRE = /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?)*\.?$/; /** * Server states that we will treat as the server being online. * * Our requirements are that the server can process transactions and notify * us of changes. */ Server.onlineStates = [ 'syncing', 'tracking', 'proposing', 'validating', 'full' ]; /** * This is the final interface between client code and a socket connection to a * `rippled` server. As such, this is a decent hook point to allow a WebSocket * interface conforming object to be used as a basis to mock rippled. This * avoids the need to bind a websocket server to a port and allows a more * synchronous style of code to represent a client <-> server message sequence. * We can also use this to log a message sequence to a buffer. * * @api private */ Server.websocketConstructor = function() { // We require this late, because websocket shims may be loaded after // ripple-lib in the browser return require('ws'); }; /** * Set server state * * @param {String} state * @api private */ Server.prototype._setState = function(state) { if (state !== this._state) { if (this._remote.trace) { log.info('set_state:', this._opts.url, this._hostid, state); } this._state = state; this.emit('state', state); switch (state) { case 'online': this._connected = true; this._retry = 0; this.emit('connect'); break; case 'offline': this._connected = false; this.emit('disconnect'); break; } } }; /** * Check that server is still active. * * Server activity is determined by ledger_closed events. * Maximum delay to receive a ledger_closed event is 20s. * * If server is inactive, reconnect * * @api private */ Server.prototype._checkActivity = function() { if (!this._connected) { return; } if (isNaN(this._lastLedgerClose)) { return; } var delta = (Date.now() - this._lastLedgerClose); if (delta > (1000 * 25)) { log.info('reconnect: activity delta:', delta); this.reconnect(); } }; /** * Server maintains a score for request prioritization. * * The score is determined by various data including * this server's lag to receive ledger_closed events, * ping response time, and load(fee) change * * @param {String} type * @param {Object} data * @api private */ Server.prototype._updateScore = function(type, data) { if (!this._connected) { return; } var weight = this._scoreWeights[type] || 1; switch (type) { case 'ledgerclose': // Ledger lag var delta = data.ledger_index - this._lastLedgerIndex; if (delta > 0) { this._score += weight * delta; } break; case 'response': // Ping lag var delta = Math.floor((Date.now() - data.time) / 200); this._score += weight * delta; break; case 'loadchange': // Load/fee change this._fee = Number(this._computeFee(10)); break; } if (this._score > 1e3) { log.info('reconnect: score:', this._score); this.reconnect(); } }; /** * Get the server's remote address * * Incompatible with ripple-lib client build */ Server.prototype.getRemoteAddress = Server.prototype._remoteAddress = function() { var address; try { address = this._ws._socket.remoteAddress; } catch (e) { } return address; }; /** * Get the server's hostid */ Server.prototype.getHostID = function() { return this._hostid; }; /** * Disconnect from rippled WebSocket server * * @api public */ Server.prototype.disconnect = function() { var self = this; if (!this._connected) { this.once('socket_open', function() { self.disconnect(); }); return; } //these need to be reset so that updateScore //and checkActivity do not trigger reconnect this._lastLedgerIndex = NaN; this._lastLedgerClose = NaN; this._score = 0; this._shouldConnect = false; this._setState('offline'); if (this._ws) { this._ws.close(); } }; /** * Reconnect to rippled WebSocket server * * @api public */ Server.prototype.reconnect = function() { var self = this; function reconnect() { self._shouldConnect = true; self._retry = 0; self.connect(); }; if (this._ws && this._shouldConnect) { if (this.isConnected()) { this.once('disconnect', reconnect); this.disconnect(); } else { reconnect(); } } }; /** * Connect to rippled WebSocket server and subscribe to events that are * internally requisite. Automatically retry connections with a gradual * back-off * * @api public */ Server.prototype.connect = function() { var self = this; var WebSocket = Server.websocketConstructor(); if (!WebSocket) { throw new Error('No websocket support detected!'); } // We don't connect if we believe we're already connected. This means we have // recently received a message from the server and the WebSocket has not // reported any issues either. If we do fail to ping or the connection drops, // we will automatically reconnect. if (this._connected) { return; } // Ensure any existing socket is given the command to close first. if (this._ws) { this._ws.close(); } if (this._remote.trace) { log.info('connect:', this._opts.url, this._hostid); } var ws = this._ws = new WebSocket(this._opts.url); this._shouldConnect = true; self.emit('connecting'); ws.onmessage = function onMessage(msg) { self.emit('message', msg.data); }; ws.onopen = function onOpen() { if (ws === self._ws) { self.emit('socket_open'); // Subscribe to events self._request(self._remote._serverPrepareSubscribe()); } }; ws.onerror = function onError(e) { if (ws === self._ws) { self.emit('socket_error'); if (self._remote.trace) { log.info('onerror:', self._opts.url, self._hostid, e.data || e); } // Most connection errors for WebSockets are conveyed as 'close' events with // code 1006. This is done for security purposes and therefore unlikely to // ever change. // This means that this handler is hardly ever called in practice. If it is, // it probably means the server's WebSocket implementation is corrupt, or // the connection is somehow producing corrupt data. // Most WebSocket applications simply log and ignore this error. Once we // support for multiple servers, we may consider doing something like // lowering this server's quality score. // However, in Node.js this event may be triggered instead of the close // event, so we need to handle it. self._handleClose(); } }; ws.onclose = function onClose() { if (ws === self._ws) { if (self._remote.trace) { log.info('onclose:', self._opts.url, self._hostid, ws.readyState); } self._handleClose(); } }; }; /** * Retry connection to rippled server * * @api private */ Server.prototype._retryConnect = function() { var self = this; this._retry += 1; var retryTimeout = (this._retry < 40) // First, for 2 seconds: 20 times per second ? (1000 / 20) : (this._retry < 40 + 60) // Then, for 1 minute: once per second ? (1000) : (this._retry < 40 + 60 + 60) // Then, for 10 minutes: once every 10 seconds ? (10 * 1000) // Then: once every 30 seconds : (30 * 1000); function connectionRetry() { if (self._shouldConnect) { if (self._remote.trace) { log.info('retry', self._opts.url, self._hostid); } self.connect(); } }; this._retryTimer = setTimeout(connectionRetry, retryTimeout); }; /** * Handle connection closes * * @api private */ Server.prototype._handleClose = function() { var self = this; var ws = this._ws; function noOp(){}; // Prevent additional events from this socket ws.onopen = ws.onerror = ws.onclose = ws.onmessage = noOp; this.emit('socket_close'); this._setState('offline'); if (this._shouldConnect) { this._retryConnect(); } }; /** * Handle incoming messages from rippled WebSocket server * * @param {JSON-parseable} message * @api private */ Server.prototype._handleMessage = function(message) { var self = this; try { message = JSON.parse(message); } catch(e) { } if (!Server.isValidMessage(message)) { this.emit('unexpected', message); return; } switch (message.type) { case 'ledgerClosed': this._handleLedgerClosed(message); break; case 'serverStatus': this._handleServerStatus(message); break; case 'response': this._handleResponse(message); break; case 'path_find': this._handlePathFind(message); break; } }; Server.prototype._handleLedgerClosed = function(message) { this._lastLedgerIndex = message.ledger_index; this._lastLedgerClose = Date.now(); this.emit('ledger_closed', message); }; Server.prototype._handleServerStatus = function(message) { // This message is only received when online. // As we are connected, it is the definitive final state. var isOnline = ~Server.onlineStates.indexOf(message.server_status); this._setState(isOnline ? 'online' : 'offline'); if (!Server.isLoadStatus(message)) { return; } this.emit('load', message, this); this._remote.emit('load', message, this); var loadChanged = message.load_base !== this._load_base || message.load_factor !== this._load_factor if (loadChanged) { this._load_base = message.load_base; this._load_factor = message.load_factor; this.emit('load_changed', message, this); this._remote.emit('load_changed', message, this); } }; Server.prototype._handleResponse = function(message) { // A response to a request. var request = this._requests[message.id]; delete this._requests[message.id]; if (!request) { if (this._remote.trace) { log.info('UNEXPECTED:', this._opts.url, this._hostid, message); } return; } if (message.status === 'success') { if (this._remote.trace) { log.info('response:', this._opts.url, this._hostid, message); } var command = request.message.command; var result = message.result; var responseEvent = 'response_' + command; request.emit('success', result); [ this, this._remote ].forEach(function(emitter) { emitter.emit(responseEvent, result, request, message); }); } else if (message.error) { if (this._remote.trace) { log.info('error:', this._opts.url, this._hostid, message); } var error = { error: 'remoteError', error_message: 'Remote reported an error.', remote: message }; request.emit('error', error); } }; Server.prototype._handlePathFind = function(message) { if (this._remote.trace) { log.info('path_find:', this._opts.url, this._hostid, message); } }; /** * Handle subscription response messages. Subscription response * messages indicate that a connection to the server is ready * * @api private */ Server.prototype._handleResponseSubscribe = function(message) { if (~(Server.onlineStates.indexOf(message.server_status))) { this._setState('online'); } if (Server.isLoadStatus(message)) { this._load_base = message.load_base || 256; this._load_factor = message.load_factor || 256; this._fee_ref = message.fee_ref; this._fee_base = message.fee_base; this._reserve_base = message.reserve_base; this._reserve_inc = message.reserve_inc; } }; /** * Check that received message from rippled is valid * * @api private */ Server.isValidMessage = function(message) { return (typeof message === 'object') && (typeof message.type === 'string'); }; /** * Check that received serverStatus message contains * load status information * * @api private */ Server.isLoadStatus = function(message) { return (typeof message.load_base === 'number') && (typeof message.load_factor === 'number'); }; /** * Send JSON message to rippled WebSocket server * * @param {JSON-Stringifiable} message * @api private */ Server.prototype._sendMessage = function(message) { if (this._ws) { if (this._remote.trace) { log.info('request:', this._opts.url, this._hostid, message); } this._ws.send(JSON.stringify(message)); } }; /** * Submit a Request object. * * Requests are indexed by message ID, which is repeated * in the response from rippled WebSocket server * * @param {Request} request * @api private */ Server.prototype._request = function(request) { var self = this; // Only bother if we are still connected. if (!this._ws) { if (this._remote.trace) { log.info('request: DROPPING:', self._opts.url, self._hostid, request.message); } return; } request.server = this; request.message.id = this._id; request.time = Date.now(); this._requests[request.message.id] = request; // Advance message ID this._id++; function sendRequest() { self._sendMessage(request.message); }; var isOpen = this._ws.readyState === 1; var isSubscribeRequest = request && request.message.command === 'subscribe'; if (this.isConnected() || (isOpen && isSubscribeRequest)) { sendRequest(); } else { this.once('connect', sendRequest); } }; Server.prototype.isConnected = Server.prototype._isConnected = function() { return this._connected; }; /** * Calculate transaction fee * * @param {Transaction|Number} Fee units for a provided transaction * @return {Number} Final fee in XRP for specified number of fee units * @api private */ Server.prototype._computeFee = function(transaction) { var units; if (transaction instanceof Transaction) { units = transaction._getFeeUnits(); } else if (typeof transaction === 'number') { units = transaction; } else { throw new Error('Invalid argument'); } return this._feeTx(units).to_json(); }; /** * Calculate a transaction fee for a number of tx fee units. * * This takes into account the last known network and local load fees. * * @param {Number} Fee units for a provided transaction * @return {Amount} Final fee in XRP for specified number of fee units. */ Server.prototype._feeTx = function(units) { var fee_unit = this._feeTxUnit(); return Amount.from_json(String(Math.ceil(units * fee_unit))); }; /** * Get the current recommended transaction fee unit. * * Multiply this value with the number of fee units in order to calculate the * recommended fee for the transaction you are trying to submit. * * @return {Number} Recommended amount for one fee unit as float. */ Server.prototype._feeTxUnit = function() { var fee_unit = this._fee_base / this._fee_ref; // Apply load fees fee_unit *= this._load_factor / this._load_base; // Apply fee cushion (a safety margin in case fees rise since we were last updated) fee_unit *= this._fee_cushion; return fee_unit; }; /** * Get the current recommended reserve base. * * Returns the base reserve with load fees and safety margin applied. */ Server.prototype._reserve = function(ownerCount) { var reserve_base = Amount.from_json(String(this._reserve_base)); var reserve_inc = Amount.from_json(String(this._reserve_inc)); var owner_count = ownerCount || 0; if (owner_count < 0) { throw new Error('Owner count must not be negative.'); } return reserve_base.add(reserve_inc.product_human(owner_count)); }; exports.Server = Server; // vim:sw=2:sts=2:ts=8:et
src/js/ripple/server.js
var util = require('util'); var url = require('url'); var EventEmitter = require('events').EventEmitter; var Amount = require('./amount').Amount; var Transaction = require('./transaction').Transaction; var log = require('./log').internal.sub('server'); /** * @constructor Server * * @param {Remote} Reference to a Remote object * @param {Object} Options * @param {String} host * @param {Number|String} port * @param [Boolean] securec */ function Server(remote, opts) { EventEmitter.call(this); var self = this; if (typeof opts === 'string') { var parsedUrl = url.parse(opts); opts = { host: parsedUrl.hostname, port: parsedUrl.port, secure: (parsedUrl.protocol === 'ws:') ? false : true }; } if (typeof opts !== 'object') { throw new TypeError('Server configuration is not an Object'); } if (!Server.domainRE.test(opts.host)) { throw new Error('Server host is malformed, use "host" and "port" server configuration'); } // We want to allow integer strings as valid port numbers for backward compatibility if (!(opts.port = Number(opts.port))) { throw new TypeError('Server port must be a number'); } if (opts.port < 1 || opts.port > 65535) { throw new TypeError('Server "port" must be an integer in range 1-65535'); } if (typeof opts.secure !== 'boolean') { opts.secure = true; } this._remote = remote; this._opts = opts; this._ws = void(0); this._connected = false; this._shouldConnect = false; this._state = 'offline'; this._id = 0; this._retry = 0; this._requests = { }; this._load_base = 256; this._load_factor = 256; this._fee = 10; this._fee_ref = 10; this._fee_base = 10; this._reserve_base = void(0); this._reserve_inc = void(0); this._fee_cushion = this._remote.fee_cushion; this._lastLedgerIndex = NaN; this._lastLedgerClose = NaN; this._score = 0; this._scoreWeights = { ledgerclose: 5, response: 1 }; this._url = this._opts.url = (this._opts.secure ? 'wss://' : 'ws://') + this._opts.host + ':' + this._opts.port; this._hostid = ''; function onMessage(message) { self._handleMessage(message); }; this.on('message', onMessage); function onSubscribeResponse(message) { self._handleResponseSubscribe(message); }; this.on('response_subscribe', onSubscribeResponse); function setActivityInterval() { var interval = self._checkActivity.bind(self); self._activityInterval = setInterval(interval, 1000); }; this.on('disconnect', function onDisconnect() { clearInterval(self._activityInterval); self.once('ledger_closed', setActivityInterval); }); this.once('ledger_closed', setActivityInterval); this._remote.on('ledger_closed', function(ledger) { self._updateScore('ledgerclose', ledger); }); this.on('response_ping', function(message, request) { self._updateScore('response', request); }); this.on('load_changed', function(load) { self._updateScore('loadchange', load); }); this.on('response_server_info', function(message) { try { self._hostid = '(' + message.info.pubkey_node + ')'; } catch (e) { } }); this.on('connect', function() { self._request(self._remote.requestServerInfo()); }); }; util.inherits(Server, EventEmitter); Server.domainRE = /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|[-_]){0,61}[0-9A-Za-z])?)*\.?$/; /** * Server states that we will treat as the server being online. * * Our requirements are that the server can process transactions and notify * us of changes. */ Server.onlineStates = [ 'syncing', 'tracking', 'proposing', 'validating', 'full' ]; /** * This is the final interface between client code and a socket connection to a * `rippled` server. As such, this is a decent hook point to allow a WebSocket * interface conforming object to be used as a basis to mock rippled. This * avoids the need to bind a websocket server to a port and allows a more * synchronous style of code to represent a client <-> server message sequence. * We can also use this to log a message sequence to a buffer. * * @api private */ Server.websocketConstructor = function() { // We require this late, because websocket shims may be loaded after // ripple-lib in the browser return require('ws'); }; /** * Set server state * * @param {String} state * @api private */ Server.prototype._setState = function(state) { if (state !== this._state) { if (this._remote.trace) { log.info('set_state:', this._opts.url, this._hostid, state); } this._state = state; this.emit('state', state); switch (state) { case 'online': this._connected = true; this._retry = 0; this.emit('connect'); break; case 'offline': this._connected = false; this.emit('disconnect'); break; } } }; /** * Check that server is still active. * * Server activity is determined by ledger_closed events. * Maximum delay to receive a ledger_closed event is 20s. * * If server is inactive, reconnect * * @api private */ Server.prototype._checkActivity = function() { if (!this._connected) { return; } if (isNaN(this._lastLedgerClose)) { return; } var delta = (Date.now() - this._lastLedgerClose); if (delta > (1000 * 25)) { this.reconnect(); } }; /** * Server maintains a score for request prioritization. * * The score is determined by various data including * this server's lag to receive ledger_closed events, * ping response time, and load(fee) change * * @param {String} type * @param {Object} data * @api private */ Server.prototype._updateScore = function(type, data) { if (!this._connected) { return; } var weight = this._scoreWeights[type] || 1; switch (type) { case 'ledgerclose': // Ledger lag var delta = data.ledger_index - this._lastLedgerIndex; if (delta > 0) { this._score += weight * delta; } break; case 'response': // Ping lag var delta = Math.floor((Date.now() - data.time) / 200); this._score += weight * delta; break; case 'loadchange': // Load/fee change this._fee = Number(this._computeFee(10)); break; } if (this._score > 1e3) { this.reconnect(); } }; /** * Get the server's remote address * * Incompatible with ripple-lib client build */ Server.prototype.getRemoteAddress = Server.prototype._remoteAddress = function() { var address; try { address = this._ws._socket.remoteAddress; } catch (e) { } return address; }; /** * Get the server's hostid */ Server.prototype.getHostID = function() { return this._hostid; }; /** * Disconnect from rippled WebSocket server * * @api public */ Server.prototype.disconnect = function() { var self = this; if (!this._connected) { this.once('socket_open', function() { self.disconnect(); }); return; } //these need to be reset so that updateScore //and checkActivity do not trigger reconnect this._lastLedgerIndex = NaN; this._lastLedgerClose = NaN; this._score = 0; this._shouldConnect = false; this._setState('offline'); if (this._ws) { this._ws.close(); } }; /** * Reconnect to rippled WebSocket server * * @api public */ Server.prototype.reconnect = function() { var self = this; function reconnect() { self._shouldConnect = true; self._retry = 0; self.connect(); }; if (this._ws && this._shouldConnect) { if (this.isConnected()) { this.once('disconnect', reconnect); this.disconnect(); } else { reconnect(); } } }; /** * Connect to rippled WebSocket server and subscribe to events that are * internally requisite. Automatically retry connections with a gradual * back-off * * @api public */ Server.prototype.connect = function() { var self = this; var WebSocket = Server.websocketConstructor(); if (!WebSocket) { throw new Error('No websocket support detected!'); } // We don't connect if we believe we're already connected. This means we have // recently received a message from the server and the WebSocket has not // reported any issues either. If we do fail to ping or the connection drops, // we will automatically reconnect. if (this._connected) { return; } // Ensure any existing socket is given the command to close first. if (this._ws) { this._ws.close(); } if (this._remote.trace) { log.info('connect:', this._opts.url, this._hostid); } var ws = this._ws = new WebSocket(this._opts.url); this._shouldConnect = true; self.emit('connecting'); ws.onmessage = function onMessage(msg) { self.emit('message', msg.data); }; ws.onopen = function onOpen() { if (ws === self._ws) { self.emit('socket_open'); // Subscribe to events self._request(self._remote._serverPrepareSubscribe()); } }; ws.onerror = function onError(e) { if (ws === self._ws) { self.emit('socket_error'); if (self._remote.trace) { log.info('onerror:', self._opts.url, self._hostid, e.data || e); } // Most connection errors for WebSockets are conveyed as 'close' events with // code 1006. This is done for security purposes and therefore unlikely to // ever change. // This means that this handler is hardly ever called in practice. If it is, // it probably means the server's WebSocket implementation is corrupt, or // the connection is somehow producing corrupt data. // Most WebSocket applications simply log and ignore this error. Once we // support for multiple servers, we may consider doing something like // lowering this server's quality score. // However, in Node.js this event may be triggered instead of the close // event, so we need to handle it. self._handleClose(); } }; ws.onclose = function onClose() { if (ws === self._ws) { if (self._remote.trace) { log.info('onclose:', self._opts.url, self._hostid, ws.readyState); } self._handleClose(); } }; }; /** * Retry connection to rippled server * * @api private */ Server.prototype._retryConnect = function() { var self = this; this._retry += 1; var retryTimeout = (this._retry < 40) // First, for 2 seconds: 20 times per second ? (1000 / 20) : (this._retry < 40 + 60) // Then, for 1 minute: once per second ? (1000) : (this._retry < 40 + 60 + 60) // Then, for 10 minutes: once every 10 seconds ? (10 * 1000) // Then: once every 30 seconds : (30 * 1000); function connectionRetry() { if (self._shouldConnect) { if (self._remote.trace) { log.info('retry', self._opts.url, self._hostid); } self.connect(); } }; this._retryTimer = setTimeout(connectionRetry, retryTimeout); }; /** * Handle connection closes * * @api private */ Server.prototype._handleClose = function() { var self = this; var ws = this._ws; function noOp(){}; // Prevent additional events from this socket ws.onopen = ws.onerror = ws.onclose = ws.onmessage = noOp; this.emit('socket_close'); this._setState('offline'); if (this._shouldConnect) { this._retryConnect(); } }; /** * Handle incoming messages from rippled WebSocket server * * @param {JSON-parseable} message * @api private */ Server.prototype._handleMessage = function(message) { var self = this; try { message = JSON.parse(message); } catch(e) { } if (!Server.isValidMessage(message)) { this.emit('unexpected', message); return; } switch (message.type) { case 'ledgerClosed': this._handleLedgerClosed(message); break; case 'serverStatus': this._handleServerStatus(message); break; case 'response': this._handleResponse(message); break; case 'path_find': this._handlePathFind(message); break; } }; Server.prototype._handleLedgerClosed = function(message) { this._lastLedgerIndex = message.ledger_index; this._lastLedgerClose = Date.now(); this.emit('ledger_closed', message); }; Server.prototype._handleServerStatus = function(message) { // This message is only received when online. // As we are connected, it is the definitive final state. var isOnline = ~Server.onlineStates.indexOf(message.server_status); this._setState(isOnline ? 'online' : 'offline'); if (!Server.isLoadStatus(message)) { return; } this.emit('load', message, this); this._remote.emit('load', message, this); var loadChanged = message.load_base !== this._load_base || message.load_factor !== this._load_factor if (loadChanged) { this._load_base = message.load_base; this._load_factor = message.load_factor; this.emit('load_changed', message, this); this._remote.emit('load_changed', message, this); } }; Server.prototype._handleResponse = function(message) { // A response to a request. var request = this._requests[message.id]; delete this._requests[message.id]; if (!request) { if (this._remote.trace) { log.info('UNEXPECTED:', this._opts.url, this._hostid, message); } return; } if (message.status === 'success') { if (this._remote.trace) { log.info('response:', this._opts.url, this._hostid, message); } var command = request.message.command; var result = message.result; var responseEvent = 'response_' + command; request.emit('success', result); [ this, this._remote ].forEach(function(emitter) { emitter.emit(responseEvent, result, request, message); }); } else if (message.error) { if (this._remote.trace) { log.info('error:', this._opts.url, this._hostid, message); } var error = { error: 'remoteError', error_message: 'Remote reported an error.', remote: message }; request.emit('error', error); } }; Server.prototype._handlePathFind = function(message) { if (this._remote.trace) { log.info('path_find:', this._opts.url, this._hostid, message); } }; /** * Handle subscription response messages. Subscription response * messages indicate that a connection to the server is ready * * @api private */ Server.prototype._handleResponseSubscribe = function(message) { if (~(Server.onlineStates.indexOf(message.server_status))) { this._setState('online'); } if (Server.isLoadStatus(message)) { this._load_base = message.load_base || 256; this._load_factor = message.load_factor || 256; this._fee_ref = message.fee_ref; this._fee_base = message.fee_base; this._reserve_base = message.reserve_base; this._reserve_inc = message.reserve_inc; } }; /** * Check that received message from rippled is valid * * @api private */ Server.isValidMessage = function(message) { return (typeof message === 'object') && (typeof message.type === 'string'); }; /** * Check that received serverStatus message contains * load status information * * @api private */ Server.isLoadStatus = function(message) { return (typeof message.load_base === 'number') && (typeof message.load_factor === 'number'); }; /** * Send JSON message to rippled WebSocket server * * @param {JSON-Stringifiable} message * @api private */ Server.prototype._sendMessage = function(message) { if (this._ws) { if (this._remote.trace) { log.info('request:', this._opts.url, this._hostid, message); } this._ws.send(JSON.stringify(message)); } }; /** * Submit a Request object. * * Requests are indexed by message ID, which is repeated * in the response from rippled WebSocket server * * @param {Request} request * @api private */ Server.prototype._request = function(request) { var self = this; // Only bother if we are still connected. if (!this._ws) { if (this._remote.trace) { log.info('request: DROPPING:', self._opts.url, self._hostid, request.message); } return; } request.server = this; request.message.id = this._id; request.time = Date.now(); this._requests[request.message.id] = request; // Advance message ID this._id++; function sendRequest() { self._sendMessage(request.message); }; var isOpen = this._ws.readyState === 1; var isSubscribeRequest = request && request.message.command === 'subscribe'; if (this.isConnected() || (isOpen && isSubscribeRequest)) { sendRequest(); } else { this.once('connect', sendRequest); } }; Server.prototype.isConnected = Server.prototype._isConnected = function() { return this._connected; }; /** * Calculate transaction fee * * @param {Transaction|Number} Fee units for a provided transaction * @return {Number} Final fee in XRP for specified number of fee units * @api private */ Server.prototype._computeFee = function(transaction) { var units; if (transaction instanceof Transaction) { units = transaction._getFeeUnits(); } else if (typeof transaction === 'number') { units = transaction; } else { throw new Error('Invalid argument'); } return this._feeTx(units).to_json(); }; /** * Calculate a transaction fee for a number of tx fee units. * * This takes into account the last known network and local load fees. * * @param {Number} Fee units for a provided transaction * @return {Amount} Final fee in XRP for specified number of fee units. */ Server.prototype._feeTx = function(units) { var fee_unit = this._feeTxUnit(); return Amount.from_json(String(Math.ceil(units * fee_unit))); }; /** * Get the current recommended transaction fee unit. * * Multiply this value with the number of fee units in order to calculate the * recommended fee for the transaction you are trying to submit. * * @return {Number} Recommended amount for one fee unit as float. */ Server.prototype._feeTxUnit = function() { var fee_unit = this._fee_base / this._fee_ref; // Apply load fees fee_unit *= this._load_factor / this._load_base; // Apply fee cushion (a safety margin in case fees rise since we were last updated) fee_unit *= this._fee_cushion; return fee_unit; }; /** * Get the current recommended reserve base. * * Returns the base reserve with load fees and safety margin applied. */ Server.prototype._reserve = function(ownerCount) { var reserve_base = Amount.from_json(String(this._reserve_base)); var reserve_inc = Amount.from_json(String(this._reserve_inc)); var owner_count = ownerCount || 0; if (owner_count < 0) { throw new Error('Owner count must not be negative.'); } return reserve_base.add(reserve_inc.product_human(owner_count)); }; exports.Server = Server; // vim:sw=2:sts=2:ts=8:et
[CHORE] server: add logging when reconnect is triggered
src/js/ripple/server.js
[CHORE] server: add logging when reconnect is triggered
<ide><path>rc/js/ripple/server.js <ide> var delta = (Date.now() - this._lastLedgerClose); <ide> <ide> if (delta > (1000 * 25)) { <add> log.info('reconnect: activity delta:', delta); <ide> this.reconnect(); <ide> } <ide> }; <ide> } <ide> <ide> if (this._score > 1e3) { <add> log.info('reconnect: score:', this._score); <ide> this.reconnect(); <ide> } <ide> };
JavaScript
mit
0f5ba2cf5457db8f7f7e7aeeebd8d80927babc0a
0
NIEM/movement-frontend,NIEM/movement-frontend
'use strict'; /** * @module dhsniem * * @description * Main module of the application. */ angular .module('dhsniem', [ 'ngAnimate', 'ngCookies', 'ui.router', 'ngSanitize', 'ngTouch', 'ui.bootstrap' ]) .config(function($urlRouterProvider) { $urlRouterProvider.when('', '/'); // redirect to root if the state is '' $urlRouterProvider.otherwise('/'); // redirect to root if state is not found }) .run(function($rootScope, $window) { $rootScope.$on('$stateChangeSuccess', function() { $window.scroll(0,0); }); });
src/app.js
'use strict'; /** * @module dhsniem * * @description * Main module of the application. */ angular .module('dhsniem', [ 'ngAnimate', 'ngCookies', 'ui.router', 'ngSanitize', 'ngTouch', 'ui.bootstrap' ]) .config(function($urlRouterProvider) { $urlRouterProvider.when('', '/'); // redirect to root if the state is '' $urlRouterProvider.otherwise('/'); // redirect to root if state is not found });
DN-250 scroll to top on state change
src/app.js
DN-250 scroll to top on state change
<ide><path>rc/app.js <ide> $urlRouterProvider.when('', '/'); // redirect to root if the state is '' <ide> <ide> $urlRouterProvider.otherwise('/'); // redirect to root if state is not found <add> }) <add> <add> .run(function($rootScope, $window) { <add> $rootScope.$on('$stateChangeSuccess', function() { <add> $window.scroll(0,0); <ide> }); <add>}); <add>
JavaScript
apache-2.0
0e8d51da2400f669871883928d7abe16907a3ccf
0
DrSmugleaf/Banter-Bot,DrSmugleaf/Banter-Bot
// // Copyright (c) 2016-2017 DrSmugleaf // "use strict" module.exports = { clone(object) { if(object == null || typeof object != "object") return object var copy = object.constructor() for(const attribute in object) { if(object.hasOwnProperty(attribute)) copy[attribute] = object[attribute] } return copy }, equals(array, array2) { if(!array || !array2) return false if(array.length !== array2.length) return false for(var i = 0; i < array.length; i++) { if(array[i] instanceof Array && array2[i] instanceof Array) { if(!array[i].equals(array2[i])) return false } else if(array[i] !== array2[i]) return false } return true } }
src/util/arrayutil.js
// // Copyright (c) 2016-2017 DrSmugleaf // "use strict" module.exports = { clone(object) { if(object == null || typeof object != "object") return object var copy = object.constructor() for(const attribute in object) { if(object.hasOwnProperty(attribute)) copy[attribute] = object[attribute] } return copy } }
Added equals to arrayutil
src/util/arrayutil.js
Added equals to arrayutil
<ide><path>rc/util/arrayutil.js <ide> if(object.hasOwnProperty(attribute)) copy[attribute] = object[attribute] <ide> } <ide> return copy <add> }, <add> <add> equals(array, array2) { <add> if(!array || !array2) return false <add> <add> if(array.length !== array2.length) return false <add> <add> for(var i = 0; i < array.length; i++) { <add> if(array[i] instanceof Array && array2[i] instanceof Array) { <add> if(!array[i].equals(array2[i])) return false <add> } else if(array[i] !== array2[i]) return false <add> } <add> <add> return true <ide> } <ide> }
Java
apache-2.0
a414c44ff9c97e330f5ccf982a1eb1cd3c870f52
0
pwoodworth/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,vladmm/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,signed/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,caot/intellij-community,supersven/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,izonder/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,da1z/intellij-community,asedunov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,samthor/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,kdwink/intellij-community,amith01994/intellij-community,hurricup/intellij-community,holmes/intellij-community,retomerz/intellij-community,jexp/idea2,orekyuu/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,jexp/idea2,blademainer/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,jagguli/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,amith01994/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,jexp/idea2,youdonghai/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,consulo/consulo,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,asedunov/intellij-community,samthor/intellij-community,signed/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,supersven/intellij-community,xfournet/intellij-community,signed/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,ernestp/consulo,apixandru/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,dslomov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ryano144/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,signed/intellij-community,ryano144/intellij-community,fitermay/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,kool79/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,slisson/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,asedunov/intellij-community,allotria/intellij-community,amith01994/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,da1z/intellij-community,holmes/intellij-community,apixandru/intellij-community,semonte/intellij-community,Lekanich/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,semonte/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,holmes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,caot/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,dslomov/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,adedayo/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,FHannes/intellij-community,supersven/intellij-community,slisson/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ernestp/consulo,da1z/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,adedayo/intellij-community,allotria/intellij-community,slisson/intellij-community,izonder/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,consulo/consulo,amith01994/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,fnouama/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,FHannes/intellij-community,jexp/idea2,nicolargo/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,xfournet/intellij-community,adedayo/intellij-community,allotria/intellij-community,robovm/robovm-studio,amith01994/intellij-community,allotria/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,vladmm/intellij-community,kool79/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ryano144/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,hurricup/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,ol-loginov/intellij-community,signed/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,caot/intellij-community,FHannes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,semonte/intellij-community,kdwink/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ernestp/consulo,signed/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,clumsy/intellij-community,joewalnes/idea-community,consulo/consulo,diorcety/intellij-community,fitermay/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,caot/intellij-community,FHannes/intellij-community,petteyg/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,joewalnes/idea-community,petteyg/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,da1z/intellij-community,izonder/intellij-community,wreckJ/intellij-community,allotria/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,consulo/consulo,caot/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,hurricup/intellij-community,fnouama/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,holmes/intellij-community,dslomov/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,ibinti/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ryano144/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,supersven/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,caot/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,slisson/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,diorcety/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,samthor/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,allotria/intellij-community,fnouama/intellij-community,ernestp/consulo,apixandru/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,dslomov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,jagguli/intellij-community,consulo/consulo,clumsy/intellij-community,diorcety/intellij-community,clumsy/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,izonder/intellij-community,adedayo/intellij-community,robovm/robovm-studio,slisson/intellij-community,izonder/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,samthor/intellij-community,amith01994/intellij-community,izonder/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,supersven/intellij-community,supersven/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,jagguli/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,adedayo/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,signed/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,slisson/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,semonte/intellij-community,fitermay/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,kool79/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,da1z/intellij-community,izonder/intellij-community,fitermay/intellij-community,da1z/intellij-community,kdwink/intellij-community,apixandru/intellij-community,semonte/intellij-community,supersven/intellij-community,blademainer/intellij-community,xfournet/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ernestp/consulo,ol-loginov/intellij-community,ibinti/intellij-community,kdwink/intellij-community,jexp/idea2,fitermay/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,dslomov/intellij-community,FHannes/intellij-community,slisson/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,caot/intellij-community,samthor/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,blademainer/intellij-community,asedunov/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,caot/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,kool79/intellij-community,signed/intellij-community,caot/intellij-community,robovm/robovm-studio,clumsy/intellij-community,akosyakov/intellij-community,kool79/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ryano144/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,kool79/intellij-community,jexp/idea2,slisson/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,allotria/intellij-community,Distrotech/intellij-community,holmes/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,jexp/idea2,amith01994/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,blademainer/intellij-community,supersven/intellij-community,signed/intellij-community,orekyuu/intellij-community,semonte/intellij-community,fnouama/intellij-community,samthor/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community
/** * @author cdr */ package com.intellij.openapi.editor.actions.moveUpDown; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtil; import com.intellij.lang.ASTNode; class MoveStatementHandler extends EditorWriteActionHandler { private final boolean isDown; private final Mover[] myMovers; public MoveStatementHandler(boolean down) { isDown = down; // order is important myMovers = new Mover[]{new StatementMover(down), new DeclarationMover(down), new LineMover(down)}; } public void executeWriteAction(Editor editor, DataContext dataContext) { final Project project = editor.getProject(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile file = getRoot(documentManager.getPsiFile(document), editor); final Mover mover = getSuitableMover(editor, file); mover.move(editor,file); } public boolean isEnabled(Editor editor, DataContext dataContext) { if (editor.isOneLineMode()) { return false; } final Project project = editor.getProject(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile psiFile = documentManager.getPsiFile(document); PsiFile file = getRoot(psiFile, editor); if (file == null) return false; final Mover mover = getSuitableMover(editor, file); if (mover == null || mover.insertOffset == -1) return false; final int maxLine = editor.offsetToLogicalPosition(editor.getDocument().getTextLength()).line; final LineRange range = mover.whatToMove; if (range.startLine <= 1 && !isDown) return false; return range.endLine < maxLine - 1 || !isDown; } private static PsiFile getRoot(final PsiFile file, final Editor editor) { if (file == null || editor == null) return null; PsiElement leafElement = file.findElementAt(editor.getCaretModel().getOffset()); if (leafElement == null) return null; ASTNode node = leafElement.getNode(); if (node == null) return null; return (PsiFile)PsiUtil.getRoot(node).getPsi(); } private Mover getSuitableMover(final Editor editor, final PsiFile file) { for (final Mover mover : myMovers) { final boolean available = mover.checkAvailable(editor, file); if (available) return mover; } return null; } }
source/com/intellij/openapi/editor/actions/moveUpDown/MoveStatementHandler.java
/** * @author cdr */ package com.intellij.openapi.editor.actions.moveUpDown; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtil; class MoveStatementHandler extends EditorWriteActionHandler { private final boolean isDown; private final Mover[] myMovers; public MoveStatementHandler(boolean down) { isDown = down; // order is important myMovers = new Mover[]{new StatementMover(down), new DeclarationMover(down), new LineMover(down)}; } public void executeWriteAction(Editor editor, DataContext dataContext) { final Project project = editor.getProject(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile file = getRoot(documentManager.getPsiFile(document), editor); final Mover mover = getSuitableMover(editor, file); mover.move(editor,file); } public boolean isEnabled(Editor editor, DataContext dataContext) { if (editor.isOneLineMode()) { return false; } final Project project = editor.getProject(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile psiFile = documentManager.getPsiFile(document); PsiFile file = getRoot(psiFile, editor); if (file == null) return false; final Mover mover = getSuitableMover(editor, file); if (mover == null || mover.insertOffset == -1) return false; final int maxLine = editor.offsetToLogicalPosition(editor.getDocument().getTextLength()).line; final LineRange range = mover.whatToMove; if (range.startLine <= 1 && !isDown) return false; return range.endLine < maxLine - 1 || !isDown; } private static PsiFile getRoot(final PsiFile file, final Editor editor) { if (file == null || editor == null) return null; PsiElement leafElement = file.findElementAt(editor.getCaretModel().getOffset()); if (leafElement == null) return null; return (PsiFile)PsiUtil.getRoot(leafElement.getNode()).getPsi(); } private Mover getSuitableMover(final Editor editor, final PsiFile file) { for (final Mover mover : myMovers) { final boolean available = mover.checkAvailable(editor, file); if (available) return mover; } return null; } }
IDEADEV-6645
source/com/intellij/openapi/editor/actions/moveUpDown/MoveStatementHandler.java
IDEADEV-6645
<ide><path>ource/com/intellij/openapi/editor/actions/moveUpDown/MoveStatementHandler.java <ide> import com.intellij.psi.PsiElement; <ide> import com.intellij.psi.PsiFile; <ide> import com.intellij.psi.util.PsiUtil; <add>import com.intellij.lang.ASTNode; <ide> <ide> class MoveStatementHandler extends EditorWriteActionHandler { <ide> private final boolean isDown; <ide> if (file == null || editor == null) return null; <ide> PsiElement leafElement = file.findElementAt(editor.getCaretModel().getOffset()); <ide> if (leafElement == null) return null; <del> return (PsiFile)PsiUtil.getRoot(leafElement.getNode()).getPsi(); <add> ASTNode node = leafElement.getNode(); <add> if (node == null) return null; <add> return (PsiFile)PsiUtil.getRoot(node).getPsi(); <ide> } <ide> <ide> private Mover getSuitableMover(final Editor editor, final PsiFile file) {
JavaScript
mit
c28161476868d70d18dad5dcf389ba37ea3a1f60
0
Honko/honko-damagecalc,MagiaSN/honko-damagecalc,GrievingTrauer/German-Showdown-Calc,Honko/honko-damagecalc,GrievingTrauer/German-Showdown-Calc,Ununhexium20/honko-damagecalc,Honko/honko-damagecalc,sobolews/honko-damagecalc,AustinXII/honko-damagecalc,AustinXII/honko-damagecalc,Zarel/honko-damagecalc,sobolews/honko-damagecalc,Zarel/honko-damagecalc,charizard8888/1v1calc,MagiaSN/honko-damagecalc,fsibapt/fsibapt.github.io,bmeduho/honko-damagecalc,Ununhexium20/honko-damagecalc,charizard8888/1v1calc,MagiaSN/honko-damagecalc,bmeduho/honko-damagecalc,xfix/gamut-was-taken.github.io,Zarel/honko-damagecalc,fsibapt/fsibapt.github.io
$.fn.DataTable.ColVis.prototype._fnDomColumnButton = function(i) { var that = this, column = this.s.dt.aoColumns[i], dt = this.s.dt; var title = this.s.fnLabel === null ? column.sTitle : this.s.fnLabel(i, column.sTitle, column.nTh); return $( '<li ' + (dt.bJUI ? 'class="ui-button ui-state-default"' : '') + '>' + '<label>' + '<input type="checkbox" />' + '<span>' + title + '</span>' + '</label>' + '</li>' ) .click(function(e) { var showHide = !$('input', this).is(":checked"); if (e.target.nodeName.toLowerCase() !== "li") { showHide = !showHide; } /* Need to consider the case where the initialiser created more than one table - change the * API index that DataTables is using */ var oldIndex = $.fn.dataTableExt.iApiIndex; $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that); // Optimisation for server-side processing when scrolling - don't do a full redraw if (dt.oFeatures.bServerSide) { that.s.dt.oInstance.fnSetColumnVis(i, showHide, false); that.s.dt.oInstance.fnAdjustColumnSizing(false); if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "") { that.s.dt.oInstance.oApi._fnScrollDraw(that.s.dt); } that._fnDrawCallback(); } else { that.s.dt.oInstance.fnSetColumnVis(i, showHide); } $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */ if ( (e.target.nodeName.toLowerCase() === 'input' || e.target.nodeName.toLowerCase() === 'li') && that.s.fnStateChange !== null ) { that.s.fnStateChange.call(that, i, showHide); } })[0]; }; $.fn.dataTableExt.oSort['damage-pre'] = parseFloat; function calculate() { var attacker, defender, setName, setTier; var selectedTiers = getSelectedTiers(); var setOptions = getSetOptions(); var dataSet = []; for (var i = 0; i < setOptions.length; i++) { if (setOptions[i].id && typeof setOptions[i].id !== "undefined") { setName = setOptions[i].id.substring(setOptions[i].id.indexOf("(") + 1, setOptions[i].id.lastIndexOf(")")); setTier = setName.substring(0, setName.indexOf(" ")); if (_.contains(selectedTiers, setTier)) { attacker = (mode === "one-vs-all") ? new Pokemon($("#p1")) : new Pokemon(setOptions[i].id); defender = (mode === "one-vs-all") ? new Pokemon(setOptions[i].id) : new Pokemon($("#p1")); var field = new Field(); var damageResults = calculateMovesOfAttacker(attacker, defender, field); var result, minDamage, maxDamage, minPercent, maxPercent; var defenderSide = field.getSide( ~~(mode === "one-vs-all") ); var highestMaxPercent = -1; var data = [ setOptions[i].id, (mode === "one-vs-all") ? defender.type1 : attacker.type1, (mode === "one-vs-all") ? defender.type2 : attacker.type2, (mode === "one-vs-all") ? defender.ability : attacker.ability, (mode === "one-vs-all") ? defender.item : attacker.item ]; for (var n = 0; n < 4; n++) { result = damageResults[n]; minDamage = result.damage[0] * attacker.moves[n].hits; maxDamage = result.damage[result.damage.length-1] * attacker.moves[n].hits; minPercent = Math.floor(minDamage * 1000 / defender.maxHP) / 10; maxPercent = Math.floor(maxDamage * 1000 / defender.maxHP) / 10; result.koChanceText = attacker.moves[n].bp === 0 ? 'nice move' : getKOChanceText(result.damage, defender, defenderSide, attacker.moves[n].hits, attacker.ability === 'Bad Dreams'); if (maxPercent > highestMaxPercent) { highestMaxPercent = maxPercent; while (data.length > 5) { data.pop(); } data.push( attacker.moves[n].name.replace("Hidden Power", "HP") ); data.push( minPercent + " - " + maxPercent + "%" ); data.push( result.koChanceText ); } else if (maxPercent === highestMaxPercent) { data[5] += (attacker.moves[n].name === "(No Move)") ? "" : " & " + attacker.moves[n].name.replace("Hidden Power", "HP"); } } dataSet.push(data); } } } table.clear(); table.rows.add(dataSet).draw(); } function getSelectedTiers() { var selectedTiers = $('.tiers input:checked').map(function () { return this.id; }).get(); return selectedTiers; } var calculateMovesOfAttacker; $(".gen").change(function () { $(".tiers input").prop("checked", false); $("#singles-format").attr("disabled", false); switch(gen) { case 1: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_RBY; break; case 2: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_GSC; break; case 3: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_ADV; break; case 4: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_DPP; break; default: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_BW; break; } adjustTierBorderRadius(); if ( $.fn.DataTable.isDataTable("#holder-2") ) { table.clear(); constructDataTable(); var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>"; $("#holder-2_wrapper").prepend(honkalculator); var dtHeadTop = $(".sorting").offset().top; var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top; var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 ); var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2; $(".bs-btn").css({ "top": buttonOffset }); $(".bs-btn").click(function() { calculate(); }); } }); function adjustTierBorderRadius() { var squaredLeftCorner = { "border-top-left-radius": 0, "border-bottom-left-radius": 0 }; var roundedLeftCorner = { "border-top-left-radius": "8px", "border-bottom-left-radius": "8px" }; if (gen <= 2) { $("#UU").next("label").css(roundedLeftCorner); } else { $("#UU").next("label").css(squaredLeftCorner); $("#NU").next("label").css(roundedLeftCorner); if (gen > 3) { $("#NU").next("label").css(squaredLeftCorner); $("#LC").next("label").css(roundedLeftCorner); if (gen > 4) { $("#LC").next("label").css(squaredLeftCorner); $("#Doubles").next("label").css(roundedLeftCorner); if (gen > 5) { $("#Doubles").next("label").css(squaredLeftCorner); } } } } } $(".mode").change(function() { if ( $("#one-vs-one").prop("checked") ) { window.location.replace( "index.html" ); } else { window.location.replace( "calc_bc.html?mode=" + $(this).attr("id") ); } }); $(".tiers label").mouseup(function() { var oldID = $('.tiers input:checked').attr("id"); var newID = $(this).attr("for"); if ((oldID === "Doubles" || oldID === "VGC14") && (newID !== oldID)) { $("#singles-format").attr("disabled", false); $("#singles-format").prop("checked", true); } if ((oldID === "VGC14" || oldID === "LC") && (newID !== "VGC14" && newID !== "LC")) { $('.level').val("100"); $('.level').keyup(); $('.level').popover({ content: "Level has been reset to 100", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 3000); } }); $(".tiers input").change(function() { var type = $(this).attr("type"); var id = $(this).attr("id"); $(".tiers input").not(":" + type).prop("checked", false); // deselect all radios if a checkbox is checked, and vice-versa if (gen === 1 && $("#OU").prop("checked")) { $("#UU").prop("checked", true); } if (id === "Doubles" || id === "VGC14") { $("#doubles-format").prop("checked", true); $("#singles-format").attr("disabled", true); } if (id === "LC" && $('.level').val() !== "5") { $('.level').val("5"); $('.level').popover({ content: "Level has been set to 5", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } if (id === "VGC14" && $('.level').val() !== "50") { $('.level').val("50"); $('.level').popover({ content: "Level has been set to 50", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } }); $(".set-selector").change(function() { var selectedTier = getSelectedTiers()[0]; if (selectedTier === "LC" && $('.level').val() !== "5") { $('.level').val("5"); $('.level').popover({ content: "Level has been set to 5", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } if (selectedTier === "VGC14" && $('.level').val() !== "50") { $('.level').val("50"); $('.level').popover({ content: "Level has been set to 50", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } }); var table; function constructDataTable() { var dtWidth = $(window).width() - $("#holder-2").offset().left; dtWidth -= 2 * parseFloat($(".holder-0").css("padding-right")); table = $("#holder-2").DataTable( { destroy: true, columnDefs: [ { targets: (gen > 2) ? [] : (gen === 2) ? [3] : [3, 4], visible: false, searchable: false }, { targets: [6], type: 'damage' } ], dom: 'C<"clear">frtiS', colVis: { exclude: (gen > 2) ? [0, 5, 6] : (gen === 2) ? [0, 3, 5, 6] : [0, 3, 4, 5, 6], stateChange: function(iColumn, bVisible) { var column = table.settings()[0].aoColumns[iColumn]; if (column.bSearchable !== bVisible) { column.bSearchable = bVisible; table.rows().invalidate(); } } }, scrollX: dtWidth, scrollY: dtHeight, scrollCollapse: true } ); $(".dataTables_wrapper").width(dtWidth); } function getBottomOffset(obj) { return obj.offset().top + obj.outerHeight(); } var mode, dtHeight; $(document).ready(function() { var url = window.location.href; mode = url.substring(url.indexOf('=') + 1, url.length); $("#" + mode).prop("checked", true); $("#holder-2 th:first").text( (mode === "one-vs-all") ? "Defender" : "Attacker" ); $("#holder-2").show(); setDTHeight(); constructDataTable(); var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>"; $("#holder-2_wrapper").prepend(honkalculator); var dtHeadTop = $(".sorting").offset().top; var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top; var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 ); var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2; $(".bs-btn").css({ "top": buttonOffset }); $(".bs-btn").click(function() { calculate(); }); }); function setDTHeight() { $("#holder-2").DataTable( { dom: 'C<"clear">frti' }); var theadBottomOffset = getBottomOffset($(".sorting")); var heightUnderDT = getBottomOffset($(".holder-0")) - getBottomOffset($("#holder-2 tbody")); dtHeight = $(document).height() - theadBottomOffset - heightUnderDT; }
js/calc_bc.js
$.fn.DataTable.ColVis.prototype._fnDomColumnButton = function(i) { var that = this, column = this.s.dt.aoColumns[i], dt = this.s.dt; var title = this.s.fnLabel === null ? column.sTitle : this.s.fnLabel(i, column.sTitle, column.nTh); return $( '<li ' + (dt.bJUI ? 'class="ui-button ui-state-default"' : '') + '>' + '<label>' + '<input type="checkbox" />' + '<span>' + title + '</span>' + '</label>' + '</li>' ) .click(function(e) { var showHide = !$('input', this).is(":checked"); if (e.target.nodeName.toLowerCase() !== "li") { showHide = !showHide; } /* Need to consider the case where the initialiser created more than one table - change the * API index that DataTables is using */ var oldIndex = $.fn.dataTableExt.iApiIndex; $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that); // Optimisation for server-side processing when scrolling - don't do a full redraw if (dt.oFeatures.bServerSide) { that.s.dt.oInstance.fnSetColumnVis(i, showHide, false); that.s.dt.oInstance.fnAdjustColumnSizing(false); if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "") { that.s.dt.oInstance.oApi._fnScrollDraw(that.s.dt); } that._fnDrawCallback(); } else { that.s.dt.oInstance.fnSetColumnVis(i, showHide); } $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */ if ( (e.target.nodeName.toLowerCase() === 'input' || e.target.nodeName.toLowerCase() === 'li') && that.s.fnStateChange !== null ) { that.s.fnStateChange.call(that, i, showHide); } })[0]; }; function calculate() { var attacker, defender, setName, setTier; var selectedTiers = getSelectedTiers(); var setOptions = getSetOptions(); var dataSet = []; for (var i = 0; i < setOptions.length; i++) { if (setOptions[i].id && typeof setOptions[i].id !== "undefined") { setName = setOptions[i].id.substring(setOptions[i].id.indexOf("(") + 1, setOptions[i].id.lastIndexOf(")")); setTier = setName.substring(0, setName.indexOf(" ")); if (_.contains(selectedTiers, setTier)) { attacker = (mode === "one-vs-all") ? new Pokemon($("#p1")) : new Pokemon(setOptions[i].id); defender = (mode === "one-vs-all") ? new Pokemon(setOptions[i].id) : new Pokemon($("#p1")); var field = new Field(); var damageResults = calculateMovesOfAttacker(attacker, defender, field); var result, minDamage, maxDamage, minPercent, maxPercent; var defenderSide = field.getSide( ~~(mode === "one-vs-all") ); var highestMaxPercent = -1; var data = [ setOptions[i].id, (mode === "one-vs-all") ? defender.type1 : attacker.type1, (mode === "one-vs-all") ? defender.type2 : attacker.type2, (mode === "one-vs-all") ? defender.ability : attacker.ability, (mode === "one-vs-all") ? defender.item : attacker.item ]; for (var n = 0; n < 4; n++) { result = damageResults[n]; minDamage = result.damage[0] * attacker.moves[n].hits; maxDamage = result.damage[result.damage.length-1] * attacker.moves[n].hits; minPercent = Math.floor(minDamage * 1000 / defender.maxHP) / 10; maxPercent = Math.floor(maxDamage * 1000 / defender.maxHP) / 10; result.koChanceText = attacker.moves[n].bp === 0 ? 'nice move' : getKOChanceText(result.damage, defender, defenderSide, attacker.moves[n].hits, attacker.ability === 'Bad Dreams'); if (maxPercent > highestMaxPercent) { highestMaxPercent = maxPercent; while (data.length > 5) { data.pop(); } data.push( attacker.moves[n].name.replace("Hidden Power", "HP") ); data.push( minPercent + " - " + maxPercent + "%" ); data.push( result.koChanceText ); } else if (maxPercent === highestMaxPercent) { data[5] += (attacker.moves[n].name === "(No Move)") ? "" : " & " + attacker.moves[n].name.replace("Hidden Power", "HP"); } } dataSet.push(data); } } } table.clear(); table.rows.add(dataSet).draw(); } function getSelectedTiers() { var selectedTiers = $('.tiers input:checked').map(function () { return this.id; }).get(); return selectedTiers; } var calculateMovesOfAttacker; $(".gen").change(function () { $(".tiers input").prop("checked", false); $("#singles-format").attr("disabled", false); switch(gen) { case 1: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_RBY; break; case 2: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_GSC; break; case 3: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_ADV; break; case 4: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_DPP; break; default: calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_BW; break; } adjustTierBorderRadius(); if ( $.fn.DataTable.isDataTable("#holder-2") ) { table.clear(); constructDataTable(); var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>"; $("#holder-2_wrapper").prepend(honkalculator); var dtHeadTop = $(".sorting").offset().top; var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top; var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 ); var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2; $(".bs-btn").css({ "top": buttonOffset }); $(".bs-btn").click(function() { calculate(); }); } }); function adjustTierBorderRadius() { var squaredLeftCorner = { "border-top-left-radius": 0, "border-bottom-left-radius": 0 }; var roundedLeftCorner = { "border-top-left-radius": "8px", "border-bottom-left-radius": "8px" }; if (gen <= 2) { $("#UU").next("label").css(roundedLeftCorner); } else { $("#UU").next("label").css(squaredLeftCorner); $("#NU").next("label").css(roundedLeftCorner); if (gen > 3) { $("#NU").next("label").css(squaredLeftCorner); $("#LC").next("label").css(roundedLeftCorner); if (gen > 4) { $("#LC").next("label").css(squaredLeftCorner); $("#Doubles").next("label").css(roundedLeftCorner); if (gen > 5) { $("#Doubles").next("label").css(squaredLeftCorner); } } } } } $(".mode").change(function() { if ( $("#one-vs-one").prop("checked") ) { window.location.replace( "index.html" ); } else { window.location.replace( "calc_bc.html?mode=" + $(this).attr("id") ); } }); $(".tiers label").mouseup(function() { var oldID = $('.tiers input:checked').attr("id"); var newID = $(this).attr("for"); if ((oldID === "Doubles" || oldID === "VGC14") && (newID !== oldID)) { $("#singles-format").attr("disabled", false); $("#singles-format").prop("checked", true); } if ((oldID === "VGC14" || oldID === "LC") && (newID !== "VGC14" && newID !== "LC")) { $('.level').val("100"); $('.level').keyup(); $('.level').popover({ content: "Level has been reset to 100", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 3000); } }); $(".tiers input").change(function() { var type = $(this).attr("type"); var id = $(this).attr("id"); $(".tiers input").not(":" + type).prop("checked", false); // deselect all radios if a checkbox is checked, and vice-versa if (gen === 1 && $("#OU").prop("checked")) { $("#UU").prop("checked", true); } if (id === "Doubles" || id === "VGC14") { $("#doubles-format").prop("checked", true); $("#singles-format").attr("disabled", true); } if (id === "LC" && $('.level').val() !== "5") { $('.level').val("5"); $('.level').popover({ content: "Level has been set to 5", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } if (id === "VGC14" && $('.level').val() !== "50") { $('.level').val("50"); $('.level').popover({ content: "Level has been set to 50", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } }); $(".set-selector").change(function() { var selectedTier = getSelectedTiers()[0]; if (selectedTier === "LC" && $('.level').val() !== "5") { $('.level').val("5"); $('.level').popover({ content: "Level has been set to 5", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } if (selectedTier === "VGC14" && $('.level').val() !== "50") { $('.level').val("50"); $('.level').popover({ content: "Level has been set to 50", placement: "right" }).popover('show'); setTimeout(function(){ $('.level').popover('destroy') }, 1350); } }); var table; function constructDataTable() { var dtWidth = $(window).width() - $("#holder-2").offset().left; dtWidth -= 2 * parseFloat($(".holder-0").css("padding-right")); table = $("#holder-2").DataTable( { destroy: true, columnDefs: [ { targets: (gen > 2) ? [] : (gen === 2) ? [3] : [3, 4], visible: false, searchable: false } ], dom: 'C<"clear">frtiS', colVis: { exclude: (gen > 2) ? [0, 5, 6] : (gen === 2) ? [0, 3, 5, 6] : [0, 3, 4, 5, 6], stateChange: function(iColumn, bVisible) { var column = table.settings()[0].aoColumns[iColumn]; if (column.bSearchable !== bVisible) { column.bSearchable = bVisible; table.rows().invalidate(); } } }, scrollX: dtWidth, scrollY: dtHeight, scrollCollapse: true } ); $(".dataTables_wrapper").width(dtWidth); } function getBottomOffset(obj) { return obj.offset().top + obj.outerHeight(); } var mode, dtHeight; $(document).ready(function() { var url = window.location.href; mode = url.substring(url.indexOf('=') + 1, url.length); $("#" + mode).prop("checked", true); $("#holder-2 th:first").text( (mode === "one-vs-all") ? "Defender" : "Attacker" ); $("#holder-2").show(); setDTHeight(); constructDataTable(); var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>"; $("#holder-2_wrapper").prepend(honkalculator); var dtHeadTop = $(".sorting").offset().top; var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top; var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 ); var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2; $(".bs-btn").css({ "top": buttonOffset }); $(".bs-btn").click(function() { calculate(); }); }); function setDTHeight() { $("#holder-2").DataTable( { dom: 'C<"clear">frti' }); var theadBottomOffset = getBottomOffset($(".sorting")); var heightUnderDT = getBottomOffset($(".holder-0")) - getBottomOffset($("#holder-2 tbody")); dtHeight = $(document).height() - theadBottomOffset - heightUnderDT; }
Fix ordering by damage.
js/calc_bc.js
Fix ordering by damage.
<ide><path>s/calc_bc.js <ide> } <ide> })[0]; <ide> }; <add> <add>$.fn.dataTableExt.oSort['damage-pre'] = parseFloat; <ide> <ide> function calculate() { <ide> var attacker, defender, setName, setTier; <ide> targets: (gen > 2) ? [] : (gen === 2) ? [3] : [3, 4], <ide> visible: false, <ide> searchable: false <add> }, <add> { <add> targets: [6], <add> type: 'damage' <ide> } <ide> ], <ide> dom: 'C<"clear">frtiS',
Java
bsd-3-clause
5b4e5b11892482929941524f821c4307e6e07be7
0
EmilHernvall/tregmine,Clunker5/tregmine-2.0,Clunker5/tregmine-2.0,EmilHernvall/tregmine,EmilHernvall/tregmine
package info.tregmine.inventoryspy; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInventoryEvent; import org.bukkit.event.player.PlayerPickupItemEvent; public class SpyPlayerListener implements Listener { private final Main plugin; public SpyPlayerListener(Main instance) { this.plugin = instance; plugin.getServer(); } @EventHandler public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { event.getPlayer().getInventory().clear(); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.getPlayer().sendMessage("error"); event.setCancelled(true); return; } } } @EventHandler public void onInventoryOpen (PlayerInventoryEvent event) { event.getPlayer().sendMessage("INV"); } @EventHandler public void onPlayerDropItem (PlayerDropItemEvent event) { if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.whoDropedItem.put(event.getItemDrop().hashCode(), tregminePlayer.getName()); } @EventHandler public void onPlayerPickupItem (PlayerPickupItemEvent event){ if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (event.getItem().getItemStack().getType() == Material.MOB_SPAWNER) { event.setCancelled(true); return; } if (this.plugin.whoDropedItem.containsKey(event.getItem().hashCode())) { if (event.isCancelled()) { return; } String from = this.plugin.whoDropedItem.get(event.getItem().hashCode()); if (from != null && !event.getPlayer().getName().matches(from)) { info.tregmine.api.TregminePlayer tregminePlayerFrom = this.plugin.tregmine.tregminePlayer.get(from); info.tregmine.api.TregminePlayer tregminePlayerTo = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.log.info (event.getItem().getItemStack().getAmount() + ":" + event.getItem().getItemStack().getType().toString() + " " + tregminePlayerFrom.getChatName() + " ==> " + tregminePlayerTo.getChatName() ); if (!tregminePlayerFrom.getMetaBoolean("invis") && ! tregminePlayerTo.getMetaBoolean("invis")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "You got " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + ChatColor.YELLOW + " from " + tregminePlayerFrom.getChatName() ); this.plugin.getServer().getPlayer(from).sendMessage(ChatColor.YELLOW + "You gave " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + " to " + tregminePlayerTo.getChatName() ); } } this.plugin.whoDropedItem.put(event.getItem().hashCode(), null); } } }
InventorySpy/src/info/tregmine/inventoryspy/SpyPlayerListener.java
package info.tregmine.inventoryspy; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInventoryEvent; import org.bukkit.event.player.PlayerPickupItemEvent; public class SpyPlayerListener implements Listener { private final Main plugin; public SpyPlayerListener(Main instance) { this.plugin = instance; plugin.getServer(); } @EventHandler public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { event.getPlayer().getInventory().clear(); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { event.getPlayer().sendMessage("Interaction faild"); // if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { // event.setCancelled(true); // return; // } } } @EventHandler public void onInventoryOpen (PlayerInventoryEvent event) { event.getPlayer().sendMessage("INV"); } @EventHandler public void onPlayerDropItem (PlayerDropItemEvent event) { if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.whoDropedItem.put(event.getItemDrop().hashCode(), tregminePlayer.getName()); } @EventHandler public void onPlayerPickupItem (PlayerPickupItemEvent event){ if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (event.getItem().getItemStack().getType() == Material.MOB_SPAWNER) { event.setCancelled(true); return; } if (this.plugin.whoDropedItem.containsKey(event.getItem().hashCode())) { if (event.isCancelled()) { return; } String from = this.plugin.whoDropedItem.get(event.getItem().hashCode()); if (from != null && !event.getPlayer().getName().matches(from)) { info.tregmine.api.TregminePlayer tregminePlayerFrom = this.plugin.tregmine.tregminePlayer.get(from); info.tregmine.api.TregminePlayer tregminePlayerTo = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.log.info (event.getItem().getItemStack().getAmount() + ":" + event.getItem().getItemStack().getType().toString() + " " + tregminePlayerFrom.getChatName() + " ==> " + tregminePlayerTo.getChatName() ); if (!tregminePlayerFrom.getMetaBoolean("invis") && ! tregminePlayerTo.getMetaBoolean("invis")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "You got " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + ChatColor.YELLOW + " from " + tregminePlayerFrom.getChatName() ); this.plugin.getServer().getPlayer(from).sendMessage(ChatColor.YELLOW + "You gave " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + " to " + tregminePlayerTo.getChatName() ); } } this.plugin.whoDropedItem.put(event.getItem().hashCode(), null); } } }
error
InventorySpy/src/info/tregmine/inventoryspy/SpyPlayerListener.java
error
<ide><path>nventorySpy/src/info/tregmine/inventoryspy/SpyPlayerListener.java <ide> @EventHandler <ide> public void onPlayerInteract(PlayerInteractEvent event) { <ide> if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { <del> event.getPlayer().sendMessage("Interaction faild"); <del>// if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { <del>// event.setCancelled(true); <del>// return; <del>// } <add> if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { <add> event.getPlayer().sendMessage("error"); <add> event.setCancelled(true); <add> return; <ide> } <add> } <ide> } <ide> <ide>
Java
apache-2.0
b7e60acf91edb844b425ecd20dde1c83aa41d058
0
no-hope/java-toolkit,no-hope/java-toolkit,no-hope/java-toolkit,no-hope/java-toolkit
package org.nohope.akka.spring; import akka.actor.UntypedActor; import javax.inject.Inject; import javax.inject.Named; /** * @author <a href="mailto:[email protected]">ketoth xupack</a> * @since 9/16/12 11:12 PM */ public class Bean extends UntypedActor { private final Integer param1; private final String param2; private final String param3; @Inject public Bean(final Integer param1, @Named("param2") final String param2, @Named("param3") final String param3) { this.param1 = param1; this.param2 = param2; this.param3 = param3; } public Integer getParam1() { return param1; } public String getParam2() { return param2; } public String getParam3() { return param3; } @Override public void onReceive(final Object message) { if (message instanceof Props) { switch ((Props) message) { case PARAM1: getSender().tell(param1, getSelf()); break; case PARAM2: getSender().tell(param2, getSelf()); break; case PARAM3: getSender().tell(param3, getSelf()); break; } } } public static enum Props { PARAM1, PARAM2, PARAM3 } }
projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java
package org.nohope.akka.spring; import akka.actor.UntypedActor; import javax.inject.Inject; import javax.inject.Named; /** * @author <a href="mailto:[email protected]">ketoth xupack</a> * @since 9/16/12 11:12 PM */ public class Bean extends UntypedActor { private final Integer param1; private final String param2; private final String param3; @Inject public Bean(final Integer param1, @Named("param2") final String param2, @Named("param3") final String param3) { this.param1 = param1; this.param2 = param2; this.param3 = param3; } public Integer getParam1() { return param1; } public String getParam2() { return param2; } public String getParam3() { return param3; } @Override public void onReceive(final Object message) { if (message instanceof Props) { switch ((Props) message) { case PARAM1: getSender().tell(param1); break; case PARAM2: getSender().tell(param2); break; case PARAM3: getSender().tell(param3); break; } } } public static enum Props { PARAM1, PARAM2, PARAM3 } }
fix for akka deprecated api Signed-off-by: Ketoth Xupack <[email protected]>
projects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java
fix for akka deprecated api
<ide><path>rojects/akka-spring/src/test/java/org/nohope/akka/spring/Bean.java <ide> if (message instanceof Props) { <ide> switch ((Props) message) { <ide> case PARAM1: <del> getSender().tell(param1); <add> getSender().tell(param1, getSelf()); <ide> break; <ide> case PARAM2: <del> getSender().tell(param2); <add> getSender().tell(param2, getSelf()); <ide> break; <ide> case PARAM3: <del> getSender().tell(param3); <add> getSender().tell(param3, getSelf()); <ide> break; <ide> } <ide> }
Java
apache-2.0
0ef037416b0cc46057e24011d1c2e0e4180b9ae7
0
codenpk/aerosolve,dastjead/aerosolve,muspelheim/aerosolve,quevedin/aerosolve,aglne/aerosolve,codenpk/aerosolve,b-cuts/aerosolve,linguistbreaker/aerosolve,linearregression/aerosolve,airbnb/aerosolve,aglne/aerosolve,dastjead/aerosolve,TDDFT/aerosolve,b-cuts/aerosolve,lancezlin/aerosolve,jyt109/aerosolve,igitur/aerosolve,matheus-santos/aerosolve,Chasego/aerosolve,jasper-chen/aerosolve,giserh/aerosolve,sagivo/aerosolve,airbnb/aerosolve,footbook/aerosolve,lancezlin/aerosolve,npujowidianto/aerosolve,footbook/aerosolve,wavelets/aerosolve,giserh/aerosolve,KBryan/aerosolve,jyt109/aerosolve,igitur/aerosolve,muspelheim/aerosolve,ralic/aerosolve,fhernandez173/aerosolve,rogervaas/aerosolve,zcqqq/aerosolve,mathkann/aerosolve,rogervaas/aerosolve,dmoliveira/aerosolve,common2015/aerosolve,KBryan/aerosolve,linearregression/aerosolve,matheus-santos/aerosolve,jeancroy/aerosolve,Chasego/aerosolve,TDDFT/aerosolve,mathkann/aerosolve,zcqqq/aerosolve,dmoliveira/aerosolve,wavelets/aerosolve,is00hcw/aerosolve,fhernandez173/aerosolve,linguistbreaker/aerosolve,sagivo/aerosolve,jasper-chen/aerosolve,common2015/aerosolve,is00hcw/aerosolve,quevedin/aerosolve,jeancroy/aerosolve,npujowidianto/aerosolve,ralic/aerosolve
package com.airbnb.aerosolve.core.models; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.Serializable; import java.lang.StringBuilder; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.AbstractMap; import com.airbnb.aerosolve.core.FeatureVector; import com.airbnb.aerosolve.core.ModelHeader; import com.airbnb.aerosolve.core.ModelRecord; import com.airbnb.aerosolve.core.DebugScoreRecord; import com.airbnb.aerosolve.core.util.Util; import com.airbnb.aerosolve.core.util.Spline; import lombok.Getter; import lombok.Setter; // A simple decision tree model. public class DecisionTreeModel extends AbstractModel { private static final long serialVersionUID = 3651061358422885379L; @Getter @Setter protected ArrayList<ModelRecord> stumps; public DecisionTreeModel() { } @Override public float scoreItem(FeatureVector combinedItem) { Map<String, Map<String, Double>> floatFeatures = Util.flattenFeature(combinedItem); int leaf = getLeafIndex(floatFeatures); if (leaf < 0) return 0.0f; ModelRecord stump = stumps.get(leaf); return (float) stump.featureWeight; } public int getLeafIndex(Map<String, Map<String, Double>> floatFeatures) { if (stumps.isEmpty()) return -1; int index = 0; while (true) { ModelRecord stump = stumps.get(index); if (!stump.isSetLeftChild() || !stump.isSetRightChild()) { break; } boolean response = BoostedStumpsModel.getStumpResponse(stump, floatFeatures); if (response) { index = stump.rightChild; } else { index = stump.leftChild; } } return index; } @Override // Decision trees don't usually have debuggable components. public float debugScoreItem(FeatureVector combinedItem, StringBuilder builder) { return 0.0f; } @Override // Decision trees don't usually have debuggable components. public List<DebugScoreRecord> debugScoreComponents(FeatureVector combinedItem) { List<DebugScoreRecord> scoreRecordsList = new ArrayList<>(); return scoreRecordsList; } public void save(BufferedWriter writer) throws IOException { ModelHeader header = new ModelHeader(); header.setModelType("decision_tree"); long count = stumps.size(); header.setNumRecords(count); ModelRecord headerRec = new ModelRecord(); headerRec.setModelHeader(header); writer.write(Util.encode(headerRec)); writer.newLine(); for (ModelRecord rec : stumps) { writer.write(Util.encode(rec)); writer.newLine(); } writer.flush(); } @Override protected void loadInternal(ModelHeader header, BufferedReader reader) throws IOException { long rows = header.getNumRecords(); stumps = new ArrayList<>(); for (long i = 0; i < rows; i++) { String line = reader.readLine(); ModelRecord record = Util.decodeModel(line); stumps.add(record); } } /* * Returns a debuggable single tree in graphviz DOT format */ public String toDot() { StringBuilder sb = new StringBuilder(); sb.append("digraph g {\n"); sb.append("graph [ rankdir = \"LR\" ]\n"); for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); if (stump.isSetLeftChild()) { sb.append(String.format("\"node%d\" [\n", i)); double thresh = stump.threshold; sb.append(String.format( "label = \"<f0> %s:%s | <f1> less or equal %f | <f2> greater than %f\";\n", stump.featureFamily, stump.featureName, thresh, thresh)); sb.append("shape = \"record\";\n"); sb.append("];\n"); } else { sb.append(String.format("\"node%d\" [\n", i)); sb.append(String.format("label = \"<f0> Weight %f\";\n", stump.featureWeight)); sb.append("shape = \"record\";\n"); sb.append("];\n"); } } int count = 0; for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); if (stump.isSetLeftChild()) { sb.append(String.format("\"node%d\":f1 -> \"node%d\":f0 [ id = %d ];\n", i, stump.leftChild, count)); count = count + 1; sb.append(String.format("\"node%d\":f2 -> \"node%d\":f0 [id = %d];\n", i, stump.rightChild, count)); count = count + 1; } } sb.append("}\n"); return sb.toString(); } // Returns the transform config in human readable form. public String toHumanReadableTransform() { StringBuilder sb = new StringBuilder(); sb.append(" nodes: [\n"); for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); sb.append(" \""); if (stump.isSetLeftChild()) { // Parent node, node id, family, name, threshold, left, right sb.append( String.format("P,%d,%s,%s,%f,%d,%d", i, stump.featureFamily, stump.featureName, stump.threshold, stump.leftChild, stump.rightChild)); } else { // Leaf node, node id, feature weight, human readable leaf name. sb.append(String.format("L,%d,%f,LEAF_%d", i, stump.featureWeight, i)); } sb.append("\"\n"); } sb.append(" ]\n"); return sb.toString(); } // Constructs a tree from human readable transform list. public static DecisionTreeModel fromHumanReadableTransform(List<String> rows) { DecisionTreeModel tree = new DecisionTreeModel(); ArrayList<ModelRecord> records = new ArrayList<>(); tree.setStumps(records); for (String row : rows) { ModelRecord rec = new ModelRecord(); records.add(rec); String token[] = row.split(","); if (token[0].contains("P")) { // Parent node rec.setFeatureFamily(token[2]); rec.setFeatureName(token[3]); rec.setThreshold(Double.parseDouble(token[4])); rec.setLeftChild(Integer.parseInt(token[5])); rec.setRightChild(Integer.parseInt(token[6])); } else { rec.setFeatureName(token[3]); rec.setFeatureWeight(Double.parseDouble(token[2])); } } return tree; } }
core/src/main/java/com/airbnb/aerosolve/core/models/DecisionTreeModel.java
package com.airbnb.aerosolve.core.models; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.Serializable; import java.lang.StringBuilder; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.AbstractMap; import com.airbnb.aerosolve.core.FeatureVector; import com.airbnb.aerosolve.core.ModelHeader; import com.airbnb.aerosolve.core.ModelRecord; import com.airbnb.aerosolve.core.DebugScoreRecord; import com.airbnb.aerosolve.core.util.Util; import com.airbnb.aerosolve.core.util.Spline; import lombok.Getter; import lombok.Setter; // A simple decision tree model. public class DecisionTreeModel extends AbstractModel { private static final long serialVersionUID = 3651061358422885379L; @Getter @Setter protected ArrayList<ModelRecord> stumps; public DecisionTreeModel() { } @Override public float scoreItem(FeatureVector combinedItem) { Map<String, Map<String, Double>> floatFeatures = Util.flattenFeature(combinedItem); int leaf = getLeafIndex(floatFeatures); if (leaf < 0) return 0.0f; ModelRecord stump = stumps.get(leaf); return (float) stump.featureWeight; } public int getLeafIndex(Map<String, Map<String, Double>> floatFeatures) { if (stumps.isEmpty()) return -1; int index = 0; while (true) { ModelRecord stump = stumps.get(index); if (!stump.isSetLeftChild() || !stump.isSetRightChild()) { break; } boolean response = BoostedStumpsModel.getStumpResponse(stump, floatFeatures); if (response) { index = stump.rightChild; } else { index = stump.leftChild; } } return index; } @Override // Decision trees don't usually have debuggable components. public float debugScoreItem(FeatureVector combinedItem, StringBuilder builder) { return 0.0f; } @Override // Decision trees don't usually have debuggable components. public List<DebugScoreRecord> debugScoreComponents(FeatureVector combinedItem) { List<DebugScoreRecord> scoreRecordsList = new ArrayList<>(); return scoreRecordsList; } public void save(BufferedWriter writer) throws IOException { ModelHeader header = new ModelHeader(); header.setModelType("decision_tree"); long count = stumps.size(); header.setNumRecords(count); ModelRecord headerRec = new ModelRecord(); headerRec.setModelHeader(header); writer.write(Util.encode(headerRec)); writer.newLine(); for (ModelRecord rec : stumps) { writer.write(Util.encode(rec)); writer.newLine(); } writer.flush(); } @Override protected void loadInternal(ModelHeader header, BufferedReader reader) throws IOException { long rows = header.getNumRecords(); stumps = new ArrayList<>(); for (long i = 0; i < rows; i++) { String line = reader.readLine(); ModelRecord record = Util.decodeModel(line); stumps.add(record); } } /* * Returns a debuggable single tree in graphviz DOT format */ public String toDot() { StringBuilder sb = new StringBuilder(); sb.append("digraph g {\n"); sb.append("graph [ rankdir = \"LR\" ]\n"); for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); if (stump.isSetLeftChild()) { sb.append(String.format("\"node%d\" [\n", i)); double thresh = stump.threshold; sb.append(String.format( "label = \"<f0> %s:%s | <f1> less or equal %f | <f2> greater than %f\";\n", stump.featureFamily, stump.featureName, thresh, thresh)); sb.append("shape = \"record\";\n"); sb.append("];\n"); } else { sb.append(String.format("\"node%d\" [\n", i)); sb.append(String.format("label = \"<f0> Weight %f\";\n", stump.featureWeight)); sb.append("shape = \"record\";\n"); sb.append("];\n"); } } int count = 0; for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); if (stump.isSetLeftChild()) { sb.append(String.format("\"node%d\":f1 -> \"node%d\":f0 [ id = %d ];\n", i, stump.leftChild, count)); count = count + 1; sb.append(String.format("\"node%d\":f2 -> \"node%d\":f0 [id = %d];\n", i, stump.rightChild, count)); count = count + 1; } } sb.append("}\n"); return sb.toString(); } // Returns the transform config in human readable form. public String toHumanReadableTransform() { StringBuilder sb = new StringBuilder(); sb.append(" nodes: [\n"); for (int i = 0; i < stumps.size(); i++) { ModelRecord stump = stumps.get(i); sb.append(" \""); if (stump.isSetLeftChild()) { // Parent node, node id, family, name, threshold, left, right sb.append( String.format("P,%d,%s,%s,%f,%d,%d", i, stump.featureFamily, stump.featureName, stump.threshold, stump.leftChild, stump.rightChild)); } else { // Leaf node, node id, feature weight, human readable leaf name. sb.append(String.format("L,%d,%f,LEAF_%d", i, stump.featureWeight, i)); } sb.append("\"\n"); } sb.append(" ]\n"); return sb.toString(); } // Constructs a tree from human readable transform list. public static DecisionTreeModel fromHumanReadableTransform(List<String> rows) { DecisionTreeModel tree = new DecisionTreeModel(); ArrayList<ModelRecord> records = new ArrayList<>(); tree.setStumps(records); for (String row : rows) { ModelRecord rec = new ModelRecord(); records.add(rec); String token[] = row.split(","); if (token[0].contains("P")) { // Parent node rec.setFeatureFamily(token[2]); rec.setFeatureName(token[3]); rec.setThreshold(Double.parseDouble(token[4])); rec.setLeftChild(Integer.parseInt(token[5])); rec.setRightChild(Integer.parseInt(token[6])); } else { rec.setFeatureName(token[3]); rec.setFeatureWeight(Double.parseDouble(token[2])); } } return tree; } }
Fix more indents
core/src/main/java/com/airbnb/aerosolve/core/models/DecisionTreeModel.java
Fix more indents
<ide><path>ore/src/main/java/com/airbnb/aerosolve/core/models/DecisionTreeModel.java <ide> <ide> // Constructs a tree from human readable transform list. <ide> public static DecisionTreeModel fromHumanReadableTransform(List<String> rows) { <del> DecisionTreeModel tree = new DecisionTreeModel(); <del> ArrayList<ModelRecord> records = new ArrayList<>(); <del> tree.setStumps(records); <del> for (String row : rows) { <del> ModelRecord rec = new ModelRecord(); <del> records.add(rec); <del> String token[] = row.split(","); <del> if (token[0].contains("P")) { <del> // Parent node <del> rec.setFeatureFamily(token[2]); <del> rec.setFeatureName(token[3]); <del> rec.setThreshold(Double.parseDouble(token[4])); <del> rec.setLeftChild(Integer.parseInt(token[5])); <del> rec.setRightChild(Integer.parseInt(token[6])); <del> } else { <add> DecisionTreeModel tree = new DecisionTreeModel(); <add> ArrayList<ModelRecord> records = new ArrayList<>(); <add> tree.setStumps(records); <add> for (String row : rows) { <add> ModelRecord rec = new ModelRecord(); <add> records.add(rec); <add> String token[] = row.split(","); <add> if (token[0].contains("P")) { <add> // Parent node <add> rec.setFeatureFamily(token[2]); <add> rec.setFeatureName(token[3]); <add> rec.setThreshold(Double.parseDouble(token[4])); <add> rec.setLeftChild(Integer.parseInt(token[5])); <add> rec.setRightChild(Integer.parseInt(token[6])); <add> } else { <ide> rec.setFeatureName(token[3]); <del> rec.setFeatureWeight(Double.parseDouble(token[2])); <del> } <del> } <del> return tree; <add> rec.setFeatureWeight(Double.parseDouble(token[2])); <add> } <add> } <add> return tree; <ide> } <ide> }
Java
mit
3a507b2091dd266113e57e0779bdc3e50fa24cde
0
dnalves/sugar,satyan/sugar,mitchyboy9/sugar,mbag102/sugar,AdamLuptak/Time_MNA,RossinesP/sugar,janzoner/sugar
package com.orm; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.text.TextUtils; import android.util.Log; import com.orm.dsl.Table; import com.orm.dsl.Unique; import com.orm.util.NamingHelper; import com.orm.util.QueryBuilder; import com.orm.util.ReflectionUtil; import com.orm.util.SugarCursor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import static com.orm.SugarContext.getSugarContext; public class SugarRecord { public static final String SUGAR = "Sugar"; private Long id = null; private static SQLiteDatabase getSugarDataBase() { return getSugarContext().getSugarDb().getDB(); } public static <T> int deleteAll(Class<T> type) { return deleteAll(type, null); } public static <T> int deleteAll(Class<T> type, String whereClause, String... whereArgs) { return getSugarDataBase().delete(NamingHelper.toSQLName(type), whereClause, whereArgs); } public static <T> Cursor getCursor(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor raw = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new SugarCursor(raw); } @SuppressWarnings("deprecation") public static <T> void saveInTx(T... objects) { saveInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void saveInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object: objects) { save(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } @SuppressWarnings("deprecation") public static <T> void updateInTx(T... objects) { updateInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void updateInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object: objects) { update(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } @SuppressWarnings("deprecation") public static <T> int deleteInTx(T... objects) { return deleteInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> int deleteInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); int deletedRows = 0; try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object : objects) { if (delete(object)) { ++deletedRows; } } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { deletedRows = 0; Log.i(SUGAR, "Error in deleting in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } return deletedRows; } public static <T> List<T> listAll(Class<T> type) { return find(type, null, null, null, null, null); } public static <T> List<T> listAll(Class<T> type, String orderBy) { return find(type, null, null, null, orderBy, null); } public static <T> T findById(Class<T> type, Long id) { List<T> list = find(type, "id=?", new String[]{String.valueOf(id)}, null, null, "1"); if (list.isEmpty()) return null; return list.get(0); } public static <T> T findById(Class<T> type, Integer id) { return findById(type, Long.valueOf(id)); } public static <T> List<T> findById(Class<T> type, String[] ids) { String whereClause = "id IN (" + QueryBuilder.generatePlaceholders(ids.length) + ")"; return find(type, whereClause, ids); } public static <T> T first(Class<T>type) { List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID ASC LIMIT 1"); if (list.isEmpty()) { return null; } return list.get(0); } public static <T> T last(Class<T>type) { List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID DESC LIMIT 1"); if (list.isEmpty()) { return null; } return list.get(0); } public static <T> Iterator<T> findAll(Class<T> type) { return findAsIterator(type, null, null, null, null, null); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String... whereArgs) { return findAsIterator(type, whereClause, whereArgs, null, null, null); } public static <T> Iterator<T> findWithQueryAsIterator(Class<T> type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); return new CursorIterator<T>(type, cursor); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new CursorIterator<T>(type, cursor); } public static <T> List<T> find(Class<T> type, String whereClause, String... whereArgs) { return find(type, whereClause, whereArgs, null, null, null); } public static <T> List<T> findWithQuery(Class<T> type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); return getEntitiesFromCursor(cursor, type); } public static void executeQuery(String query, String... arguments) { getSugarDataBase().execSQL(query, arguments); } public static <T> List<T> find(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return getEntitiesFromCursor(cursor, type); } public static <T> List<T> getEntitiesFromCursor(Cursor cursor, Class<T> type){ T entity; List<T> result = new ArrayList<T>(); try { while (cursor.moveToNext()) { entity = type.getDeclaredConstructor().newInstance(); inflate(cursor, entity, getSugarContext().getEntitiesMap()); result.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { cursor.close(); } return result; } public static <T> long count(Class<?> type) { return count(type, null, null, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs) { return count(type, whereClause, whereArgs, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { long result = -1; String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : ""; SQLiteStatement sqliteStatement; try { sqliteStatement = getSugarDataBase().compileStatement("SELECT count(*) FROM " + NamingHelper.toSQLName(type) + filter); } catch (SQLiteException e) { e.printStackTrace(); return result; } if (whereArgs != null) { for (int i = whereArgs.length; i != 0; i--) { sqliteStatement.bindString(i, whereArgs[i - 1]); } } try { result = sqliteStatement.simpleQueryForLong(); } finally { sqliteStatement.close(); } return result; } public static long save(Object object) { return save(getSugarDataBase(), object); } static long save(SQLiteDatabase db, Object object) { Map<Object, Long> entitiesMap = getSugarContext().getEntitiesMap(); List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); Field idField = null; for (Field column : columns) { ReflectionUtil.addFieldValueToColumn(values, column, object, entitiesMap); if (column.getName().equals("id")) { idField = column; } } boolean isSugarEntity = isSugarEntity(object.getClass()); if (isSugarEntity && entitiesMap.containsKey(object)) { values.put("id", entitiesMap.get(object)); } long id = db.insertWithOnConflict(NamingHelper.toSQLName(object.getClass()), null, values, SQLiteDatabase.CONFLICT_REPLACE); if (object.getClass().isAnnotationPresent(Table.class)) { if (idField != null) { idField.setAccessible(true); try { idField.set(object, new Long(id)); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { entitiesMap.put(object, id); } } else if (SugarRecord.class.isAssignableFrom(object.getClass())) { ((SugarRecord) object).setId(id); } Log.i(SUGAR, object.getClass().getSimpleName() + " saved : " + id); return id; } public static long update(Object object) { return update(getSugarDataBase(), object); } static long update(SQLiteDatabase db, Object object) { Map<Object, Long> entitiesMap = getSugarContext().getEntitiesMap(); List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); Field idField = null; StringBuilder whereClause = new StringBuilder(); List<String> whereArgs = new ArrayList<>(); for (Field column : columns) { if(column.isAnnotationPresent(Unique.class)) { try { column.setAccessible(true); String columnName = NamingHelper.toSQLName(column); Object columnValue = column.get(object); whereClause.append(columnName).append(" = ?"); whereArgs.add(String.valueOf(columnValue)); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { if (!column.getName().equals("id")) { ReflectionUtil.addFieldValueToColumn(values, column, object, entitiesMap); } } } String[] whereArgsArray = whereArgs.toArray(new String[whereArgs.size()]); // Get SugarRecord based on Unique values long rowsEffected = db.update(NamingHelper.toSQLName(object.getClass()), values, whereClause.toString(), whereArgsArray); if (rowsEffected == 0) { return save(db, object); } else { return rowsEffected; } } public static boolean isSugarEntity(Class<?> objectClass) { return objectClass.isAnnotationPresent(Table.class) || SugarRecord.class.isAssignableFrom(objectClass); } private static void inflate(Cursor cursor, Object object, Map<Object, Long> entitiesMap) { List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); if (!entitiesMap.containsKey(object)) { entitiesMap.put(object, cursor.getLong(cursor.getColumnIndex(("ID")))); } for (Field field : columns) { field.setAccessible(true); Class<?> fieldType = field.getType(); if (isSugarEntity(fieldType)) { try { long id = cursor.getLong(cursor.getColumnIndex(NamingHelper.toSQLName(field))); field.set(object, (id > 0) ? findById(fieldType, id) : null); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { ReflectionUtil.setFieldValueFromCursor(cursor, field, object); } } } public boolean delete() { Long id = getId(); Class<?> type = getClass(); if (id != null && id > 0L) { Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); return getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; } else { Log.i(SUGAR, "Cannot delete object: " + type.getSimpleName() + " - object has not been saved"); return false; } } public static boolean delete(Object object) { Class<?> type = object.getClass(); if (type.isAnnotationPresent(Table.class)) { try { Field field = type.getDeclaredField("id"); field.setAccessible(true); Long id = (Long) field.get(object); if (id != null && id > 0L) { boolean deleted = getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); return deleted; } else { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - object has not been saved"); return false; } } catch (NoSuchFieldException e) { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - annotated object has no id"); return false; } catch (IllegalAccessException e) { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - can't access id"); return false; } } else if (SugarRecord.class.isAssignableFrom(type)) { return ((SugarRecord) object).delete(); } else { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - not persisted"); return false; } } public long save() { return save(getSugarDataBase(), this); } public long update() { return update(getSugarDataBase(), this); } @SuppressWarnings("unchecked") void inflate(Cursor cursor) { inflate(cursor, this, getSugarContext().getEntitiesMap()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } static class CursorIterator<E> implements Iterator<E> { Class<E> type; Cursor cursor; public CursorIterator(Class<E> type, Cursor cursor) { this.type = type; this.cursor = cursor; } @Override public boolean hasNext() { return cursor != null && !cursor.isClosed() && !cursor.isAfterLast(); } @Override public E next() { E entity = null; if (cursor == null || cursor.isAfterLast()) { throw new NoSuchElementException(); } if (cursor.isBeforeFirst()) { cursor.moveToFirst(); } try { entity = type.getDeclaredConstructor().newInstance(); inflate(cursor, entity, getSugarContext().getEntitiesMap()); } catch (Exception e) { e.printStackTrace(); } finally { cursor.moveToNext(); if (cursor.isAfterLast()) { cursor.close(); } } return entity; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
library/src/main/java/com/orm/SugarRecord.java
package com.orm; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.text.TextUtils; import android.util.Log; import com.orm.dsl.Table; import com.orm.dsl.Unique; import com.orm.util.NamingHelper; import com.orm.util.QueryBuilder; import com.orm.util.ReflectionUtil; import com.orm.util.SugarCursor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import static com.orm.SugarContext.getSugarContext; public class SugarRecord { public static final String SUGAR = "Sugar"; private Long id = null; private static SQLiteDatabase getSugarDataBase() { return getSugarContext().getSugarDb().getDB(); } public static <T> int deleteAll(Class<T> type) { return deleteAll(type, null); } public static <T> int deleteAll(Class<T> type, String whereClause, String... whereArgs) { return getSugarDataBase().delete(NamingHelper.toSQLName(type), whereClause, whereArgs); } public static <T> Cursor getCursor(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor raw = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new SugarCursor(raw); } @SuppressWarnings("deprecation") public static <T> void saveInTx(T... objects) { saveInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void saveInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object: objects) { save(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } @SuppressWarnings("deprecation") public static <T> void updateInTx(T... objects) { updateInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> void updateInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object: objects) { update(object); } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { Log.i(SUGAR, "Error in saving in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } } @SuppressWarnings("deprecation") public static <T> int deleteInTx(T... objects) { return deleteInTx(Arrays.asList(objects)); } @SuppressWarnings("deprecation") public static <T> int deleteInTx(Collection<T> objects) { SQLiteDatabase sqLiteDatabase = getSugarDataBase(); int deletedRows = 0; try { sqLiteDatabase.beginTransaction(); sqLiteDatabase.setLockingEnabled(false); for (T object : objects) { if (delete(object)) { ++deletedRows; } } sqLiteDatabase.setTransactionSuccessful(); } catch (Exception e) { deletedRows = 0; Log.i(SUGAR, "Error in deleting in transaction " + e.getMessage()); } finally { sqLiteDatabase.endTransaction(); sqLiteDatabase.setLockingEnabled(true); } return deletedRows; } public static <T> List<T> listAll(Class<T> type) { return find(type, null, null, null, null, null); } public static <T> List<T> listAll(Class<T> type, String orderBy) { return find(type, null, null, null, orderBy, null); } public static <T> T findById(Class<T> type, Long id) { List<T> list = find(type, "id=?", new String[]{String.valueOf(id)}, null, null, "1"); if (list.isEmpty()) return null; return list.get(0); } public static <T> T findById(Class<T> type, Integer id) { return findById(type, Long.valueOf(id)); } public static <T> List<T> findById(Class<T> type, String[] ids) { String whereClause = "id IN (" + QueryBuilder.generatePlaceholders(ids.length) + ")"; return find(type, whereClause, ids); } public static <T> T first(Class<T>type) { List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID ASC LIMIT 1"); if (list.isEmpty()) { return null; } return list.get(0); } public static <T> T last(Class<T>type) { List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ID DESC LIMIT 1"); if (list.isEmpty()) { return null; } return list.get(0); } public static <T> Iterator<T> findAll(Class<T> type) { return findAsIterator(type, null, null, null, null, null); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String... whereArgs) { return findAsIterator(type, whereClause, whereArgs, null, null, null); } public static <T> Iterator<T> findWithQueryAsIterator(Class<T> type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); return new CursorIterator<T>(type, cursor); } public static <T> Iterator<T> findAsIterator(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new CursorIterator<T>(type, cursor); } public static <T> List<T> find(Class<T> type, String whereClause, String... whereArgs) { return find(type, whereClause, whereArgs, null, null, null); } public static <T> List<T> findWithQuery(Class<T> type, String query, String... arguments) { Cursor cursor = getSugarDataBase().rawQuery(query, arguments); return getEntitiesFromCursor(cursor, type); } public static void executeQuery(String query, String... arguments) { getSugarDataBase().execSQL(query, arguments); } public static <T> List<T> find(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor cursor = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return getEntitiesFromCursor(cursor, type); } public static <T> List<T> getEntitiesFromCursor(Cursor cursor, Class<T> type){ T entity; List<T> result = new ArrayList<T>(); try { while (cursor.moveToNext()) { entity = type.getDeclaredConstructor().newInstance(); inflate(cursor, entity, getSugarContext().getEntitiesMap()); result.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { cursor.close(); } return result; } public static <T> long count(Class<?> type) { return count(type, null, null, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs) { return count(type, whereClause, whereArgs, null, null, null); } public static <T> long count(Class<?> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { long result = -1; String filter = (!TextUtils.isEmpty(whereClause)) ? " where " + whereClause : ""; SQLiteStatement sqliteStatement; try { sqliteStatement = getSugarDataBase().compileStatement("SELECT count(*) FROM " + NamingHelper.toSQLName(type) + filter); } catch (SQLiteException e) { e.printStackTrace(); return result; } if (whereArgs != null) { for (int i = whereArgs.length; i != 0; i--) { sqliteStatement.bindString(i, whereArgs[i - 1]); } } try { result = sqliteStatement.simpleQueryForLong(); } finally { sqliteStatement.close(); } return result; } public static long save(Object object) { return save(getSugarDataBase(), object); } static long save(SQLiteDatabase db, Object object) { Map<Object, Long> entitiesMap = getSugarContext().getEntitiesMap(); List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); Field idField = null; for (Field column : columns) { ReflectionUtil.addFieldValueToColumn(values, column, object, entitiesMap); if (column.getName().equals("id")) { idField = column; } } boolean isSugarEntity = isSugarEntity(object.getClass()); if (isSugarEntity && entitiesMap.containsKey(object)) { values.put("id", entitiesMap.get(object)); } long id = db.insertWithOnConflict(NamingHelper.toSQLName(object.getClass()), null, values, SQLiteDatabase.CONFLICT_REPLACE); if (object.getClass().isAnnotationPresent(Table.class)) { if (idField != null) { idField.setAccessible(true); try { idField.set(object, new Long(id)); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { entitiesMap.put(object, id); } } else if (SugarRecord.class.isAssignableFrom(object.getClass())) { ((SugarRecord) object).setId(id); } Log.i(SUGAR, object.getClass().getSimpleName() + " saved : " + id); return id; } public static long update(Object object) { return update(getSugarDataBase(), object); } static long update(SQLiteDatabase db, Object object) { Map<Object, Long> entitiesMap = getSugarContext().getEntitiesMap(); List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); ContentValues values = new ContentValues(columns.size()); Field idField = null; StringBuilder whereClause = new StringBuilder(); List<String> whereArgs = new ArrayList<>(); for (Field column : columns) { if(column.isAnnotationPresent(Unique.class)) { try { column.setAccessible(true); String columnName = NamingHelper.toSQLName(column); Object columnValue = column.get(object); whereClause.append(columnName).append(" = ?"); whereArgs.add(String.valueOf(columnValue)); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { if (!column.getName().equals("id")) { ReflectionUtil.addFieldValueToColumn(values, column, object, entitiesMap); } } } String[] whereArgsArray = whereArgs.toArray(new String[whereArgs.size()]); // Get SugarRecord based on Unique values long id = db.update(NamingHelper.toSQLName(object.getClass()), values, whereClause.toString(), whereArgsArray); return id; } public static boolean isSugarEntity(Class<?> objectClass) { return objectClass.isAnnotationPresent(Table.class) || SugarRecord.class.isAssignableFrom(objectClass); } private static void inflate(Cursor cursor, Object object, Map<Object, Long> entitiesMap) { List<Field> columns = ReflectionUtil.getTableFields(object.getClass()); if (!entitiesMap.containsKey(object)) { entitiesMap.put(object, cursor.getLong(cursor.getColumnIndex(("ID")))); } for (Field field : columns) { field.setAccessible(true); Class<?> fieldType = field.getType(); if (isSugarEntity(fieldType)) { try { long id = cursor.getLong(cursor.getColumnIndex(NamingHelper.toSQLName(field))); field.set(object, (id > 0) ? findById(fieldType, id) : null); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { ReflectionUtil.setFieldValueFromCursor(cursor, field, object); } } } public boolean delete() { Long id = getId(); Class<?> type = getClass(); if (id != null && id > 0L) { Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); return getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; } else { Log.i(SUGAR, "Cannot delete object: " + type.getSimpleName() + " - object has not been saved"); return false; } } public static boolean delete(Object object) { Class<?> type = object.getClass(); if (type.isAnnotationPresent(Table.class)) { try { Field field = type.getDeclaredField("id"); field.setAccessible(true); Long id = (Long) field.get(object); if (id != null && id > 0L) { boolean deleted = getSugarDataBase().delete(NamingHelper.toSQLName(type), "Id=?", new String[]{id.toString()}) == 1; Log.i(SUGAR, type.getSimpleName() + " deleted : " + id); return deleted; } else { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - object has not been saved"); return false; } } catch (NoSuchFieldException e) { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - annotated object has no id"); return false; } catch (IllegalAccessException e) { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - can't access id"); return false; } } else if (SugarRecord.class.isAssignableFrom(type)) { return ((SugarRecord) object).delete(); } else { Log.i(SUGAR, "Cannot delete object: " + object.getClass().getSimpleName() + " - not persisted"); return false; } } public long save() { return save(getSugarDataBase(), this); } public long update() { return update(getSugarDataBase(), this); } @SuppressWarnings("unchecked") void inflate(Cursor cursor) { inflate(cursor, this, getSugarContext().getEntitiesMap()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } static class CursorIterator<E> implements Iterator<E> { Class<E> type; Cursor cursor; public CursorIterator(Class<E> type, Cursor cursor) { this.type = type; this.cursor = cursor; } @Override public boolean hasNext() { return cursor != null && !cursor.isClosed() && !cursor.isAfterLast(); } @Override public E next() { E entity = null; if (cursor == null || cursor.isAfterLast()) { throw new NoSuchElementException(); } if (cursor.isBeforeFirst()) { cursor.moveToFirst(); } try { entity = type.getDeclaredConstructor().newInstance(); inflate(cursor, entity, getSugarContext().getEntitiesMap()); } catch (Exception e) { e.printStackTrace(); } finally { cursor.moveToNext(); if (cursor.isAfterLast()) { cursor.close(); } } return entity; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
save record when update fails
library/src/main/java/com/orm/SugarRecord.java
save record when update fails
<ide><path>ibrary/src/main/java/com/orm/SugarRecord.java <ide> <ide> String[] whereArgsArray = whereArgs.toArray(new String[whereArgs.size()]); <ide> // Get SugarRecord based on Unique values <del> long id = db.update(NamingHelper.toSQLName(object.getClass()), values, whereClause.toString(), whereArgsArray); <del> <del> return id; <add> long rowsEffected = db.update(NamingHelper.toSQLName(object.getClass()), values, whereClause.toString(), whereArgsArray); <add> <add> if (rowsEffected == 0) { <add> return save(db, object); <add> } else { <add> return rowsEffected; <add> } <ide> } <ide> <ide>
Java
mit
error: pathspec 'src/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/Fish.java' did not match any file(s) known to git
fe89619cb283119e7eaaed43155d167d7dde5059
1
sunnydas/grokkingalgos,sunnydas/grokkingalgos
package com.sunny.grokkingalgorithms.basic_2020.warmup; import java.util.Stack; public class Fish { /* * You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position. Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where: 0 represents a fish flowing upstream, 1 represents a fish flowing downstream. If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet: If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive. For example, consider arrays A and B such that: A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0 Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive. Write a function: class Solution { public int solution(int[] A, int[] B); } that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive. For example, given the arrays shown above, the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [0..1,000,000,000]; each element of array B is an integer that can have one of the following values: 0, 1; the elements of A are all distinct. */ public static int solution(int[] A, int[] B) { /* A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0 5,1,2 3 0 represents a fish flowing upstream, 1 represents a fish flowing downstream. 4,3,2,1,5 5,1,2,0 3 * * */ Stack<Integer> upStreamStack = new Stack<Integer>(); int dir = B[B.length - 1]; int size = A[A.length - 1]; upStreamStack.add(B.length - 1); for(int i = A.length - 2; i >= 0 ; i--) { int curSize = A[i]; int curDir = B[i]; if(curDir == dir) { //System.out.println(i); upStreamStack.add(i); //System.out.println(upStreamStack); }else{ if(!upStreamStack.isEmpty() && B[upStreamStack.peek()] == B[i]) { upStreamStack.add(i); } else { //System.out.println(upStreamStack); while(!upStreamStack.isEmpty() && (A[upStreamStack.peek()] < curSize) ) { upStreamStack.pop(); } } } dir = curDir; } //System.out.println(upStreamStack); return upStreamStack.size(); } public static void main(String[] args) { // TODO Auto-generated method stub int[] a = new int[] {4,3,2,1,5}; int[] b = new int[] {0,1,0,0,0}; System.out.println(solution(a, b)); /* * * ([0, 1], [1, 1]) */ a = new int[] {0,1}; b = new int[] {1,1}; System.out.println(solution(a,b)); } }
src/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/Fish.java
Checkpoint commit FIsh
src/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/Fish.java
Checkpoint commit FIsh
<ide><path>rc/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/Fish.java <add>package com.sunny.grokkingalgorithms.basic_2020.warmup; <add> <add>import java.util.Stack; <add> <add>public class Fish { <add> <add> /* <add> * You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. <add> <add>The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position. <add> <add>Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where: <add> <add>0 represents a fish flowing upstream, <add>1 represents a fish flowing downstream. <add>If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet: <add> <add>If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, <add>If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. <add>We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive. <add> <add>For example, consider arrays A and B such that: <add> <add> A[0] = 4 B[0] = 0 <add> A[1] = 3 B[1] = 1 <add> A[2] = 2 B[2] = 0 <add> A[3] = 1 B[3] = 0 <add> A[4] = 5 B[4] = 0 <add>Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive. <add> <add>Write a function: <add> <add>class Solution { public int solution(int[] A, int[] B); } <add> <add>that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive. <add> <add>For example, given the arrays shown above, the function should return 2, as explained above. <add> <add>Write an efficient algorithm for the following assumptions: <add> <add>N is an integer within the range [1..100,000]; <add>each element of array A is an integer within the range [0..1,000,000,000]; <add>each element of array B is an integer that can have one of the following values: 0, 1; <add>the elements of A are all distinct. <add> */ <add> <add> public static int solution(int[] A, int[] B) { <add> /* <add> A[0] = 4 B[0] = 0 <add> A[1] = 3 B[1] = 1 <add> A[2] = 2 B[2] = 0 <add> A[3] = 1 B[3] = 0 <add> A[4] = 5 B[4] = 0 <add> <add> <add> 5,1,2 3 <add> <add> <add> 0 represents a fish flowing upstream, <add>1 represents a fish flowing downstream. <add> <add>4,3,2,1,5 <add> <add>5,1,2,0 <add>3 <add> * <add> * <add> */ <add> Stack<Integer> upStreamStack = new Stack<Integer>(); <add> int dir = B[B.length - 1]; <add> int size = A[A.length - 1]; <add> upStreamStack.add(B.length - 1); <add> for(int i = A.length - 2; i >= 0 ; i--) { <add> int curSize = A[i]; <add> int curDir = B[i]; <add> if(curDir == dir) { <add> //System.out.println(i); <add> upStreamStack.add(i); <add> //System.out.println(upStreamStack); <add> }else{ <add> if(!upStreamStack.isEmpty() && B[upStreamStack.peek()] == B[i]) { <add> upStreamStack.add(i); <add> } <add> else { <add> //System.out.println(upStreamStack); <add> while(!upStreamStack.isEmpty() && <add> (A[upStreamStack.peek()] < curSize) ) { <add> upStreamStack.pop(); <add> } <add> } <add> } <add> dir = curDir; <add> } <add> //System.out.println(upStreamStack); <add> return upStreamStack.size(); <add> } <add> <add> public static void main(String[] args) { <add> // TODO Auto-generated method stub <add> int[] a = new int[] {4,3,2,1,5}; <add> int[] b = new int[] {0,1,0,0,0}; <add> System.out.println(solution(a, b)); <add> /* <add> * <add> * ([0, 1], [1, 1]) <add> */ <add> a = new int[] {0,1}; <add> b = new int[] {1,1}; <add> System.out.println(solution(a,b)); <add> } <add> <add>}
Java
mit
3bc17f21b2eb5bdf904b186e7bc8f7a6152dc1ee
0
vincentzhang96/DNGearSim
/* * The MIT License (MIT) * * Copyright (c) 2016 Vincent Zhang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package co.phoenixlab.dn.dngearsim.bootstrap; import co.phoenixlab.dn.dngearsim.utils.version.VersionHashPair; import co.phoenixlab.dn.dngearsim.utils.version.Versions; import javafx.concurrent.Task; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.NoSuchElementException; import java.util.Optional; import java.util.ResourceBundle; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static java.nio.file.StandardOpenOption.READ; public class BootstrapTask extends Task<BootstrapHandoff> { /** * Size of the buffer to use to read in the file for digesting */ private static final int DIGEST_BUFFER_SIZE = 8192; /** * Return result when the version-hashpair can't be retrieved */ private static final VersionHashPair NOT_FOUND = new VersionHashPair(); /** * Return result when the version can't be retrieved */ private static final int NOT_FOUND_I = 0; /** * Listener to call on successful load */ private final Consumer<BootstrapHandoff> onBootstrapOk; /** * Listener to call when the bootstrapper itself needs to be updated externally */ private final Runnable onBootstrapSelfUpdateRequired; /** * Whether or not the bootstrapper itself needs to be updated externally */ private volatile boolean selfUpdateRequred; /** * The MessageDigest using SHA-256 to use to hash */ private final MessageDigest sha256Digest; /** * Reusable buffer for computing digests */ private final ByteBuffer digestBuffer; /** * A custom error message to display on exceptions */ private Optional<String> errorMessage; /** * Handler to call when the task fails, with the failure reason */ private final Consumer<String> onFailed; /** * The ResourceBundle for localization strings */ private final ResourceBundle localeBundle; /** * Configuration for this bootstrap task */ private BootstrapConfig config; public BootstrapTask(Consumer<BootstrapHandoff> onBootstrapOk, Runnable onBootstrapSelfUpdateRequired, Consumer<String> onFailed, ResourceBundle localeBundle) { this.onBootstrapOk = onBootstrapOk; this.onBootstrapSelfUpdateRequired = onBootstrapSelfUpdateRequired; this.onFailed = onFailed; this.localeBundle = localeBundle; this.errorMessage = Optional.empty(); this.selfUpdateRequred = false; updateTitle("BootstrapTask"); try { sha256Digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { // This shouldn't happen, since SHA-256 MUST be present on all implementations of Java throw new AssertionError("MessageDigest.getInstance(SHA-256) should never throw NoSuchAlgorithmnExcepton"); } digestBuffer = ByteBuffer.allocateDirect(DIGEST_BUFFER_SIZE); } @Override protected BootstrapHandoff call() throws Exception { config = new BootstrapConfig(); if (doesBootstrapRequireUpdate()) { selfUpdateRequred = true; return null; } checkAndPerformUpdaterUpdate(); // TODO return null; } private boolean doesBootstrapRequireUpdate() throws Exception { updateMessage(localeBundle.getString("bootstrap.splash.text.checking_bootstrap")); TimeUnit.MILLISECONDS.sleep(500); int local = getLocalBootstrapVersion(); int remote = getLatestRemoteBootstrapVersion(); // This system does not perform a hashs check because the assumption is that if the bootstrap is not intact // then no guarantee can be made about the running code // Requires update if the remote version is greater than the local // Don't update if we can't get a response from the server return remote != NOT_FOUND_I && remote > local; } private int getLocalBootstrapVersion() { try (InputStream inputStream = getClass().getResourceAsStream("/co/phoenixlab/dn/dngearsim/bootstrap/version")) { Scanner scanner = new Scanner(inputStream); scanner.useDelimiter(";"); String versionStr = scanner.next(); String compileTime = scanner.next(); return Versions.parseVersion(versionStr); } catch (IOException | NumberFormatException | NoSuchElementException exception) { return NOT_FOUND_I; } } private int getLatestRemoteBootstrapVersion() { // TODO return NOT_FOUND_I; } private void checkAndPerformUpdaterUpdate() throws Exception { updateMessage(localeBundle.getString("bootstrap.splash.text.checking_updater")); TimeUnit.MILLISECONDS.sleep(500); VersionHashPair local = getLocalUpdaterVersion(); VersionHashPair remote = getRemoteUpdaterVersion(); // Check if we got a remote version, if not then we obviously cant update // If we don't have an existing updater or the existing updater was corrupted or is an older version, then // perform an update // And if we can't do either, we're screwed if (remote == NOT_FOUND && local == NOT_FOUND) { errorMessage = Optional.of(localeBundle.getString("bootstrap.splash.error.text.no_updater")); throw new Exception(); } if (remote.isVersionHigherThan(local) || (remote.areVersionsEqual(local) && !remote.areHashesEqual(local))) { performUpdate(remote); } else { updateMessage(localeBundle.getString("bootstrap.splash.text.updater_ok")); TimeUnit.MILLISECONDS.sleep(500); } } private VersionHashPair getLocalUpdaterVersion() { // Find the JAR Path jarPath = config.updaterJarPath; if (Files.notExists(jarPath)) { return NOT_FOUND; } // Get the version info next to the JAR Path updaterVersionPath = config.updaterBinDir.resolve("VERSION"); if (Files.notExists(updaterVersionPath)) { return NOT_FOUND; } try { byte[] data = Files.readAllBytes(updaterVersionPath); String versionData = new String(data, StandardCharsets.UTF_8); VersionHashPair pair = VersionHashPair.parse(versionData); // Verify hash byte[] hash = computeFileHash(jarPath); if (pair.areHashesEqual(new VersionHashPair(0, hash))) { return pair; } } catch (Exception ignored) { } return NOT_FOUND; } private VersionHashPair getRemoteUpdaterVersion() { try { URL patcherVersionURL = new URL(config.remoteUpdateBaseUrl + config.updaterProjectName + "/version"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(patcherVersionURL.openStream()))) { String vers = reader.readLine(); return VersionHashPair.parse(vers); } } catch (Exception ignored) { } return NOT_FOUND; } private void performUpdate(VersionHashPair remote) { } @Override protected void succeeded() { if (selfUpdateRequred) { onBootstrapSelfUpdateRequired.run(); } else { onBootstrapOk.accept(getValue()); } } @Override protected void failed() { onFailed.accept(errorMessage.orElseGet(this::getExceptionErrorMessage)); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private String getExceptionErrorMessage() { Throwable throwable = getException(); if (throwable != null) { return localeBundle.getString("bootstrap.splash.error.text.unexpected_exception") + " " + throwable.getClass().getSimpleName(); } else { return localeBundle.getString("bootstrap.splash.error.text.unexpected"); } } @Override protected void cancelled() { } private byte[] computeFileHash(Path path) throws IOException { sha256Digest.reset(); digestBuffer.rewind(); try (ByteChannel channel = Files.newByteChannel(path, READ)) { while (channel.read(digestBuffer) > -1) { digestBuffer.flip(); sha256Digest.update(digestBuffer); } } return sha256Digest.digest(); } }
Bootstrap/src/main/java/co/phoenixlab/dn/dngearsim/bootstrap/BootstrapTask.java
/* * The MIT License (MIT) * * Copyright (c) 2016 Vincent Zhang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package co.phoenixlab.dn.dngearsim.bootstrap; import co.phoenixlab.dn.dngearsim.utils.version.VersionHashPair; import co.phoenixlab.dn.dngearsim.utils.version.Versions; import javafx.concurrent.Task; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.NoSuchElementException; import java.util.Optional; import java.util.ResourceBundle; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static java.nio.file.StandardOpenOption.READ; public class BootstrapTask extends Task<BootstrapHandoff> { /** * Size of the buffer to use to read in the file for digesting */ private static final int DIGEST_BUFFER_SIZE = 8192; /** * Return result when the version-hashpair can't be retrieved */ private static final VersionHashPair NOT_FOUND = new VersionHashPair(); /** * Return result when the version can't be retrieved */ private static final int NOT_FOUND_I = 0; /** * Listener to call on successful load */ private final Consumer<BootstrapHandoff> onBootstrapOk; /** * Listener to call when the bootstrapper itself needs to be updated externally */ private final Runnable onBootstrapSelfUpdateRequired; /** * Whether or not the bootstrapper itself needs to be updated externally */ private volatile boolean selfUpdateRequred; /** * The MessageDigest using SHA-256 to use to hash */ private final MessageDigest sha256Digest; /** * Reusable buffer for computing digests */ private final ByteBuffer digestBuffer; /** * A custom error message to display on exceptions */ private Optional<String> errorMessage; /** * Handler to call when the task fails, with the failure reason */ private final Consumer<String> onFailed; /** * The ResourceBundle for localization strings */ private final ResourceBundle localeBundle; /** * Configuration for this bootstrap task */ private BootstrapConfig config; public BootstrapTask(Consumer<BootstrapHandoff> onBootstrapOk, Runnable onBootstrapSelfUpdateRequired, Consumer<String> onFailed, ResourceBundle localeBundle) { this.onBootstrapOk = onBootstrapOk; this.onBootstrapSelfUpdateRequired = onBootstrapSelfUpdateRequired; this.onFailed = onFailed; this.localeBundle = localeBundle; this.errorMessage = Optional.empty(); this.selfUpdateRequred = false; updateTitle("BootstrapTask"); try { sha256Digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { // This shouldn't happen, since SHA-256 MUST be present on all implementations of Java throw new AssertionError("MessageDigest.getInstance(SHA-256) should never throw NoSuchAlgorithmnExcepton"); } digestBuffer = ByteBuffer.allocateDirect(DIGEST_BUFFER_SIZE); } @Override protected BootstrapHandoff call() throws Exception { config = new BootstrapConfig(); if (doesBootstrapRequireUpdate()) { selfUpdateRequred = true; return null; } checkAndPerformUpdaterUpdate(); // TODO return null; } private boolean doesBootstrapRequireUpdate() throws Exception { updateMessage(localeBundle.getString("bootstrap.splash.text.checking_bootstrap")); TimeUnit.MILLISECONDS.sleep(500); int local = getLocalBootstrapVersion(); int remote = getLatestRemoteBootstrapVersion(); // This system does not perform a hashs check because the assumption is that if the bootstrap is not intact // then no guarantee can be made about the running code // Requires update if the remote version is greater than the local // Don't update if we can't get a response from the server return remote != NOT_FOUND_I && remote > local; } private int getLocalBootstrapVersion() { try (InputStream inputStream = getClass().getResourceAsStream("/co/phoenixlab/dn/dngearsim/bootstrap/version")) { Scanner scanner = new Scanner(inputStream); scanner.useDelimiter(";"); String versionStr = scanner.next(); String compileTime = scanner.next(); return Versions.parseVersion(versionStr); } catch (IOException | NumberFormatException | NoSuchElementException exception) { return NOT_FOUND_I; } } private int getLatestRemoteBootstrapVersion() { // TODO return NOT_FOUND_I; } private void checkAndPerformUpdaterUpdate() throws Exception { updateMessage(localeBundle.getString("bootstrap.splash.text.checking_updater")); TimeUnit.MILLISECONDS.sleep(500); VersionHashPair local = getLocalUpdaterVersion(); VersionHashPair remote = getRemoteUpdaterVersion(); // Check if we got a remote version, if not then we obviously cant update // If we don't have an existing updater or the existing updater was corrupted or is an older version, then // perform an update // And if we can't do either, we're screwed if (remote == NOT_FOUND && local == NOT_FOUND) { errorMessage = Optional.of(localeBundle.getString("bootstrap.splash.error.text.no_updater")); throw new Exception(); } if (remote.isVersionHigherThan(local) || (remote.areVersionsEqual(local) && !remote.areHashesEqual(local))) { performUpdate(remote); } else { updateMessage(localeBundle.getString("bootstrap.splash.text.updater_ok")); TimeUnit.MILLISECONDS.sleep(500); } } private VersionHashPair getLocalUpdaterVersion() { // Find the JAR Path jarPath = config.updaterJarPath; if (Files.notExists(jarPath)) { return NOT_FOUND; } // Get the version info next to the JAR Path updaterVersionPath = config.updaterBinDir.resolve("VERSION"); if (Files.notExists(updaterVersionPath)) { return NOT_FOUND; } try { byte[] data = Files.readAllBytes(updaterVersionPath); String versionData = new String(data, StandardCharsets.UTF_8); VersionHashPair pair = VersionHashPair.parse(versionData); // Verify hash byte[] hash = computeFileHash(jarPath); if (pair.areHashesEqual(new VersionHashPair(0, hash))) { return pair; } } catch (Exception ignored) { } return NOT_FOUND; } private VersionHashPair getRemoteUpdaterVersion() { try { URL patcherVersionURL = new URL(config.remoteUpdateBaseUrl + config.updaterProjectName + "/VERSION"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(patcherVersionURL.openStream()))) { String vers = reader.readLine(); return VersionHashPair.parse(vers); } } catch (Exception ignored) { } return NOT_FOUND; } private void performUpdate(VersionHashPair remote) { } @Override protected void succeeded() { if (selfUpdateRequred) { onBootstrapSelfUpdateRequired.run(); } else { onBootstrapOk.accept(getValue()); } } @Override protected void failed() { onFailed.accept(errorMessage.orElseGet(this::getExceptionErrorMessage)); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private String getExceptionErrorMessage() { Throwable throwable = getException(); if (throwable != null) { return localeBundle.getString("bootstrap.splash.error.text.unexpected_exception") + " " + throwable.getClass().getSimpleName(); } else { return localeBundle.getString("bootstrap.splash.error.text.unexpected"); } } @Override protected void cancelled() { } private byte[] computeFileHash(Path path) throws IOException { sha256Digest.reset(); digestBuffer.rewind(); try (ByteChannel channel = Files.newByteChannel(path, READ)) { while (channel.read(digestBuffer) > -1) { digestBuffer.flip(); sha256Digest.update(digestBuffer); } } return sha256Digest.digest(); } }
Fix incorrect casing for version URL
Bootstrap/src/main/java/co/phoenixlab/dn/dngearsim/bootstrap/BootstrapTask.java
Fix incorrect casing for version URL
<ide><path>ootstrap/src/main/java/co/phoenixlab/dn/dngearsim/bootstrap/BootstrapTask.java <ide> <ide> private VersionHashPair getRemoteUpdaterVersion() { <ide> try { <del> URL patcherVersionURL = new URL(config.remoteUpdateBaseUrl + config.updaterProjectName + "/VERSION"); <add> URL patcherVersionURL = new URL(config.remoteUpdateBaseUrl + config.updaterProjectName + "/version"); <ide> try (BufferedReader reader = new BufferedReader(new InputStreamReader(patcherVersionURL.openStream()))) { <ide> String vers = reader.readLine(); <ide> return VersionHashPair.parse(vers);
Java
epl-1.0
3cf9f7edef9d77c9647ca6fb0fd69c60e3b99927
0
bpsm/edn-java
// (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License package us.bpsm.edn; import java.io.Serializable; /** * A Tagged value that received no specific handling because the Parser * was not configured with a handler for its tag. */ public final class TaggedValue implements Serializable { private final Tag tag; private final Object value; private TaggedValue(Tag tag, Object value) { this.tag = tag; this.value = value; } /** * Return a tagged value for the given tag and value (some edn data). * The tag must not be null. * @param tag not null. * @param value may be null. * @return a TaggedValue, never null. */ public static TaggedValue newTaggedValue(Tag tag, Object value) { if (tag == null) { throw new IllegalArgumentException("tag must not be null"); } return new TaggedValue(tag, value); } /** * Returns this TaggedValue's tag, which is never null. * @return never null. */ public Tag getTag() { return tag; } public Object getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + tag.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TaggedValue other = (TaggedValue) obj; if (!tag.equals(other.tag)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } @Override public String toString() { return tag + " " + value; } }
src/main/java/us/bpsm/edn/TaggedValue.java
// (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License package us.bpsm.edn; /** * A Tagged value that received no specific handling because the Parser * was not configured with a handler for its tag. */ public final class TaggedValue { private final Tag tag; private final Object value; private TaggedValue(Tag tag, Object value) { this.tag = tag; this.value = value; } /** * Return a tagged value for the given tag and value (some edn data). * The tag must not be null. * @param tag not null. * @param value may be null. * @return a TaggedValue, never null. */ public static TaggedValue newTaggedValue(Tag tag, Object value) { if (tag == null) { throw new IllegalArgumentException("tag must not be null"); } return new TaggedValue(tag, value); } /** * Returns this TaggedValue's tag, which is never null. * @return never null. */ public Tag getTag() { return tag; } public Object getValue() { return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + tag.hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TaggedValue other = (TaggedValue) obj; if (!tag.equals(other.tag)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } @Override public String toString() { return tag + " " + value; } }
43: TaggedValue is now Serializable This depends on the fact that the TaggedValue's Value be Serializable, which exactly what this set of changes accomplishes.
src/main/java/us/bpsm/edn/TaggedValue.java
43: TaggedValue is now Serializable
<ide><path>rc/main/java/us/bpsm/edn/TaggedValue.java <ide> // (c) 2012 B Smith-Mannschott -- Distributed under the Eclipse Public License <ide> package us.bpsm.edn; <add> <add>import java.io.Serializable; <ide> <ide> /** <ide> * A Tagged value that received no specific handling because the Parser <ide> * was not configured with a handler for its tag. <ide> */ <del>public final class TaggedValue { <add>public final class TaggedValue implements Serializable { <ide> private final Tag tag; <ide> private final Object value; <ide>
Java
mit
1a7d7d207bb8df066d47b73de26661bbe049cbda
0
kzantow/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,kzantow/blueocean-plugin,kzantow/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,kzantow/blueocean-plugin
package io.jenkins.blueocean.rest.impl.pipeline.credential; import com.cloudbees.plugins.credentials.CredentialsStoreAction; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.domains.DomainSpecification; import com.google.common.collect.ImmutableList; import hudson.model.User; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.credential.CredentialsUtils; import io.jenkins.blueocean.rest.Navigable; import io.jenkins.blueocean.rest.Reachable; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.Container; import io.jenkins.blueocean.rest.model.CreateResponse; import io.jenkins.blueocean.rest.model.Resource; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.json.JsonBody; import org.kohsuke.stapler.verb.POST; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * Credential API implementation. * * TODO: Remove it once proper REST API is implemented in Credentials plugin * * @author Vivek Pandey */ public class CredentialApi extends Resource { private final CredentialsStoreAction credentialStoreAction; private final Reachable parent; public static final String DOMAIN_NAME = "blueocean-domain"; public CredentialApi(CredentialsStoreAction ca, Reachable parent) { this.credentialStoreAction = ca; this.parent = parent; } @Exported public String getStore(){ return credentialStoreAction.getUrlName(); } @POST @WebMethod(name = "") public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No authenticated user found"); } JSONObject jsonObject = body.getJSONObject("credentials"); final IdCredentials credentials = request.bindJSON(IdCredentials.class, jsonObject); String domainName = DOMAIN_NAME; if(jsonObject.get("domain") != null && jsonObject.get("domain") instanceof String){ domainName = (String) jsonObject.get("domain"); } CredentialsUtils.createCredentialsInUserStore(credentials, authenticatedUser, domainName, ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification())); CredentialsStoreAction.DomainWrapper domainWrapper = credentialStoreAction.getDomain(domainName); if(domainWrapper != null) { CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(credentials.getId()); if (credentialsWrapper != null){ return new CreateResponse( new CredentialApi.Credential( credentialsWrapper, getLink().rel("domains").rel(domainName).rel("credentials"))); } } //this should never happen throw new ServiceException.UnexpectedErrorException("Unexpected error, failed to create credential"); } @Navigable public Container<CredentialDomain> getDomains(){ return new Container<CredentialDomain>() { private final Link self = CredentialApi.this.getLink().rel("domains"); Map<String, CredentialsStoreAction.DomainWrapper> map = credentialStoreAction.getDomains(); @Override public CredentialDomain get(String name) { return new CredentialDomain(map.get(name), getLink()); } @Override public Link getLink() { return self; } @Override public Iterator<CredentialDomain> iterator() { final Iterator<CredentialsStoreAction.DomainWrapper> i = map.values().iterator(); return new Iterator<CredentialDomain>(){ @Override public boolean hasNext() { return i.hasNext(); } @Override public CredentialDomain next() { return new CredentialDomain(i.next(), getLink()); } @Override public void remove() { throw new ServiceException.NotImplementedException("Not implemented yet"); } }; } }; } @Override public Link getLink() { return parent.getLink().rel(getStore()); } public static class CredentialDomain extends Resource{ private final Link self; private final CredentialsStoreAction.DomainWrapper domainWrapper; public CredentialDomain(CredentialsStoreAction.DomainWrapper domainWrapper, Link parent) { this.self = parent.rel(domainWrapper.getUrlName()); this.domainWrapper = domainWrapper; } @Exported(inline = true, merge = true) public CredentialsStoreAction.DomainWrapper getDomain(){ return domainWrapper; } @Override public Link getLink() { return self; } @Navigable public CredentialValueContainer getCredentials(){ return new CredentialValueContainer(domainWrapper, this); } } public static class CredentialValueContainer extends Container<Credential>{ private final CredentialsStoreAction.DomainWrapper domainWrapper; private final Link self; public CredentialValueContainer(CredentialsStoreAction.DomainWrapper domainWrapper, Reachable parent) { this.domainWrapper = domainWrapper; this.self = parent.getLink().rel("credentials"); } @Override public Credential get(String name) { CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(name); if(credentialsWrapper != null) { return new Credential(credentialsWrapper, self); } throw new ServiceException.NotFoundException(String.format("Credential %s not found in domain %s", name, domainWrapper.getFullName())); } @POST @WebMethod(name = "") @Deprecated public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { final IdCredentials credentials = request.bindJSON(IdCredentials.class, body.getJSONObject("credentials")); domainWrapper.getStore().addCredentials(domainWrapper.getDomain(), credentials); final Domain domain = domainWrapper.getDomain(); domainWrapper.getStore().addCredentials(domain, credentials); return new CreateResponse(new Credential(domainWrapper.getCredentials().get(credentials.getId()), getLink())); } @Override public Link getLink() { return self; } @Override public Iterator<Credential> iterator() { final Iterator<CredentialsStoreAction.CredentialsWrapper> i = domainWrapper.getCredentialsList().iterator(); return new Iterator<Credential>(){ @Override public boolean hasNext() { return i.hasNext(); } @Override public Credential next() { return new Credential(i.next(),self); } @Override public void remove() { throw new ServiceException.NotImplementedException("Not implemented yet"); } }; } } public static class Credential extends Resource{ private final Link self; private final CredentialsStoreAction.CredentialsWrapper credentialsWrapper; public Credential(CredentialsStoreAction.CredentialsWrapper credentialsWrapper, Link parent) { this.self = parent.rel(credentialsWrapper.getUrlName()); this.credentialsWrapper = credentialsWrapper; } @Exported(merge = true, inline = true) public CredentialsStoreAction.CredentialsWrapper getCredential(){ return credentialsWrapper; } @Override public Link getLink() { return self; } @Exported public String getDomain(){ return credentialsWrapper.getDomain().getUrlName(); } /** * If description is empty its displayName:domain:type, otherwise just the given description name */ @Exported public String getDescription(){ if(credentialsWrapper.getDescription() == null || credentialsWrapper.getDescription().trim().isEmpty()){ return String.format("%s:%s:%s",credentialsWrapper.getDisplayName(),credentialsWrapper.getDomain().getUrlName(), credentialsWrapper.getTypeName()); } return credentialsWrapper.getDescription(); } } }
blueocean-pipeline-api-impl/src/main/java/io/jenkins/blueocean/rest/impl/pipeline/credential/CredentialApi.java
package io.jenkins.blueocean.rest.impl.pipeline.credential; import com.cloudbees.plugins.credentials.CredentialsStoreAction; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.domains.DomainSpecification; import com.google.common.collect.ImmutableList; import hudson.model.User; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.credential.CredentialsUtils; import io.jenkins.blueocean.rest.Navigable; import io.jenkins.blueocean.rest.Reachable; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.Container; import io.jenkins.blueocean.rest.model.CreateResponse; import io.jenkins.blueocean.rest.model.Resource; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.json.JsonBody; import org.kohsuke.stapler.verb.POST; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * Credential API implementation. * * TODO: Remove it once proper REST API is implemented in Credentials plugin * * @author Vivek Pandey */ public class CredentialApi extends Resource { private final CredentialsStoreAction credentialStoreAction; private final Reachable parent; public static final String DOMAIN_NAME = "blueocean-domain"; public CredentialApi(CredentialsStoreAction ca, Reachable parent) { this.credentialStoreAction = ca; this.parent = parent; } @Exported public String getStore(){ return credentialStoreAction.getUrlName(); } @POST @WebMethod(name = "") public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No authenticated user found"); } JSONObject jsonObject = body.getJSONObject("credentials"); final IdCredentials credentials = request.bindJSON(IdCredentials.class, jsonObject); String domainName = DOMAIN_NAME; if(jsonObject.get("domain") != null && jsonObject.get("domain") instanceof String){ domainName = (String) jsonObject.get("domain"); } CredentialsUtils.createCredentialsInUserStore(credentials, authenticatedUser, domainName, ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification())); CredentialsStoreAction.DomainWrapper domainWrapper = credentialStoreAction.getDomain(domainName); if(domainWrapper != null) { CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(credentials.getId()); if (credentialsWrapper != null){ return new CreateResponse( new CredentialApi.Credential( credentialsWrapper, getLink().rel("domains").rel(domainName).rel("credentials"))); } } //this should never happen throw new ServiceException.UnexpectedErrorException("Unexpected error, failed to create credential"); } @Navigable public Container<CredentialDomain> getDomains(){ return new Container<CredentialDomain>() { private final Link self = CredentialApi.this.getLink().rel("domains"); Map<String, CredentialsStoreAction.DomainWrapper> map = credentialStoreAction.getDomains(); @Override public CredentialDomain get(String name) { return new CredentialDomain(map.get(name), getLink()); } @Override public Link getLink() { return self; } @Override public Iterator<CredentialDomain> iterator() { final Iterator<CredentialsStoreAction.DomainWrapper> i = map.values().iterator(); return new Iterator<CredentialDomain>(){ @Override public boolean hasNext() { return i.hasNext(); } @Override public CredentialDomain next() { return new CredentialDomain(i.next(), getLink()); } @Override public void remove() { throw new ServiceException.NotImplementedException("Not implemented yet"); } }; } }; } @Override public Link getLink() { return parent.getLink().rel(getStore()); } public static class CredentialDomain extends Resource{ private final Link self; private final CredentialsStoreAction.DomainWrapper domainWrapper; public CredentialDomain(CredentialsStoreAction.DomainWrapper domainWrapper, Link parent) { this.self = parent.rel(domainWrapper.getUrlName()); this.domainWrapper = domainWrapper; } @Exported(inline = true, merge = true) public CredentialsStoreAction.DomainWrapper getDomain(){ return domainWrapper; } @Override public Link getLink() { return self; } @Navigable public CredentialValueContainer getCredentials(){ return new CredentialValueContainer(domainWrapper, this); } } public static class CredentialValueContainer extends Container<Credential>{ private final CredentialsStoreAction.DomainWrapper domainWrapper; private final Link self; public CredentialValueContainer(CredentialsStoreAction.DomainWrapper domainWrapper, Reachable parent) { this.domainWrapper = domainWrapper; this.self = parent.getLink().rel("credentials"); } @Override public Credential get(String name) { CredentialsStoreAction.CredentialsWrapper credetialsWrapper = domainWrapper.getCredential(name); if(credetialsWrapper != null) { return new Credential(credetialsWrapper, self); } throw new ServiceException.NotFoundException(String.format("Credential %s not found in domain %s", name, domainWrapper.getFullName())); } @POST @WebMethod(name = "") @Deprecated public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { final IdCredentials credentials = request.bindJSON(IdCredentials.class, body.getJSONObject("credentials")); domainWrapper.getStore().addCredentials(domainWrapper.getDomain(), credentials); final Domain domain = domainWrapper.getDomain(); domainWrapper.getStore().addCredentials(domain, credentials); return new CreateResponse(new Credential(domainWrapper.getCredentials().get(credentials.getId()), getLink())); } @Override public Link getLink() { return self; } @Override public Iterator<Credential> iterator() { final Iterator<CredentialsStoreAction.CredentialsWrapper> i = domainWrapper.getCredentialsList().iterator(); return new Iterator<Credential>(){ @Override public boolean hasNext() { return i.hasNext(); } @Override public Credential next() { return new Credential(i.next(),self); } @Override public void remove() { throw new ServiceException.NotImplementedException("Not implemented yet"); } }; } } public static class Credential extends Resource{ private final Link self; private final CredentialsStoreAction.CredentialsWrapper credentialsWrapper; public Credential(CredentialsStoreAction.CredentialsWrapper credentialsWrapper, Link parent) { this.self = parent.rel(credentialsWrapper.getUrlName()); this.credentialsWrapper = credentialsWrapper; } @Exported(merge = true, inline = true) public CredentialsStoreAction.CredentialsWrapper getCredential(){ return credentialsWrapper; } @Override public Link getLink() { return self; } @Exported public String getDomain(){ return credentialsWrapper.getDomain().getUrlName(); } /** * If description is empty its displayName:domain:type, otherwise just the given description name */ @Exported public String getDescription(){ if(credentialsWrapper.getDescription() == null || credentialsWrapper.getDescription().trim().isEmpty()){ return String.format("%s:%s:%s",credentialsWrapper.getDisplayName(),credentialsWrapper.getDomain().getUrlName(), credentialsWrapper.getTypeName()); } return credentialsWrapper.getDescription(); } } }
spelling: credential
blueocean-pipeline-api-impl/src/main/java/io/jenkins/blueocean/rest/impl/pipeline/credential/CredentialApi.java
spelling: credential
<ide><path>lueocean-pipeline-api-impl/src/main/java/io/jenkins/blueocean/rest/impl/pipeline/credential/CredentialApi.java <ide> <ide> @Override <ide> public Credential get(String name) { <del> CredentialsStoreAction.CredentialsWrapper credetialsWrapper = domainWrapper.getCredential(name); <del> if(credetialsWrapper != null) { <del> return new Credential(credetialsWrapper, self); <add> CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(name); <add> if(credentialsWrapper != null) { <add> return new Credential(credentialsWrapper, self); <ide> } <ide> throw new ServiceException.NotFoundException(String.format("Credential %s not found in domain %s", name, <ide> domainWrapper.getFullName()));
JavaScript
mit
2e4ba6b8810ce2f9ece2b77a8b17b5f9e1a3389f
0
ultratype/UltraTypeBot,ultratype/UltraTypeBot,ultratype/UltraTypeBot
(() => { // Constants const VERSION = "2.5.0", LOG_DEBUG = true, LOG_TYPING_INFO = false, DO_BAN_CHECK = true, LOAD_TIME = 4300, TURBO_PACKET_COUNT = 5, TURBO_PACKET_IDX = 1500, MAX_WPM = 999, EXT_URL = `https://chrome.google.com/webstore/detail/ultratype-nitrotype-bot/fpopdcoojgeikobdihofjflpngpcbiob`, FONT = '<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">', // lib gen = (min, max) => { return Math.floor(Math.random() * max) + min; }, ROTn = (text, map) => { let out = '', len = map.length; for(let i = 0; i < text.length; i++) { let c = text.charAt(i), j = map.indexOf(c); if (j >= 0) { c = map.charAt((j + len / 2) % len); } out += c; } return out; }, ROT47 = text => ROTn(text, "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"); let _title = "Nitro Type Race", accuracy = gen(0.93, 0.97), root, autoRefresh = false, enabled = true, autoNitroBtn = null, disqualified = false, lessonLoaded = false, finished = false, timeoutToggle = false, inDip = false, autoNitro = false, info, ws = null, infoSpan, injectedRoot, fillsY = [], points = [], errorRequests = [], lesson = "", packetLesson = "", opt, optOn = false, renderedKeys = 0, i = 0, chart, g = document.createElement('div'), timeout = 0, toggled = false, firstDetected = false, startTime = null, endTime = null, wordsPerMinute = gen(80, 105), username = "", avgSpeed = 100, acc = null, wpm = null, statsDiv = null, statsOn = true, userInfo = {}, statTogg = null, index = 0, nitrosUsed = 0, loggedEndRace = false, userBanned = false, firstTurbo = false, isStopped = false, autoTurbo = localStorage['autoTurbo']; if (!autoTurbo) { autoTurbo = false; } else { autoTurbo = JSON.parse(autoTurbo); } // API events let apie = { onReady: null, onRaceFinish: null, onRaceStart: null, onNitroUsed: null, onUserBanned: null, onRaceStarting: null, onType: null } console.clear = (function() {}); const type = charCode => { index++; $(document.body).trigger({ type: 'keypress', which: charCode }); }, overrideOnError = () => { window.onerror = evt => { if (evt.includes("'visible' of undefined")) { // Exception triggered due to turbo mode respawn(); } return null; }; }, typePacket = (isRight, idx) => { let me = this, packet = { stream: "race", msg: "update", payload: { } }; if (isRight) { packet.payload.t = idx; } else { packet.payload.e = idx; } ws.send("4" + JSON.stringify(packet)); }, turbo = () => { debug("Turbo mode called. Sending " + (TURBO_PACKET_COUNT.toString()) + " type packets."); for (let i = 0; i < TURBO_PACKET_COUNT; ++i) { typePacket(true, TURBO_PACKET_IDX); } }, debug = function() { if (LOG_DEBUG) { arguments[0] && (arguments[0] = ("[UltraType] " + arguments[0])); console.trace.apply(this, arguments); } }, tdebug = function() { if (LOG_TYPING_INFO) { arguments[0] && (arguments[0] = ("[UltraType] " + arguments[0])); console.log.apply(this, arguments); } }, useNitro = () => { if (apie.onNitroUsed) apie.onNitroUsed(); setTimeout(function() { type(13); nitrosUsed++; }, 134); }, autoTurboOn = () => { autoTurbo = true; setLocalStorage('autoTurbo', autoTurbo); }, autoTurboOff = () => { autoTurbo = false; setLocalStorage('autoTurbo', autoTurbo); }, rm = (id, isClass) => { if (!isClass) { document.getElementById(id).remove(); } else { let elms = document.getElementsByClassName(id); for (let i = 0; i < elms.length; ++i) { elms[i].remove(); } } }, addGraph = g => { if (isStopped) return; if (root) { let _style = $("<style>.highcharts-container{width:100% !important;height:100% !important;display:inline-block;}</style>"); root.appendChild(_style[0]); root.appendChild(g); } else if (document.body) { // Fallback let _style = $("<style>.highcharts-container{width:100% !important;height:100% !important;display:inline-block;}</style>"); root.appendChild(_style[0]); document.body.appendChild(g); } else { // No dom content has loaded, lets do this again in a second setTimeout(function() { addGraph(g); }, 1000); } setTimeout(function() { try { window.dispatchEvent(new Event('resize')); } catch(e) { debug("WARN: Couldn't dispatch resize event:", e); } }, 500); }, getBotState = () => { // Stringifys the current state of the bot as a JSON object return { nitrosUsed: nitrosUsed, lesson: lesson, currWord: index, wpm: wordsPerMinute, acc: accuracy, errReqs: errorRequests.length, uinfo: JSON.stringify(userInfo), fillsY: fillsY.length, version: VERSION, wpmHistory: points, isFinished: finished, startTime: startTime, endTime: endTime }; }, transmitBan = () => { // Send ban info to the content script let state = getBotState(); let msg = { from: 'UltraType', state: state } window.postMessage(msg, location.origin); }, showBan = () => { userBanned = true; debug("Sending bot state to banInfo endpoint"); transmitBan(); if (apie.onUserBanned) { apie.onUserBanned(); } return; }, checkIfBanned = callback => { if (userInfo.username) { debug("Attempting to get user's page"); let xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.nitrotype.com/racer/" + encodeURIComponent(userInfo.username), true); xhr.send(); xhr.onload = () => { let status = this.status; let res = this.responseText; if (status !== 200 || (res.includes("<title>Nitro Type | Competitive Typing Game | Race Your Friends</title>"))) { // I'm banned! showBan(); } else { // Everything normal callback(); } } // Errors aren't very nice xhr.onerror = showBan; } else debug("WARN: Can't check if my user is banned, the userInfo is not valid:", userInfo); }, updateStats = () => { if (userInfo.username) { statsDiv.innerHTML = ""; statsDiv.style.color = "white"; statsDiv.style.display = 'inline-block'; let st = document.createElement('span'); let sname = document.createElement('span'); sname.textContent = userInfo.username; sname.style.color = 'red'; st.textContent = "Stats for user "; st.appendChild(sname); statsDiv.appendChild(st); statsDiv.appendChild(document.createElement('br')); statsDiv.appendChild(document.createElement('br')); let statTitle = document.createElement('span'); let stt = document.createElement('span'); stt.textContent = userInfo.title; stt.style.color = 'blue'; statTitle.textContent = "Title: "; statTitle.appendChild(stt); statsDiv.appendChild(statTitle); statsDiv.appendChild(document.createElement('br')); if (userInfo.tag !== '') { let statTeam = document.createElement('span'); statTeam.textContent = 'Team: '; let sTeam = document.createElement('span'); if (userInfo.tagColor) sTeam.style.color = userInfo.tagColor; sTeam.textContent = userInfo.tag; statTeam.appendChild(sTeam); statsDiv.appendChild(statTeam); statsDiv.appendChild(document.createElement('br')); } let statNitro = document.createElement('span'); let sn = document.createElement('span'); sn.textContent = userInfo.nitros; sn.style.color = 'blue'; statNitro.textContent = "Total nitros: "; statNitro.appendChild(sn); statsDiv.appendChild(statNitro); statsDiv.appendChild(document.createElement('br')); let statMoney = document.createElement('span'); let stm1 = document.createElement('span'); stm1.textContent = "$" + userInfo.money + " (Spent: $" + userInfo.moneySpent + ")"; stm1.style.color = 'blue'; statMoney.textContent = 'Money: '; statMoney.appendChild(stm1); statsDiv.appendChild(statMoney); statsDiv.appendChild(document.createElement('br')); let statMember = document.createElement('span'); let sm = document.createElement('span'); sm.textContent = (userInfo.membership !== 'basic'); sm.style.color = 'blue'; statMember.textContent = 'Gold Membership: '; statMember.appendChild(sm); statsDiv.appendChild(statMember); statsDiv.appendChild(document.createElement('br')); let statRaces = document.createElement('span'); let sr = document.createElement('span'); sr.style.color = 'blue'; sr.textContent = userInfo.racesPlayed; statRaces.textContent = 'Total races played: '; statRaces.appendChild(sr); statsDiv.appendChild(statRaces); statsDiv.appendChild(document.createElement('br')); let statWins = document.createElement('span'); let sw = document.createElement('span'); sw.textContent = userInfo.consecWins; sw.style.color = 'blue'; statWins.textContent = 'Consecutive wins: '; statWins.appendChild(sw); statsDiv.appendChild(statWins); statsDiv.appendChild(document.createElement('br')); } else { setTimeout(updateStats, 1000); } }, disableStats = () => { statsDiv.innerHTML = ""; }, __ = {}, _ = { fill: window.CanvasRenderingContext2D.prototype.fillText, toStr: window.Function.prototype.toString, get: window.Object.prototype.__lookupGetter__, listen: window.addEventListener, unlisten: window.removeEventListener, reload: window.location.reload, host: ShadowRoot.prototype.__lookupGetter__('host'), fp: Function.prototype, warn: console.warn, ws: window.WebSocket, xsend: window.XMLHttpRequest.prototype.send, xopen: window.XMLHttpRequest.prototype.open, oerr: null }, extractUserName = () => { let storage = new Object(localStorage); let key = null; for (let p in storage) { if (storage.hasOwnProperty(p)) { try { key = JSON.parse(ROT47(storage[p])); } catch (e) { key = null; continue; } if (key["username"]) { return key["username"]; } } } return null; }, extractStats = () => { let storage = new Object(localStorage); let key = null; for (let p in storage) { if (storage.hasOwnProperty(p)) { try { key = JSON.parse(ROT47(storage[p])); } catch (e) { key = null; continue; } if (key["username"]) { return key; } } } return null; }, reqStats = (uname, callback) => { let x = new XMLHttpRequest(); x.open("GET", "https://www.nitrotype.com/racer/" + uname, true); x.send(); x.onload = () => { callback(x.responseText); } }, setWPM = w => { if (isStopped)return; wordsPerMinute = w; wpm.value = w; setLocalStorage('wpm', w); }, autoNitroOn = () => { autoNitroBtn.style.borderColor = "LimeGreen"; autoNitroBtn.style.color = "LimeGreen"; autoNitroBtn.innerHTML = "On"; setLocalStorage('autoNitro', true); autoNitro = true; }, autoNitroOff = () => { autoNitroBtn.style.borderColor = "Red"; autoNitroBtn.style.color = "Red"; autoNitroBtn.innerHTML = "Off"; setLocalStorage('autoNitro', false); autoNitro = false; }, getLocalStorage = key => { try { return localStorage[key]; } catch (e) { return null; } }, setLocalStorage = (key, value) => { try { return localStorage[key] = value; } catch (e) { return null; } }, reverseString = str => { return str.split``.reverse().join``; }, decryptLesson = lesson => { return reverseString(ROT47(lesson)); }, __ws = function(ip, protocol) { ws = new _.ws(ip, protocol); ws.addEventListener('message', msg => { // console.debug('recieved', msg.data); let validPacket = true; let packet = {}; if (msg.data) { try { packet = JSON.parse(msg.data.substring(1, msg.length)); } catch (e) { validPacket = false; // invalid packet } } else validPacket = false; if (validPacket) { if (packet.msg == "error") { respawn(); } else if (packet.stream == "race") { if (packet.msg == "status") { if (packet.payload.status == "countdown" && packet.payload.l) { let _lesson = packet.payload.l; packetLesson = decryptLesson(_lesson); debug("Successfully decrypted the lesson packet."); } } } } }); return ws; }, tgen = val => { max = val + 17; min = val - 17; let rand = 0; for (let i = 0; i < 6; i += 1) { rand += Math.random(); } return Math.ceil((((rand - 3) / 3) * (max - min)) + min); }, handleFillText = args => { const text = args[0]; if (text.length < 2) { renderedKeys++; fillsY.push(args[2]); // A space needs to be appended to the lesson if (fillsY[fillsY.length - 1] < fillsY[fillsY.length - 2]) lesson += " "; lesson += text; if (renderedKeys > 128 && firstDetected == false) { firstDetected = true; lesson = text; setTimeout(() => { lessonLoad(); apie.onRaceStarting && (apie.onRaceStarting()); }, 200); } } }, randomBool = percentFalse => { let percent = 0.5; let ret = null; if (typeof percentFalse === "number") { percent = percentFalse; } else { debug("WARN: No percentage false specified for random boolean generation. Using 0.5."); } ret = Math.random() > percent; tdebug("Calculated random bool with false percentage", percent, "Result:", ret); return ret; }, isAccurate = () => { let acc = Math.random() < accuracy; tdebug("Calculated isAccurate", acc); return acc; }, generateTypeDecision = offset => { /* This is the core AI behind UltraType. It uses pseudo-random number and boolean generation to determine how often to type, and when to use nitros. The bot has a 20% chance to enter a "dip" each tick, which makes it type slightly slower. */ if(isStopped) return; setTimeout(() => { let dipRate = 0.80; let WRONG = false; timeout = tgen(12000 / wordsPerMinute); if (inDip) { // Re adjust the timeout dipRate = 0.40; timeout = tgen(12000 / wordsPerMinute); } if (enabled) { if (!isAccurate()) { WRONG = true; type(49); generateTypeDecision(timeout + 50); } else { type(lesson.charCodeAt(i)); } if (!WRONG) { i++; if (i < lesson.length) { generateTypeDecision(timeout); } } if (autoNitro) { if (randomBool(0.999)) { // Theres a 0.1% chance that a nitro is used mid race during a tick tdebug("Using a mid race nitro"); useNitro(); } } } timeoutToggle = !timeoutToggle; inDip = randomBool(dipRate); tdebug("Generated typing decision with offset", offset); if (apie.onType) { apie.onType({ charTyped: lesson.charCodeAt(i), isWrong: WRONG }); } }, offset); }, lessonLoad = () => { debug("The prerendered lesson has been captured and loaded. Starting in " + (LOAD_TIME / 1000) + " seconds."); if (!isStopped) { infoSpan.innerHTML = "Starting..."; infoSpan.style.color = "#00b300"; } setTimeout(() => { if (!isStopped) { infoSpan.innerHTML = "Started!"; infoSpan.style.color = "#33ff33"; } lessonLoaded = true; startTime = new Date(); if (lesson.length > 1) { generateTypeDecision(); debug("Started the bot!"); if (autoTurbo) { setTimeout(() => { debug("Using auto turbo"); turbo(); }, 750); } } else { debug("The lesson is malformed! Lesson:", ('"' + lesson + '"')); return; } if (apie.onRaceStart) { apie.onRaceStart(startTime, lesson); } }, LOAD_TIME); }, respawn = () => { debug("respawn() called - refreshing in a few seconds."); setTimeout(location.reload.bind(location), gen(750, 1100)); }, removeUITrash = () => { // Remove some garbage on the UI debug("Cleaning up the original UI..."); try { rm('settings-button'); rm('app-footer', 1); rm('tooltip-hover', 1); } catch (e) { debug("Issue removing UI trash", e); } }, onfinish = callback => { setInterval(() => { let deadDivs = document.getElementsByClassName('popup race-results'), banner = document.getElementsByClassName('banner'), errorDivs = document.getElementsByClassName('popup popup-race-error'); if ( (deadDivs && deadDivs.length > 0) || (disqualified) || (banner && banner.length > 0) || (errorDivs && errorDivs.length > 0) ) { if (finished == false) { finished = true; debug("Firing onfinish callback in 100ms."); setTimeout(callback.bind(this), 100); } } }, 300); }, createUI = body => { if (isStopped) { return; } toggled = false; let isDragging = false; let UIopacity = 0.7; let doc = document.querySelector('html'); let inner = document.querySelector('.wrap'); injectedRoot = document.createElement('div'); body.appendChild(injectedRoot); root = injectedRoot.createShadowRoot(); let UI = document.createElement('div'); $(root).append(FONT); Object.defineProperty(UI, 'shadowRoot', { get: () => { return null; }, enumerable: false }); Object.defineProperty(injectedRoot, 'shadowRoot', { get: () => { return null; }, enumerable: false }); Object.defineProperty(root, 'shadowRoot', { get: () => { return null; }, enumerable: false }); UI.style.zIndex = 999999; UI.id = "botUI"; UI.style.position = "fixed"; UI.style.top = "3%"; UI.style.left = "3%"; UI.style.color = "white"; UI.style.borderStyle = "solid"; UI.style.borderColor = "#000066"; UI.style.borderWidth = "6px"; UI.style.borderRadius = "7px"; UI.style.padding = "10px"; UI.style.backgroundColor = "black"; UI.style.textAlign = "center"; UI.style.opacity = UIopacity; UI.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; UI.style.fontFamily = "'Ubuntu', sans-serif"; UI.onmouseover = () => { UIopacity = 1; UI.style.opacity = UIopacity; } UI.onmouseleave = () => { UIopacity = 0.7; UI.style.opacity = UIopacity; } let outerTitle = document.createElement('center'); let title = document.createElement('p'); title.style.fontSize = "135%"; title.innerHTML = "<strong>UltraType 2</strong>"; title.style.cursor = 'pointer'; title.onclick = () => { window.open(EXT_URL,'_blank'); } UI.style.fontSize = "135%"; outerTitle.appendChild(title); UI.appendChild(outerTitle); let outerInfo = document.createElement('center'); info = document.createElement('p'); infoSpan = document.createElement('span'); infoSpan.innerHTML = "Idle."; infoSpan.style.color = "#b3b3b3"; infoSpan.style.transition = "color 500ms"; info.style.fontSize = "100%"; info.innerHTML += "Status: "; info.appendChild(infoSpan); outerInfo.appendChild(info); UI.appendChild(outerInfo); let outerEnable = document.createElement('center'); let enableButton = document.createElement('button'); enableButton.className = ""; enableButton.style.backgroundColor = "transparent"; enableButton.style.border = "3px solid"; enableButton.style.borderRadius = "3px"; enableButton.style.fontSize = "125%"; enableButton.style.borderColor = "#808080"; enableButton.style.color = "#808080"; enableButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; enableButton.innerHTML = "Customize"; enableButton.onclick = () => { if (!optOn) { optOn = true; opt.style.opacity = 0.95; opt.style.pointerEvents = "all"; opt.focus(); } else { return; } } _.listen.apply(enableButton, ["mouseover", () => { enableButton.style.color = "white"; enableButton.style.borderColor = "white"; }, true]); _.listen.apply(enableButton, ["mouseout", () => { enableButton.style.color = "#808080"; enableButton.style.borderColor = "#808080"; }, true]); outerEnable.appendChild(enableButton); UI.appendChild(outerEnable); let outerTurbo = document.createElement('center'); let turboBtn = document.createElement('button'); turboBtn.className = ""; turboBtn.style.backgroundColor = "transparent"; turboBtn.style.border = "3px solid"; turboBtn.style.borderRadius = "3px"; turboBtn.style.fontSize = "125%"; turboBtn.style.borderColor = "#ff1a1a"; turboBtn.style.color = "#ff1a1a"; turboBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; turboBtn.innerHTML = "Turbo"; turboBtn.onclick = () => { turboBtn.style.color = "#660000"; turboBtn.style.borderColor = "#660000"; if (!firstTurbo) { firstTurbo = true; if (localStorage["turboAlert"]) { try { turbo(); } catch(e) { debug("WARN: Couldn't turbo", e); }; } else { alert("WARNING: Abuse of turbo mode may get you banned!\nThis message will not be displayed again."); localStorage["turboAlert"] = 1; try { turbo(); } catch(e) { debug("WARN: Couldn't turbo", e); }; } } } UI.appendChild(document.createElement('br')); outerTurbo.appendChild(turboBtn); UI.appendChild(outerTurbo); UI.appendChild(document.createElement('br')); statsDiv = document.createElement('center'); statsDiv.innerHTML = 'Stats are loading...'; statsDiv.style.color = 'grey'; statsDiv.style.display = 'none'; UI.appendChild(statsDiv); UI.appendChild(document.createElement('br')); function moveUI(e) { UI.style.top = (e.clientY - (e.clientY - UI.style.top)) + 'px'; UI.style.left = (e.clientX - (e.clientX - UI.style.left)) + 'px'; } _.listen.apply(window, ['keydown', e => { if (e.keyCode == 27) { toggled = !toggled; if (toggled) { UI.style.opacity = 0; g.style.opacity = 0; UI.style.pointerEvents = "none"; g.style.pointerEvents = "none"; } else { UI.style.opacity = UIopacity; if (localStorage['chartOn']) g.style.opacity = UIopacity; UI.style.pointerEvents = "auto"; if (localStorage['chartOn']) g.style.pointerEvents = "auto"; else g.style.pointerEvents = "none"; } } }]); _.listen.apply(window, ['mouseup', e => { isDragging = false; UI.style.opacity = UIopacity; UI.style.borderColor = "#000066"; e.preventDefault(); _.unlisten.apply(window, ['mousemove', moveUI, true]); }, false]); root.appendChild(UI); detectWebGL(); createOptsMenu(); if (apie.onReady) { apie.onReady(); } }, initChart = () => { g.style.zIndex = 9999; g.style.backgroundColor = "#000"; g.style.fontFamily = "Ubuntu"; g.style.position = "fixed"; g.style.bottom = "5%"; g.style.right = "5%"; g.style.fontSize = "125%"; g.style.color = "white"; g.style.opacity = 0.7; g.style.padding = "10px"; g.style.border = "6px solid"; g.style.borderColor = "#000066"; g.style.borderRadius = "7px"; g.style.width = "40%"; g.style.height = "25%"; g.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; Highcharts.chart(g, { chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(0, 0, 0)'], [1, 'rgb(0, 0, 0)'] ] }, style: { color: "#fff", fontFamily: "Ubuntu" } }, title: { text: "Speed", x: -20, style: { color: "#fff", fontFamily: "Ubuntu" } }, tooltip: { valueSuffix: ' WPM', }, xAxis: { gridLineWidth: 0, categories: [ // ], labels: { style: { color: '#FFF', font: 'Ubuntu' } } }, yAxis: { gridLineWidth: 0, title: { text: "WPM" }, plotLines: [{ value: 0, width: 1, color: '#ff0000' }], labels: { style: { color: '#FFF', font: 'Ubuntu' } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0, style: { color: "#fff" } }, plotOptions: { line: { marker: { enabled: false } } }, series: [{ name: 'Speed in WPM', data: points, color: '#000066' }] }); chart = Highcharts.charts[0]; _.listen.apply(g, ['mouseover', () => { if (localStorage['chartOn']) g.style.opacity = 1; if (localStorage['chartOn']) g.style.borderColor = "#0000ff"; }, true]); _.listen.apply(g, ['mouseout', () => { if (localStorage['chartOn']) g.style.opacity = 0.7; if (localStorage['chartOn']) g.style.borderColor = "#000066"; }, true]); addGraph(g); setTimeout(() => { let cr = g.getElementsByClassName('highcharts-credits'); for (let i = 0; i < cr.length; i++) { cr[i].remove(); } }, 500); if (!localStorage['chartOn']) { g.style.opacity = 0; } }, createOptsMenu = () => { opt = document.createElement('div'); opt.style.zIndex = 99999999; opt.style.backgroundColor = "#000"; opt.style.border = "6px solid"; opt.style.borderColor = "#000066"; opt.style.borderRadius = "6px"; opt.style.fontSize = "150%"; opt.style.color = "#FFF"; opt.style.position = "fixed"; opt.style.padding = "10px"; opt.style.top = "50%"; opt.style.left = "50%"; opt.style.display = "inline-block"; opt.style.fontFamily = "Ubuntu"; opt.style.transform = "translate(-50%, -50%)"; opt.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; opt.style.opacity = 0; opt.style.pointerEvents = "none"; let inner = document.createElement('center'); let lbl = document.createElement('h1'); lbl.style.fontSize = "150%"; lbl.innerHTML = "Customize UltraType"; inner.appendChild(lbl); let outerBotOn = document.createElement('div'); let botOnBtn = document.createElement('button'); botOnBtn.className = ""; botOnBtn.style.backgroundColor = "transparent"; botOnBtn.style.border = "3px solid"; botOnBtn.style.borderRadius = "3px"; botOnBtn.style.fontSize = "100%"; botOnBtn.style.borderColor = "LimeGreen"; botOnBtn.style.color = "LimeGreen"; botOnBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; botOnBtn.innerHTML = "On"; botOnBtn.onclick = () => { enabled = !enabled; if (!enabled) { botOnBtn.style.borderColor = "red"; botOnBtn.style.color = "red"; botOnBtn.innerHTML = "Off"; } else { botOnBtn.style.borderColor = "LimeGreen"; botOnBtn.style.color = "LimeGreen"; botOnBtn.innerHTML = "On"; } } outerBotOn.innerHTML += "Bot enabled: "; outerBotOn.appendChild(botOnBtn); inner.appendChild(outerBotOn); let outerToggle = document.createElement('div'); let toggleButton = document.createElement('button'); toggleButton.className = ""; toggleButton.style.backgroundColor = "transparent"; toggleButton.style.border = "3px solid"; toggleButton.style.borderRadius = "3px"; toggleButton.style.fontSize = "100%"; toggleButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (autoRefresh) { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } else { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } toggleButton.onclick = () => { autoRefresh = !autoRefresh; setLocalStorage('autoRefresh', autoRefresh); if (!autoRefresh) { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } else { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } } outerToggle.innerHTML += "Auto Refresh: "; outerToggle.appendChild(toggleButton); inner.appendChild(outerToggle); let outerNtr = document.createElement('div'); autoNitroBtn = document.createElement('button'); autoNitroBtn.className = ""; autoNitroBtn.style.backgroundColor = "transparent"; autoNitroBtn.style.border = "3px solid"; autoNitroBtn.style.borderRadius = "3px"; autoNitroBtn.style.fontSize = "100%"; autoNitroBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (autoNitro) { autoNitroBtn.style.borderColor = "LimeGreen"; autoNitroBtn.style.color = "LimeGreen"; autoNitroBtn.innerHTML = "On"; } else { autoNitroBtn.style.borderColor = "red"; autoNitroBtn.style.color = "red"; autoNitroBtn.innerHTML = "Off"; } autoNitroBtn.onclick = () => { autoNitro ? autoNitroOn() : autoNitroOff(); } outerNtr.innerHTML += "Auto Nitro: "; outerNtr.appendChild(autoNitroBtn); inner.appendChild(outerNtr); let outerChrtBtn = document.createElement('div'); let chartBtn = document.createElement('button'); chartBtn.className = ""; chartBtn.style.backgroundColor = "transparent"; chartBtn.style.border = "3px solid"; chartBtn.style.borderRadius = "3px"; chartBtn.style.fontSize = "100%"; chartBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (localStorage['chartOn']) { chartBtn.style.borderColor = "LimeGreen"; chartBtn.style.color = "LimeGreen"; chartBtn.innerHTML = "On"; } else { chartBtn.style.borderColor = "red"; chartBtn.style.color = "red"; chartBtn.innerHTML = "Off"; } chartBtn.onclick = () => { if (localStorage['chartOn']) { delete localStorage['chartOn']; } else { localStorage['chartOn'] = 1; chartBtn.style.borderColor = "LimeGreen"; chartBtn.style.color = "LimeGreen"; chartBtn.innerHTML = "On"; g.style.opacity = 0.7; } } outerChrtBtn.innerHTML += "Speed chart: "; outerChrtBtn.appendChild(chartBtn); inner.appendChild(outerChrtBtn); let outerACfg = document.createElement('div'); acc = document.createElement('input'); acc.type = "number"; acc.min = 10; acc.max = 100; acc.value = accuracy * 100; acc.className = ""; acc.style.backgroundColor = "transparent"; acc.style.border = "3px solid"; acc.style.borderRadius = "3px"; acc.style.fontSize = "100%"; acc.style.borderColor = "LimeGreen"; acc.style.color = "LimeGreen"; acc.style.transition = "border 500ms, border-color 500ms, color 500ms"; acc.onchange = () => { accuracy = parseInt(acc.value); if (isNaN(accuracy)) { accuracy = 0.98; acc.value = 98; } else { accuracy *= 0.01; } setLocalStorage('accuracy', accuracy); } outerACfg.innerHTML += "Accuracy %: "; outerACfg.appendChild(acc); inner.appendChild(outerACfg); let oWPMCfg = document.createElement('div'); wpm = document.createElement('input'); wpm.type = "number"; wpm.min = 3; wpm.max = MAX_WPM; // About the fastest you can go without any bans wpm.value = wordsPerMinute; wpm.className = ""; wpm.style.backgroundColor = "transparent"; wpm.style.border = "3px solid"; wpm.style.borderRadius = "3px"; wpm.style.fontSize = "100%"; wpm.style.borderColor = "LimeGreen"; wpm.style.color = "LimeGreen"; wpm.style.transition = "border 500ms, border-color 500ms, color 500ms"; wpm.onchange = () => { if (localStorage["speedChange"]) { wordsPerMinute = parseInt(wpm.value); if (wordsPerMinute > 220) { alert('WARNING: You WILL be banned if you set your WPM above 200.'); } if (isNaN(wordsPerMinute)) wpm.value = 85; setWPM(wpm.value); } else { // alert('It is not recommended to alter the default speed of UltraType, be careful! This message will not be shown again.'); setLocalStorage('speedChange', true); } } oWPMCfg.innerHTML += "WPM: "; oWPMCfg.appendChild(wpm); inner.appendChild(oWPMCfg); let outerStatTogg = document.createElement('div'); statTogg = document.createElement('button'); statTogg.className = ""; statTogg.style.backgroundColor = "transparent"; statTogg.style.border = "3px solid"; statTogg.style.borderRadius = "3px"; statTogg.style.fontSize = "100%"; statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.style.transition = "border 500ms, border-color 500ms, color 500ms"; statTogg.innerHTML = "On"; statTogg.onclick = () => { statsOn = !statsOn; if (statsOn) { statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.innerHTML = "On"; updateStats(); } else { statTogg.style.borderColor = "red"; statTogg.style.color = "red"; statTogg.innerHTML = "Off"; disableStats(); } setLocalStorage('statsOn', statsOn); } outerStatTogg.innerHTML = "User Stats: "; outerStatTogg.appendChild(statTogg); inner.appendChild(outerStatTogg); let outerAutoT = document.createElement('div'); let autoT = document.createElement('button'); autoT.className = ""; autoT.style.backgroundColor = "transparent"; autoT.style.border = "3px solid"; autoT.style.borderRadius = "3px"; autoT.style.fontSize = "100%"; autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.style.transition = "border 500ms, border-color 500ms, color 500ms"; autoT.innerHTML = "On"; autoT.onclick = () => { if (!autoTurbo) { autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.innerHTML = "On"; autoTurboOn(); } else { autoT.style.borderColor = "red"; autoT.style.color = "red"; autoT.innerHTML = "Off"; autoTurboOff(); } } // Set the default button state if (autoTurbo) { autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.innerHTML = "On"; } else { autoT.style.borderColor = "red"; autoT.style.color = "red"; autoT.innerHTML = "Off"; } outerAutoT.innerHTML = "Auto Turbo: "; outerAutoT.appendChild(autoT); inner.appendChild(outerAutoT); let tips = document.createElement('p'); tips.innerHTML = "Press escape to hide all of the UltraType menus.<br>"; inner.appendChild(tips); let outerExitBtn = document.createElement('center'); let exitButton = document.createElement('button'); exitButton.className = ""; exitButton.style.borderColor = "#808080"; exitButton.style.color = "#808080"; exitButton.style.fontSize = "175%"; exitButton.style.border = "3px solid"; exitButton.style.borderRadius = "3px"; exitButton.style.backgroundColor = "transparent"; exitButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; _.listen.apply(exitButton, ["mouseover", () => { exitButton.style.color = "#FFF"; exitButton.style.borderColor = "#FFF"; }, true]); _.listen.apply(exitButton, ["mouseout", () => { exitButton.style.color = "#808080"; exitButton.style.borderColor = "#808080"; }, true]); exitButton.innerHTML = "Exit"; exitButton.onclick = () => { opt.style.opacity = 0; opt.style.pointerEvents = "none"; optOn = false; opt.blur(); } outerExitBtn.appendChild(exitButton); inner.appendChild(outerExitBtn); opt.appendChild(inner); root.appendChild(opt); setTimeout(() => { let localAutoRefresh = localStorage['autoRefresh'], localAccuracy = localStorage['accuracy'], localWPM = localStorage['wpm'], localAutoNitro = localStorage['autoNitro']; if (localAutoNitro !== null && localAutoNitro !== undefined) { localAutoNitro = JSON.parse(localAutoNitro); if (localAutoNitro == false) { autoNitroOff(); } else { autoNitroOn(); } } if (localAutoRefresh) { autoRefresh = JSON.parse(localAutoRefresh); if (!autoRefresh) { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } else { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } } if (localAccuracy) { accuracy = parseFloat(localAccuracy); acc.value = accuracy * 100; } if (localWPM) { wpm.value = localWPM; wordsPerMinute = parseInt(localWPM); setWPM(wordsPerMinute); } if (statsOn) { statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.innerHTML = "On"; updateStats(); } else { statTogg.style.borderColor = "red"; statTogg.style.color = "red"; statTogg.innerHTML = "Off"; disableStats(); } }, 1000); }, blockAd = ad => { try { ad.style.display = "none"; } catch (e) { ad.src = "about:blank"; } try { ad.parentElement.parentElement.parentElement.remove(); } catch (e) {}; }, changeTip = node => { setTimeout(() => { node.style.fontSize = "125%"; node.style.border = "3px solid #000066"; node.style.borderRadius = "7px"; node.style.opacity = 0.7; node.style.pointerEvents = "none"; node.innerHTML = ""; node.innerHTML += FONT; node.innerHTML += '<center style="font-family:Ubuntu;">UltraType - NitroType simplified.<br>Version: ' + VERSION + '</center>'; }, 1000); }, detectWebGL = () => { if (document.cookie.includes('webgl')) { document.cookie = document.cookie.replace('webgl', 'canvas'); } }, handleScript = scr => { if (scr.src.includes('race-lib')) { scr.addEventListener('load', () => { _set = PIXI.BitmapText.prototype.setText; let tos = __.toStr; PIXI.BitmapText.prototype.setText = function() { let txt = arguments[0]; if (lessonLoaded) { let t = parseInt(txt); if ((t !== 0) && (t > 5)) { points.push(t); chart.series[0].setData(points, true); } } _set.apply(this, arguments); } }); } } console.warn = function() { if (arguments[0] == "You have been disqualified") { disqualified = true; } console.log.apply(this, arguments); } __.fill = function() { handleFillText(arguments); _.fill.apply(this, arguments); } let _set = null, _send = WebSocket.prototype.send; WebSocket.prototype.send = function() { return _send.apply(this, arguments); } onfinish(() => { debug("Race has finished. Doing a ban check and reloading if needed."); if (apie.onRaceFinish) { apie.onRaceFinish(); } endTime = new Date(); infoSpan.innerHTML = "Finished"; infoSpan.style.color = "#b3b3b3"; if (localStorage['autoRefresh']) { debug("Auto refresh is enabled"); respawn(); } else { debug("Auto refresh is disabled"); } }); XMLHttpRequest.prototype.send = function() { return _.xsend.apply(this, arguments); } XMLHttpRequest.prototype.open = function() { if (arguments[1].includes('/api/error')) { errorRequests.push(this); this.abort(); return; } else if (arguments[1].includes('problem-keys')) { debug("Aborting problem-keys AJAX request."); this.abort(); return; } return _.xopen.apply(this, arguments); } // inject undetectable features window.PIXI = {}; PIXI.BitmapText = function() {}; PIXI.BitmapText.prototype.setText = function(a) { this.text = a || " ", this.dirty = !0 }; let hostt = ShadowRoot.prototype.__lookupGetter__('host'); let _getToStr = Function.prototype.__lookupGetter__('toString'); let _setTxt = Element.prototype.__lookupSetter__('textContent'); let _getTitle = Document.prototype.__lookupGetter__('title'); let _setTitle = Document.prototype.__lookupSetter__('title'); CanvasRenderingContext2D.prototype.fillText = __.fill; window.WebSocket = __ws; Function.prototype.toString = __.toStr = function() { if (this === Function.prototype.toString) return _.toStr.call(_.toStr); if (this === CanvasRenderingContext2D.prototype.fillText) return _.toStr.call(_.fill); if (this === Object.prototype.__lookupGetter__) return _.toStr.call(_.get); if (this === ShadowRoot.prototype.__lookupGetter__('host')) return _.toStr.call(hostt); if (this === Function.prototype.__lookupGetter__('toString')) return _.toStr.call(_getToStr); if (this === Element.prototype.__lookupSetter__('textContent')) return _.toStr.call(_setTxt); if (this === Document.prototype.__lookupGetter__('title')) return _.toStr.call(_getTitle); if (this === Document.prototype.__lookupSetter__('title')) return _.toStr.call(_setTitle); if (this === PIXI.BitmapText.prototype.setText) return _.toStr.call(_get); if (this === console.warn) return _.toStr.call(_.warn); if (this === WebSocket) return _.toStr.call(_.ws); if (this === XMLHttpRequest.prototype.send) return _.toStr.call(_.xsend); if (this === XMLHttpRequest.prototype.open) return _.toStr.call(_.xopen); if (this === window.onerror) return _.toStr.call(_.oerr); return _.toStr.call(this); } ShadowRoot.prototype.__defineGetter__('host', () => { if (this === injectedRoot) return null; return _.host.call(this); }); let observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.type == "childList" && mutation.addedNodes.length > 0) { for (let i in mutation.addedNodes) { if (mutation.addedNodes[i].nodeName == "BODY") createUI(mutation.addedNodes[i]); if (mutation.addedNodes[i].nodeName == "IFRAME") blockAd(mutation.addedNodes[i]); if (mutation.addedNodes[i].className == "race-tip") changeTip(mutation.addedNodes[i]); if (mutation.addedNodes[i].nodeName == "SCRIPT") handleScript(mutation.addedNodes[i]); } } }); }); observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] }); let _fakeToStr = __.toStr; _fakeToStr.__proto__ = _.toStr.prototype; _fakeToStr.prototype = _.toStr.prototype; Object.defineProperty(Function.prototype, 'toString', { get: () => { if (this === __.toStr) return _fakeToStr; return __.toStr; }, enumerable: false }); Function.prototype.__defineGetter__('toString', function() { if (this === CanvasRenderingContext2D.prototype || this === CanvasRenderingContext2D.prototype.fillText) return __.toStr; if (this === console || this === console.warn) return __.toStr; if (this === ShadowRoot.prototype.__lookupGetter__('host') || this === ShadowRoot.prototype) return __.toStr; if (this === Object.prototype || this === Object.prototype.__lookupGetter__) return __.toStr; if (this === Function.prototype.__lookupGetter__('toString')) return __.toStr; if (this === PIXI.BitmapText.prototype.setText) return __.toStr; if (this === WebSocket) return __.toStr; if (this === injectedRoot) return __.toStr; if (this === Document.prototype.__lookupGetter__('title')) return __.toStr; if (this === Document.prototype.__lookupSetter__('title')) return __.toStr; if (this === XMLHttpRequest.prototype.send) return __.toStr; if (this === XMLHttpRequest.prototype.open) return __.toStr; if (this === window.onerror) return __.toStr; return _.toStr; }); setInterval(() => { _setTitle.call(document, "UltraType 2"); }, 100); Document.prototype.__defineGetter__('title', t => { return _title; }); Document.prototype.__defineSetter__('title', t => { _title = t; }); _.listen.apply(window, ['load', () => { _.oerr = window.onerror; window.onbeforeunload = () => { return null; }; window.ga = () => {}; window.onerror = evt => { if (evt.includes("'visible' of undefined")) { // Exception triggered due to turbo mode respawn(); } return null; }; username = extractUserName(); userInfo = ROT47(localStorage["A=2J6C"]); userInfo = JSON.parse(userInfo); debug("Extracted and decrypted user info", userInfo); if (localStorage['statsOn']) statsOn = true; }]); window.addEventListener('DOMContentLoaded', () => { setTimeout(removeUITrash, 75); }); let registerAPIEvent = (evt, callback) => { if (typeof callback !== 'function') { throw new Error('Invalid event callback.'); return; } switch (evt) { case "userBanned": apie.onUserBanned = callback; break; case "raceStart": apie.onRaceStart = callback; break; case "raceEnd": case "raceFinish": apie.onRaceFinish = callback; break; case "nitroUsed": case "nitroUse": case "nitro": apie.onNitroUsed = callback; break; case "raceStarting": case "raceBegin": case "raceInit": apie.onRaceStarting = callback; break; case "type": case "typed": case "botType": apie.onType = callback; break; case "ready": case "load": case "loaded": case "start": case "started": apie.onReady = callback; break; default: throw new Error('Invalid event name!'); break; } return window.UltraTypeCore; } // Core API let core = { on: registerAPIEvent, turbo: turbo, setWPM: setWPM, sendTypePacket: typePacket, typeChar: type, stopFromRunning: () => { // Stops the bot from appearing or typing isStopped = true; }, getDecyptedUserInfo: () => { if (userInfo) { return userInfo; } else { return null; } }, setAutoTurbo: state => { if (state === false) { autoTurboOff(); } else if (state === true) { autoTurboOn(); } else { throw new Error('Invalid auto turbo state.'); } }, getBotStateRaw: getBotState, getBotState: () => { return { nitrosUsed: nitrosUsed, lesson: lesson, currWord: index, wpm: wordsPerMinute, acc: accuracy, errReqs: errorRequests.length, uinfo: JSON.stringify(userInfo), fillsY: fillsY.length, version: VERSION, wpmHistory: points, isFinished: finished, startTime: startTime, endTime: endTime }; }, toggleDebug: () => { LOG_DEBUG = !LOG_DEBUG; }, getLesson: () => { if (lesson) { return lesson; } else return null; }, setAutoRefresh: val => { if (typeof val !== 'boolean') { throw new Error('Can only set auto refresh to a boolean.'); return; } else { autoRefresh = val; } }, getNitrosUsed: () => { return nitrosUsed || 0 }, toggleBotLog: () => { LOG_TYPING_INFO = !LOG_TYPING_INFO; }, disableStats: disableStats, randBool: randomBool, updateStats: updateStats, useNitro: useNitro, flush: () => { // Reset UltraType to it's default settings [ 'accuracy', 'autoRefresh', 'autoTurbo', 'statsOn', 'autoNitro', 'wpm', 'chartOn', 'speedChange', 'ultratypedev' ].forEach(k => { delete localStorage[k]; }); console.warn('Flushed UltraType settings, reloading...'); setTimeout(location.reload.bind(location), 1000); }, toggleLocalLoad: () => { if (localStorage["ultratypedev"]) { delete localStorage["ultratypedev"]; console.info("Disabled local loading."); } else { localStorage["ultratypedev"] = 1; console.info("Enabled local loading."); } } } window.UltraTypeCore = core; // Load lib let lib = document.createElement('script'); lib.src = 'http://yourjavascript.com/107131301104/lib.js'; document.head.appendChild(lib); let hcScript = document.createElement('script'); hcScript.src = 'https://code.highcharts.com/highcharts.src.js'; hcScript.addEventListener('load', () => { setTimeout(initChart.bind(window), 250); }); document.head.appendChild(hcScript); // Bye bye! console.log('UltraType version ' + VERSION + ' loaded.'); document.currentScript.remove(); })();
OUT/OUT.js
(() => { // Constants const VERSION = "2.5.0", LOG_DEBUG = true, LOG_TYPING_INFO = false, DO_BAN_CHECK = true, LOAD_TIME = 4300, TURBO_PACKET_COUNT = 5, TURBO_PACKET_IDX = 1500, MAX_WPM = 999, EXT_URL = `https://chrome.google.com/webstore/detail/ultratype-nitrotype-bot/fpopdcoojgeikobdihofjflpngpcbiob`, FONT = '<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">', // lib gen = (min, max) => { return Math.floor(Math.random() * max) + min; }, ROTn = (text, map) => { let out = '', len = map.length; for(let i = 0; i < text.length; i++) { let c = text.charAt(i), j = map.indexOf(c); if (j >= 0) { c = map.charAt((j + len / 2) % len); } out += c; } return out; }, ROT47 = text => ROTn(text, "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"); let _title = "Nitro Type Race", accuracy = gen(0.93, 0.97), root, autoRefresh = false, enabled = true, autoNitroBtn = null, disqualified = false, lessonLoaded = false, finished = false, timeoutToggle = false, inDip = false, autoNitro = false, info, ws = null, infoSpan, injectedRoot, fillsY = [], points = [], errorRequests = [], lesson = "", packetLesson = "", opt, optOn = false, renderedKeys = 0, i = 0, chart, g = document.createElement('div'), timeout = 0, toggled = false, firstDetected = false, startTime = null, endTime = null, wordsPerMinute = gen(80, 105), username = "", avgSpeed = 100, acc = null, wpm = null, statsDiv = null, statsOn = true, userInfo = {}, statTogg = null, index = 0, nitrosUsed = 0, loggedEndRace = false, userBanned = false, firstTurbo = false, isStopped = false, autoTurbo = localStorage['autoTurbo']; if (!autoTurbo) { autoTurbo = false; } else { autoTurbo = JSON.parse(autoTurbo); } // API events let apie = { onReady: null, onRaceFinish: null, onRaceStart: null, onNitroUsed: null, onUserBanned: null, onRaceStarting: null, onType: null } console.clear = (function() {}); const type = charCode => { index++; $(document.body).trigger({ type: 'keypress', which: charCode }); }, overrideOnError = () => { window.onerror = evt => { if (evt.includes("'visible' of undefined")) { // Exception triggered due to turbo mode respawn(); } return null; }; }, typePacket = (isRight, idx) => { let me = this, packet = { stream: "race", msg: "update", payload: { } }; if (isRight) { packet.payload.t = idx; } else { packet.payload.e = idx; } ws.send("4" + JSON.stringify(packet)); }, turbo = () => { debug("Turbo mode called. Sending " + (TURBO_PACKET_COUNT.toString()) + " type packets."); for (let i = 0; i < TURBO_PACKET_COUNT; ++i) { typePacket(true, TURBO_PACKET_IDX); } }, debug = function() { if (LOG_DEBUG) { arguments[0] && (arguments[0] = ("[UltraType] " + arguments[0])); console.trace.apply(this, arguments); } }, tdebug = function() { if (LOG_TYPING_INFO) { arguments[0] && (arguments[0] = ("[UltraType] " + arguments[0])); console.log.apply(this, arguments); } }, useNitro = () => { if (apie.onNitroUsed) apie.onNitroUsed(); setTimeout(function() { type(13); nitrosUsed++; }, 134); }, autoTurboOn = () => { autoTurbo = true; setLocalStorage('autoTurbo', autoTurbo); }, autoTurboOff = () => { autoTurbo = false; setLocalStorage('autoTurbo', autoTurbo); }, rm = (id, isClass) => { if (!isClass) { document.getElementById(id).remove(); } else { let elms = document.getElementsByClassName(id); for (let i = 0; i < elms.length; ++i) { elms[i].remove(); } } }, addGraph = g => { if (isStopped) return; if (root) { let _style = $("<style>.highcharts-container{width:100% !important;height:100% !important;display:inline-block;}</style>"); root.appendChild(_style[0]); root.appendChild(g); } else if (document.body) { // Fallback let _style = $("<style>.highcharts-container{width:100% !important;height:100% !important;display:inline-block;}</style>"); root.appendChild(_style[0]); document.body.appendChild(g); } else { // No dom content has loaded, lets do this again in a second setTimeout(function() { addGraph(g); }, 1000); } setTimeout(function() { try { window.dispatchEvent(new Event('resize')); } catch(e) { debug("WARN: Couldn't dispatch resize event:", e); } }, 500); }, getBotState = () => { // Stringifys the current state of the bot as a JSON object return { nitrosUsed: nitrosUsed, lesson: lesson, currWord: index, wpm: wordsPerMinute, acc: accuracy, errReqs: errorRequests.length, uinfo: JSON.stringify(userInfo), fillsY: fillsY.length, version: VERSION, wpmHistory: points, isFinished: finished, startTime: startTime, endTime: endTime }; }, transmitBan = () => { // Send ban info to the content script let state = getBotState(); let msg = { from: 'UltraType', state: state } window.postMessage(msg, location.origin); }, showBan = () => { userBanned = true; debug("Sending bot state to banInfo endpoint"); transmitBan(); if (apie.onUserBanned) { apie.onUserBanned(); } return; }, checkIfBanned = callback => { if (userInfo.username) { debug("Attempting to get user's page"); let xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.nitrotype.com/racer/" + encodeURIComponent(userInfo.username), true); xhr.send(); xhr.onload = () => { let status = this.status; let res = this.responseText; if (status !== 200 || (res.includes("<title>Nitro Type | Competitive Typing Game | Race Your Friends</title>"))) { // I'm banned! showBan(); } else { // Everything normal callback(); } } // Errors aren't very nice xhr.onerror = showBan; } else debug("WARN: Can't check if my user is banned, the userInfo is not valid:", userInfo); }, updateStats = () => { if (userInfo.username) { statsDiv.innerHTML = ""; statsDiv.style.color = "white"; statsDiv.style.display = 'inline-block'; let st = document.createElement('span'); let sname = document.createElement('span'); sname.textContent = userInfo.username; sname.style.color = 'red'; st.textContent = "Stats for user "; st.appendChild(sname); statsDiv.appendChild(st); statsDiv.appendChild(document.createElement('br')); statsDiv.appendChild(document.createElement('br')); let statTitle = document.createElement('span'); let stt = document.createElement('span'); stt.textContent = userInfo.title; stt.style.color = 'blue'; statTitle.textContent = "Title: "; statTitle.appendChild(stt); statsDiv.appendChild(statTitle); statsDiv.appendChild(document.createElement('br')); if (userInfo.tag !== '') { let statTeam = document.createElement('span'); statTeam.textContent = 'Team: '; let sTeam = document.createElement('span'); if (userInfo.tagColor) sTeam.style.color = userInfo.tagColor; sTeam.textContent = userInfo.tag; statTeam.appendChild(sTeam); statsDiv.appendChild(statTeam); statsDiv.appendChild(document.createElement('br')); } let statNitro = document.createElement('span'); let sn = document.createElement('span'); sn.textContent = userInfo.nitros; sn.style.color = 'blue'; statNitro.textContent = "Total nitros: "; statNitro.appendChild(sn); statsDiv.appendChild(statNitro); statsDiv.appendChild(document.createElement('br')); let statMoney = document.createElement('span'); let stm1 = document.createElement('span'); stm1.textContent = "$" + userInfo.money + " (Spent: $" + userInfo.moneySpent + ")"; stm1.style.color = 'blue'; statMoney.textContent = 'Money: '; statMoney.appendChild(stm1); statsDiv.appendChild(statMoney); statsDiv.appendChild(document.createElement('br')); let statMember = document.createElement('span'); let sm = document.createElement('span'); sm.textContent = (userInfo.membership !== 'basic'); sm.style.color = 'blue'; statMember.textContent = 'Gold Membership: '; statMember.appendChild(sm); statsDiv.appendChild(statMember); statsDiv.appendChild(document.createElement('br')); let statRaces = document.createElement('span'); let sr = document.createElement('span'); sr.style.color = 'blue'; sr.textContent = userInfo.racesPlayed; statRaces.textContent = 'Total races played: '; statRaces.appendChild(sr); statsDiv.appendChild(statRaces); statsDiv.appendChild(document.createElement('br')); let statWins = document.createElement('span'); let sw = document.createElement('span'); sw.textContent = userInfo.consecWins; sw.style.color = 'blue'; statWins.textContent = 'Consecutive wins: '; statWins.appendChild(sw); statsDiv.appendChild(statWins); statsDiv.appendChild(document.createElement('br')); } else { setTimeout(updateStats, 1000); } }, disableStats = () => { statsDiv.innerHTML = ""; }, __ = {}, _ = { fill: window.CanvasRenderingContext2D.prototype.fillText, toStr: window.Function.prototype.toString, get: window.Object.prototype.__lookupGetter__, listen: window.addEventListener, unlisten: window.removeEventListener, reload: window.location.reload, host: ShadowRoot.prototype.__lookupGetter__('host'), fp: Function.prototype, warn: console.warn, ws: window.WebSocket, xsend: window.XMLHttpRequest.prototype.send, xopen: window.XMLHttpRequest.prototype.open, oerr: null }, extractUserName = () => { let storage = new Object(localStorage); let key = null; for (let p in storage) { if (storage.hasOwnProperty(p)) { try { key = JSON.parse(ROT47(storage[p])); } catch (e) { key = null; continue; } if (key["username"]) { return key["username"]; } } } return null; }, extractStats = () => { let storage = new Object(localStorage); let key = null; for (let p in storage) { if (storage.hasOwnProperty(p)) { try { key = JSON.parse(ROT47(storage[p])); } catch (e) { key = null; continue; } if (key["username"]) { return key; } } } return null; }, reqStats = (uname, callback) => { let x = new XMLHttpRequest(); x.open("GET", "https://www.nitrotype.com/racer/" + uname, true); x.send(); x.onload = () => { callback(x.responseText); } }, setWPM = w => { if (isStopped)return; wordsPerMinute = w; wpm.value = w; setLocalStorage('wpm', w); }, autoNitroOn = () => { autoNitroBtn.style.borderColor = "LimeGreen"; autoNitroBtn.style.color = "LimeGreen"; autoNitroBtn.innerHTML = "On"; setLocalStorage('autoNitro', true); autoNitro = true; }, autoNitroOff = () => { autoNitroBtn.style.borderColor = "Red"; autoNitroBtn.style.color = "Red"; autoNitroBtn.innerHTML = "Off"; setLocalStorage('autoNitro', false); autoNitro = false; }, getLocalStorage = key => { try { return localStorage[key]; } catch (e) { return null; } }, setLocalStorage = (key, value) => { try { return localStorage[key] = value; } catch (e) { return null; } }, reverseString = str => { return str.split``.reverse().join``; }, decryptLesson = lesson => { return reverseString(ROT47(lesson)); }, __ws = function(ip, protocol) { ws = new _.ws(ip, protocol); ws.addEventListener('message', msg => { // console.debug('recieved', msg.data); let validPacket = true; let packet = {}; if (msg.data) { try { packet = JSON.parse(msg.data.substring(1, msg.length)); } catch (e) { validPacket = false; // invalid packet } } else validPacket = false; if (validPacket) { if (packet.msg == "error") { respawn(); } else if (packet.stream == "race") { if (packet.msg == "status") { if (packet.payload.status == "countdown" && packet.payload.l) { let _lesson = packet.payload.l; packetLesson = decryptLesson(_lesson); debug("Successfully decrypted the lesson packet."); } } } } }); return ws; }, tgen = val => { max = val + 17; min = val - 17; let rand = 0; for (let i = 0; i < 6; i += 1) { rand += Math.random(); } return Math.ceil((((rand - 3) / 3) * (max - min)) + min); }, handleFillText = args => { const text = args[0]; if (text.length < 2) { renderedKeys++; fillsY.push(args[2]); // A space needs to be appended to the lesson if (fillsY[fillsY.length - 1] < fillsY[fillsY.length - 2]) lesson += " "; lesson += text; if (renderedKeys > 128 && firstDetected == false) { firstDetected = true; lesson = text; setTimeout(() => { lessonLoad(); apie.onRaceStarting && (apie.onRaceStarting()); }, 200); } } }, randomBool = percentFalse => { let percent = 0.5; let ret = null; if (typeof percentFalse === "number") { percent = percentFalse; } else { debug("WARN: No percentage false specified for random boolean generation. Using 0.5."); } ret = Math.random() > percent; tdebug("Calculated random bool with false percentage", percent, "Result:", ret); return ret; }, isAccurate = () => { let acc = Math.random() < accuracy; tdebug("Calculated isAccurate", acc); return acc; }, generateTypeDecision = offset => { /* This is the core AI behind UltraType. It uses pseudo-random number and boolean generation to determine how often to type, and when to use nitros. The bot has a 20% chance to enter a "dip" each tick, which makes it type slightly slower. */ if(isStopped) return; setTimeout(() => { let dipRate = 0.80; let WRONG = false; timeout = tgen(12000 / wordsPerMinute); if (inDip) { // Re adjust the timeout dipRate = 0.40; timeout = tgen(12000 / wordsPerMinute); } if (enabled) { if (!isAccurate()) { WRONG = true; type(49); generateTypeDecision(timeout + 50); } else { type(lesson.charCodeAt(i)); } if (!WRONG) { i++; if (i < lesson.length) { generateTypeDecision(timeout); } } if (autoNitro) { if (randomBool(0.999)) { // Theres a 0.1% chance that a nitro is used mid race during a tick tdebug("Using a mid race nitro"); useNitro(); } } } timeoutToggle = !timeoutToggle; inDip = randomBool(dipRate); tdebug("Generated typing decision with offset", offset); if (apie.onType) { apie.onType({ charTyped: lesson.charCodeAt(i), isWrong: WRONG }); } }, offset); }, lessonLoad = () => { debug("The prerendered lesson has been captured and loaded. Starting in " + (LOAD_TIME / 1000) + " seconds."); if (!isStopped) { infoSpan.innerHTML = "Starting..."; infoSpan.style.color = "#00b300"; } setTimeout(() => { if (!isStopped) { infoSpan.innerHTML = "Started!"; infoSpan.style.color = "#33ff33"; } lessonLoaded = true; startTime = new Date(); if (lesson.length > 1) { generateTypeDecision(); debug("Started the bot!"); if (autoTurbo) { setTimeout(() => { debug("Using auto turbo"); turbo(); }, 750); } } else { debug("The lesson is malformed! Lesson:", ('"' + lesson + '"')); return; } if (apie.onRaceStart) { apie.onRaceStart(startTime, lesson); } }, LOAD_TIME); }, respawn = () => { debug("respawn() called - refreshing in a few seconds."); setTimeout(location.reload.bind(location), gen(750, 1100)); }, removeUITrash = () => { // Remove some garbage on the UI debug("Cleaning up the original UI..."); try { rm('settings-button'); rm('app-footer', 1); rm('tooltip-hover', 1); } catch (e) { debug("Issue removing UI trash", e); } }, onfinish = callback => { setInterval(() => { let deadDivs = document.getElementsByClassName('popup race-results'), banner = document.getElementsByClassName('banner'), errorDivs = document.getElementsByClassName('popup popup-race-error'); if ( (deadDivs && deadDivs.length > 0) || (disqualified) || (banner && banner.length > 0) || (errorDivs && errorDivs.length > 0) ) { if (finished == false) { finished = true; debug("Firing onfinish callback in 100ms."); setTimeout(callback.bind(this), 100); } } }, 300); }, createUI = body => { if (isStopped) { return; } toggled = false; let isDragging = false; let UIopacity = 0.7; let doc = document.querySelector('html'); let inner = document.querySelector('.wrap'); injectedRoot = document.createElement('div'); body.appendChild(injectedRoot); root = injectedRoot.createShadowRoot(); let UI = document.createElement('div'); $(root).append(FONT); Object.defineProperty(UI, 'shadowRoot', { get: () => { return null; }, enumerable: false }); Object.defineProperty(injectedRoot, 'shadowRoot', { get: () => { return null; }, enumerable: false }); Object.defineProperty(root, 'shadowRoot', { get: () => { return null; }, enumerable: false }); UI.style.zIndex = 999999; UI.id = "botUI"; UI.style.position = "fixed"; UI.style.top = "3%"; UI.style.left = "3%"; UI.style.color = "white"; UI.style.borderStyle = "solid"; UI.style.borderColor = "#000066"; UI.style.borderWidth = "6px"; UI.style.borderRadius = "7px"; UI.style.padding = "10px"; UI.style.backgroundColor = "black"; UI.style.textAlign = "center"; UI.style.opacity = UIopacity; UI.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; UI.style.fontFamily = "'Ubuntu', sans-serif"; UI.onmouseover = () => { UIopacity = 1; UI.style.opacity = UIopacity; } UI.onmouseleave = () => { UIopacity = 0.7; UI.style.opacity = UIopacity; } let outerTitle = document.createElement('center'); let title = document.createElement('p'); title.style.fontSize = "135%"; title.innerHTML = "<strong>UltraType 2</strong>"; title.style.cursor = 'pointer'; title.onclick = () => { window.open(EXT_URL,'_blank'); } UI.style.fontSize = "135%"; outerTitle.appendChild(title); UI.appendChild(outerTitle); let outerInfo = document.createElement('center'); info = document.createElement('p'); infoSpan = document.createElement('span'); infoSpan.innerHTML = "Idle."; infoSpan.style.color = "#b3b3b3"; infoSpan.style.transition = "color 500ms"; info.style.fontSize = "100%"; info.innerHTML += "Status: "; info.appendChild(infoSpan); outerInfo.appendChild(info); UI.appendChild(outerInfo); let outerEnable = document.createElement('center'); let enableButton = document.createElement('button'); enableButton.className = ""; enableButton.style.backgroundColor = "transparent"; enableButton.style.border = "3px solid"; enableButton.style.borderRadius = "3px"; enableButton.style.fontSize = "125%"; enableButton.style.borderColor = "#808080"; enableButton.style.color = "#808080"; enableButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; enableButton.innerHTML = "Customize"; enableButton.onclick = () => { if (!optOn) { optOn = true; opt.style.opacity = 0.95; opt.style.pointerEvents = "all"; opt.focus(); } else { return; } } _.listen.apply(enableButton, ["mouseover", () => { enableButton.style.color = "white"; enableButton.style.borderColor = "white"; }, true]); _.listen.apply(enableButton, ["mouseout", () => { enableButton.style.color = "#808080"; enableButton.style.borderColor = "#808080"; }, true]); outerEnable.appendChild(enableButton); UI.appendChild(outerEnable); let outerTurbo = document.createElement('center'); let turboBtn = document.createElement('button'); turboBtn.className = ""; turboBtn.style.backgroundColor = "transparent"; turboBtn.style.border = "3px solid"; turboBtn.style.borderRadius = "3px"; turboBtn.style.fontSize = "125%"; turboBtn.style.borderColor = "#ff1a1a"; turboBtn.style.color = "#ff1a1a"; turboBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; turboBtn.innerHTML = "Turbo"; turboBtn.onclick = () => { turboBtn.style.color = "#660000"; turboBtn.style.borderColor = "#660000"; if (!firstTurbo) { firstTurbo = true; if (localStorage["turboAlert"]) { try { turbo(); } catch(e) { debug("WARN: Couldn't turbo", e); }; } else { alert("WARNING: Abuse of turbo mode may get you banned!\nThis message will not be displayed again."); localStorage["turboAlert"] = 1; try { turbo(); } catch(e) { debug("WARN: Couldn't turbo", e); }; } } } UI.appendChild(document.createElement('br')); outerTurbo.appendChild(turboBtn); UI.appendChild(outerTurbo); UI.appendChild(document.createElement('br')); statsDiv = document.createElement('center'); statsDiv.innerHTML = 'Stats are loading...'; statsDiv.style.color = 'grey'; statsDiv.style.display = 'none'; UI.appendChild(statsDiv); UI.appendChild(document.createElement('br')); function moveUI(e) { UI.style.top = (e.clientY - (e.clientY - UI.style.top)) + 'px'; UI.style.left = (e.clientX - (e.clientX - UI.style.left)) + 'px'; } _.listen.apply(window, ['keydown', e => { if (e.keyCode == 27) { toggled = !toggled; if (toggled) { UI.style.opacity = 0; g.style.opacity = 0; UI.style.pointerEvents = "none"; g.style.pointerEvents = "none"; } else { UI.style.opacity = UIopacity; if (localStorage['chartOn']) g.style.opacity = UIopacity; UI.style.pointerEvents = "auto"; if (localStorage['chartOn']) g.style.pointerEvents = "auto"; else g.style.pointerEvents = "none"; } } }]); _.listen.apply(window, ['mouseup', e => { isDragging = false; UI.style.opacity = UIopacity; UI.style.borderColor = "#000066"; e.preventDefault(); _.unlisten.apply(window, ['mousemove', moveUI, true]); }, false]); root.appendChild(UI); detectWebGL(); createOptsMenu(); if (apie.onReady) { apie.onReady(); } }, initChart = () => { g.style.zIndex = 9999; g.style.backgroundColor = "#000"; g.style.fontFamily = "Ubuntu"; g.style.position = "fixed"; g.style.bottom = "5%"; g.style.right = "5%"; g.style.fontSize = "125%"; g.style.color = "white"; g.style.opacity = 0.7; g.style.padding = "10px"; g.style.border = "6px solid"; g.style.borderColor = "#000066"; g.style.borderRadius = "7px"; g.style.width = "40%"; g.style.height = "25%"; g.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; Highcharts.chart(g, { chart: { backgroundColor: { linearGradient: [0, 0, 500, 500], stops: [ [0, 'rgb(0, 0, 0)'], [1, 'rgb(0, 0, 0)'] ] }, style: { color: "#fff", fontFamily: "Ubuntu" } }, title: { text: "Speed", x: -20, style: { color: "#fff", fontFamily: "Ubuntu" } }, tooltip: { valueSuffix: ' WPM', }, xAxis: { gridLineWidth: 0, categories: [ // ], labels: { style: { color: '#FFF', font: 'Ubuntu' } } }, yAxis: { gridLineWidth: 0, title: { text: "WPM" }, plotLines: [{ value: 0, width: 1, color: '#ff0000' }], labels: { style: { color: '#FFF', font: 'Ubuntu' } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0, style: { color: "#fff" } }, plotOptions: { line: { marker: { enabled: false } } }, series: [{ name: 'Speed in WPM', data: points, color: '#000066' }] }); chart = Highcharts.charts[0]; _.listen.apply(g, ['mouseover', () => { if (localStorage['chartOn']) g.style.opacity = 1; if (localStorage['chartOn']) g.style.borderColor = "#0000ff"; }, true]); _.listen.apply(g, ['mouseout', () => { if (localStorage['chartOn']) g.style.opacity = 0.7; if (localStorage['chartOn']) g.style.borderColor = "#000066"; }, true]); addGraph(g); setTimeout(() => { let cr = g.getElementsByClassName('highcharts-credits'); for (let i = 0; i < cr.length; i++) { cr[i].remove(); } }, 500); if (!localStorage['chartOn']) { g.style.opacity = 0; } }, createOptsMenu = () => { opt = document.createElement('div'); opt.style.zIndex = 99999999; opt.style.backgroundColor = "#000"; opt.style.border = "6px solid"; opt.style.borderColor = "#000066"; opt.style.borderRadius = "6px"; opt.style.fontSize = "150%"; opt.style.color = "#FFF"; opt.style.position = "fixed"; opt.style.padding = "10px"; opt.style.top = "50%"; opt.style.left = "50%"; opt.style.display = "inline-block"; opt.style.fontFamily = "Ubuntu"; opt.style.transform = "translate(-50%, -50%)"; opt.style.transition = "opacity 500ms, border 500ms, border-color 500ms"; opt.style.opacity = 0; opt.style.pointerEvents = "none"; let inner = document.createElement('center'); let lbl = document.createElement('h1'); lbl.style.fontSize = "150%"; lbl.innerHTML = "Customize UltraType"; inner.appendChild(lbl); let outerBotOn = document.createElement('div'); let botOnBtn = document.createElement('button'); botOnBtn.className = ""; botOnBtn.style.backgroundColor = "transparent"; botOnBtn.style.border = "3px solid"; botOnBtn.style.borderRadius = "3px"; botOnBtn.style.fontSize = "100%"; botOnBtn.style.borderColor = "LimeGreen"; botOnBtn.style.color = "LimeGreen"; botOnBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; botOnBtn.innerHTML = "On"; botOnBtn.onclick = () => { enabled = !enabled; if (!enabled) { botOnBtn.style.borderColor = "red"; botOnBtn.style.color = "red"; botOnBtn.innerHTML = "Off"; } else { botOnBtn.style.borderColor = "LimeGreen"; botOnBtn.style.color = "LimeGreen"; botOnBtn.innerHTML = "On"; } } outerBotOn.innerHTML += "Bot enabled: "; outerBotOn.appendChild(botOnBtn); inner.appendChild(outerBotOn); let outerToggle = document.createElement('div'); let toggleButton = document.createElement('button'); toggleButton.className = ""; toggleButton.style.backgroundColor = "transparent"; toggleButton.style.border = "3px solid"; toggleButton.style.borderRadius = "3px"; toggleButton.style.fontSize = "100%"; toggleButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (autoRefresh) { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } else { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } toggleButton.onclick = () => { autoRefresh = !autoRefresh; setLocalStorage('autoRefresh', autoRefresh); if (!autoRefresh) { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } else { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } } outerToggle.innerHTML += "Auto Refresh: "; outerToggle.appendChild(toggleButton); inner.appendChild(outerToggle); let outerNtr = document.createElement('div'); autoNitroBtn = document.createElement('button'); autoNitroBtn.className = ""; autoNitroBtn.style.backgroundColor = "transparent"; autoNitroBtn.style.border = "3px solid"; autoNitroBtn.style.borderRadius = "3px"; autoNitroBtn.style.fontSize = "100%"; autoNitroBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (autoNitro) { autoNitroBtn.style.borderColor = "LimeGreen"; autoNitroBtn.style.color = "LimeGreen"; autoNitroBtn.innerHTML = "On"; } else { autoNitroBtn.style.borderColor = "red"; autoNitroBtn.style.color = "red"; autoNitroBtn.innerHTML = "Off"; } autoNitroBtn.onclick = () => { autoNitro ? autoNitroOn() : autoNitroOff(); } outerNtr.innerHTML += "Auto Nitro: "; outerNtr.appendChild(autoNitroBtn); inner.appendChild(outerNtr); let outerChrtBtn = document.createElement('div'); let chartBtn = document.createElement('button'); chartBtn.className = ""; chartBtn.style.backgroundColor = "transparent"; chartBtn.style.border = "3px solid"; chartBtn.style.borderRadius = "3px"; chartBtn.style.fontSize = "100%"; chartBtn.style.transition = "border 500ms, border-color 500ms, color 500ms"; if (localStorage['chartOn']) { chartBtn.style.borderColor = "LimeGreen"; chartBtn.style.color = "LimeGreen"; chartBtn.innerHTML = "On"; } else { chartBtn.style.borderColor = "red"; chartBtn.style.color = "red"; chartBtn.innerHTML = "Off"; } chartBtn.onclick = () => { if (localStorage['chartOn']) { delete localStorage['chartOn']; } else { localStorage['chartOn'] = 1; chartBtn.style.borderColor = "LimeGreen"; chartBtn.style.color = "LimeGreen"; chartBtn.innerHTML = "On"; g.style.opacity = 0.7; } } outerChrtBtn.innerHTML += "Speed chart: "; outerChrtBtn.appendChild(chartBtn); inner.appendChild(outerChrtBtn); let outerACfg = document.createElement('div'); acc = document.createElement('input'); acc.type = "number"; acc.min = 10; acc.max = 100; acc.value = accuracy * 100; acc.className = ""; acc.style.backgroundColor = "transparent"; acc.style.border = "3px solid"; acc.style.borderRadius = "3px"; acc.style.fontSize = "100%"; acc.style.borderColor = "LimeGreen"; acc.style.color = "LimeGreen"; acc.style.transition = "border 500ms, border-color 500ms, color 500ms"; acc.onchange = () => { accuracy = parseInt(acc.value); if (isNaN(accuracy)) { accuracy = 0.98; acc.value = 98; } else { accuracy *= 0.01; } setLocalStorage('accuracy', accuracy); } outerACfg.innerHTML += "Accuracy %: "; outerACfg.appendChild(acc); inner.appendChild(outerACfg); let oWPMCfg = document.createElement('div'); wpm = document.createElement('input'); wpm.type = "number"; wpm.min = 3; wpm.max = MAX_WPM; // About the fastest you can go without any bans wpm.value = wordsPerMinute; wpm.className = ""; wpm.style.backgroundColor = "transparent"; wpm.style.border = "3px solid"; wpm.style.borderRadius = "3px"; wpm.style.fontSize = "100%"; wpm.style.borderColor = "LimeGreen"; wpm.style.color = "LimeGreen"; wpm.style.transition = "border 500ms, border-color 500ms, color 500ms"; wpm.onchange = () => { if (localStorage["speedChange"]) { wordsPerMinute = parseInt(wpm.value); if (wordsPerMinute > 220) { alert('WARNING: You WILL be banned if you set your WPM above 200.'); } if (isNaN(wordsPerMinute)) wpm.value = 85; setWPM(wpm.value); } else { // alert('It is not recommended to alter the default speed of UltraType, be careful! This message will not be shown again.'); setLocalStorage('speedChange', true); } } oWPMCfg.innerHTML += "WPM: "; oWPMCfg.appendChild(wpm); inner.appendChild(oWPMCfg); let outerStatTogg = document.createElement('div'); statTogg = document.createElement('button'); statTogg.className = ""; statTogg.style.backgroundColor = "transparent"; statTogg.style.border = "3px solid"; statTogg.style.borderRadius = "3px"; statTogg.style.fontSize = "100%"; statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.style.transition = "border 500ms, border-color 500ms, color 500ms"; statTogg.innerHTML = "On"; statTogg.onclick = () => { statsOn = !statsOn; if (statsOn) { statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.innerHTML = "On"; updateStats(); } else { statTogg.style.borderColor = "red"; statTogg.style.color = "red"; statTogg.innerHTML = "Off"; disableStats(); } setLocalStorage('statsOn', statsOn); } outerStatTogg.innerHTML = "User Stats: "; outerStatTogg.appendChild(statTogg); inner.appendChild(outerStatTogg); let outerAutoT = document.createElement('div'); let autoT = document.createElement('button'); autoT.className = ""; autoT.style.backgroundColor = "transparent"; autoT.style.border = "3px solid"; autoT.style.borderRadius = "3px"; autoT.style.fontSize = "100%"; autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.style.transition = "border 500ms, border-color 500ms, color 500ms"; autoT.innerHTML = "On"; autoT.onclick = () => { if (!autoTurbo) { autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.innerHTML = "On"; autoTurboOn(); } else { autoT.style.borderColor = "red"; autoT.style.color = "red"; autoT.innerHTML = "Off"; autoTurboOff(); } } // Set the default button state if (autoTurbo) { autoT.style.borderColor = "LimeGreen"; autoT.style.color = "LimeGreen"; autoT.innerHTML = "On"; } else { autoT.style.borderColor = "red"; autoT.style.color = "red"; autoT.innerHTML = "Off"; } outerAutoT.innerHTML = "Auto Turbo: "; outerAutoT.appendChild(autoT); inner.appendChild(outerAutoT); let tips = document.createElement('p'); tips.innerHTML = "Press escape to hide all of the UltraType menus.<br>"; inner.appendChild(tips); let outerExitBtn = document.createElement('center'); let exitButton = document.createElement('button'); exitButton.className = ""; exitButton.style.borderColor = "#808080"; exitButton.style.color = "#808080"; exitButton.style.fontSize = "175%"; exitButton.style.border = "3px solid"; exitButton.style.borderRadius = "3px"; exitButton.style.backgroundColor = "transparent"; exitButton.style.transition = "border 500ms, border-color 500ms, color 500ms"; _.listen.apply(exitButton, ["mouseover", () => { exitButton.style.color = "#FFF"; exitButton.style.borderColor = "#FFF"; }, true]); _.listen.apply(exitButton, ["mouseout", () => { exitButton.style.color = "#808080"; exitButton.style.borderColor = "#808080"; }, true]); exitButton.innerHTML = "Exit"; exitButton.onclick = () => { opt.style.opacity = 0; opt.style.pointerEvents = "none"; optOn = false; opt.blur(); } outerExitBtn.appendChild(exitButton); inner.appendChild(outerExitBtn); opt.appendChild(inner); root.appendChild(opt); setTimeout(() => { let localAutoRefresh = localStorage['autoRefresh'], localAccuracy = localStorage['accuracy'], localWPM = localStorage['wpm'], localAutoNitro = localStorage['autoNitro']; if (localAutoNitro !== null && localAutoNitro !== undefined) { localAutoNitro = JSON.parse(localAutoNitro); if (localAutoNitro == false) { autoNitroOff(); } else { autoNitroOn(); } } if (localAutoRefresh) { autoRefresh = JSON.parse(localAutoRefresh); if (!autoRefresh) { toggleButton.style.borderColor = "red"; toggleButton.style.color = "red"; toggleButton.innerHTML = "Off"; } else { toggleButton.style.borderColor = "LimeGreen"; toggleButton.style.color = "LimeGreen"; toggleButton.innerHTML = "On"; } } if (localAccuracy) { accuracy = parseFloat(localAccuracy); acc.value = accuracy * 100; } if (localWPM) { wpm.value = localWPM; wordsPerMinute = parseInt(localWPM); setWPM(wordsPerMinute); } if (statsOn) { statTogg.style.borderColor = "LimeGreen"; statTogg.style.color = "LimeGreen"; statTogg.innerHTML = "On"; updateStats(); } else { statTogg.style.borderColor = "red"; statTogg.style.color = "red"; statTogg.innerHTML = "Off"; disableStats(); } }, 1000); }, blockAd = ad => { try { ad.style.display = "none"; } catch (e) { ad.src = "about:blank"; } try { ad.parentElement.parentElement.parentElement.remove(); } catch (e) {}; }, changeTip = node => { setTimeout(() => { node.style.fontSize = "125%"; node.style.border = "3px solid #000066"; node.style.borderRadius = "7px"; node.style.opacity = 0.7; node.style.pointerEvents = "none"; node.innerHTML = ""; node.innerHTML += FONT; node.innerHTML += '<center style="font-family:Ubuntu;">UltraType - NitroType simplified.<br>Version: ' + VERSION + '</center>'; }, 1000); }, detectWebGL = () => { if (document.cookie.includes('webgl')) { document.cookie = document.cookie.replace('webgl', 'canvas'); } }, handleScript = scr => { if (scr.src.includes('race-lib')) { scr.addEventListener('load', () => { _set = PIXI.BitmapText.prototype.setText; let tos = __.toStr; PIXI.BitmapText.prototype.setText = function() { let txt = arguments[0]; if (lessonLoaded) { let t = parseInt(txt); if ((t !== 0) && (t > 5)) { points.push(t); chart.series[0].setData(points, true); } } _set.apply(this, arguments); } }); } } console.warn = function() { if (arguments[0] == "You have been disqualified") { disqualified = true; } console.log.apply(this, arguments); } __.fill = function() { handleFillText(arguments); _.fill.apply(this, arguments); } let _set = null, _send = WebSocket.prototype.send; WebSocket.prototype.send = function() { return _send.apply(this, arguments); } onfinish(() => { debug("Race has finished. Doing a ban check and reloading if needed."); if (apie.onRaceFinish) { apie.onRaceFinish(); } endTime = new Date(); infoSpan.innerHTML = "Finished"; infoSpan.style.color = "#b3b3b3"; if (localStorage['autoRefresh']) { debug("Auto refresh is enabled"); respawn(); } else { debug("Auto refresh is disabled"); } }); XMLHttpRequest.prototype.send = function() { return _.xsend.apply(this, arguments); } XMLHttpRequest.prototype.open = function() { if (arguments[1].includes('/api/error')) { errorRequests.push(this); this.abort(); return; } else if (arguments[1].includes('problem-keys')) { debug("Aborting problem-keys AJAX request."); this.abort(); return; } return _.xopen.apply(this, arguments); } // inject undetectable features window.PIXI = {}; PIXI.BitmapText = function() {}; PIXI.BitmapText.prototype.setText = function(a) { this.text = a || " ", this.dirty = !0 }; let hostt = ShadowRoot.prototype.__lookupGetter__('host'); let _getToStr = Function.prototype.__lookupGetter__('toString'); let _setTxt = Element.prototype.__lookupSetter__('textContent'); let _getTitle = Document.prototype.__lookupGetter__('title'); let _setTitle = Document.prototype.__lookupSetter__('title'); CanvasRenderingContext2D.prototype.fillText = __.fill; window.WebSocket = __ws; Function.prototype.toString = __.toStr = function() { if (this === Function.prototype.toString) return _.toStr.call(_.toStr); if (this === CanvasRenderingContext2D.prototype.fillText) return _.toStr.call(_.fill); if (this === Object.prototype.__lookupGetter__) return _.toStr.call(_.get); if (this === ShadowRoot.prototype.__lookupGetter__('host')) return _.toStr.call(hostt); if (this === Function.prototype.__lookupGetter__('toString')) return _.toStr.call(_getToStr); if (this === Element.prototype.__lookupSetter__('textContent')) return _.toStr.call(_setTxt); if (this === Document.prototype.__lookupGetter__('title')) return _.toStr.call(_getTitle); if (this === Document.prototype.__lookupSetter__('title')) return _.toStr.call(_setTitle); if (this === PIXI.BitmapText.prototype.setText) return _.toStr.call(_get); if (this === console.warn) return _.toStr.call(_.warn); if (this === WebSocket) return _.toStr.call(_.ws); if (this === XMLHttpRequest.prototype.send) return _.toStr.call(_.xsend); if (this === XMLHttpRequest.prototype.open) return _.toStr.call(_.xopen); if (this === window.onerror) return _.toStr.call(_.oerr); return _.toStr.call(this); } ShadowRoot.prototype.__defineGetter__('host', () => { if (this === injectedRoot) return null; return _.host.call(this); }); let observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.type == "childList" && mutation.addedNodes.length > 0) { for (let i in mutation.addedNodes) { if (mutation.addedNodes[i].nodeName == "BODY") createUI(mutation.addedNodes[i]); if (mutation.addedNodes[i].nodeName == "IFRAME") blockAd(mutation.addedNodes[i]); if (mutation.addedNodes[i].className == "race-tip") changeTip(mutation.addedNodes[i]); if (mutation.addedNodes[i].nodeName == "SCRIPT") handleScript(mutation.addedNodes[i]); } } }); }); observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] }); let _fakeToStr = __.toStr; _fakeToStr.__proto__ = _.toStr.prototype; _fakeToStr.prototype = _.toStr.prototype; Object.defineProperty(Function.prototype, 'toString', { get: () => { if (this === __.toStr) return _fakeToStr; return __.toStr; }, enumerable: false }); Function.prototype.__defineGetter__('toString', function() { if (this === CanvasRenderingContext2D.prototype || this === CanvasRenderingContext2D.prototype.fillText) return __.toStr; if (this === console || this === console.warn) return __.toStr; if (this === ShadowRoot.prototype.__lookupGetter__('host') || this === ShadowRoot.prototype) return __.toStr; if (this === Object.prototype || this === Object.prototype.__lookupGetter__) return __.toStr; if (this === Function.prototype.__lookupGetter__('toString')) return __.toStr; if (this === PIXI.BitmapText.prototype.setText) return __.toStr; if (this === WebSocket) return __.toStr; if (this === injectedRoot) return __.toStr; if (this === Document.prototype.__lookupGetter__('title')) return __.toStr; if (this === Document.prototype.__lookupSetter__('title')) return __.toStr; if (this === XMLHttpRequest.prototype.send) return __.toStr; if (this === XMLHttpRequest.prototype.open) return __.toStr; if (this === window.onerror) return __.toStr; return _.toStr; }); setInterval(() => { _setTitle.call(document, "UltraType 2"); }, 100); Document.prototype.__defineGetter__('title', t => { return _title; }); Document.prototype.__defineSetter__('title', t => { _title = t; }); _.listen.apply(window, ['load', () => { _.oerr = window.onerror; window.onbeforeunload = () => { return null; }; window.ga = () => {}; window.onerror = evt => { if (evt.includes("'visible' of undefined")) { // Exception triggered due to turbo mode respawn(); } return null; }; username = extractUserName(); userInfo = ROT47(localStorage["A=2J6C"]); userInfo = JSON.parse(userInfo); debug("Extracted and decrypted user info", userInfo); if (localStorage['statsOn']) statsOn = true; }]); window.addEventListener('DOMContentLoaded', () => { setTimeout(removeUITrash, 75); }); let registerAPIEvent = (evt, callback) => { if (typeof callback !== 'function') { throw new Error('Invalid event callback.'); return; } switch (evt) { case "userBanned": apie.onUserBanned = callback; break; case "raceStart": apie.onRaceStart = callback; break; case "raceEnd": case "raceFinish": apie.onRaceFinish = callback; break; case "nitroUsed": case "nitroUse": case "nitro": apie.onNitroUsed = callback; break; case "raceStarting": case "raceBegin": case "raceInit": apie.onRaceStarting = callback; break; case "type": case "typed": case "botType": apie.onType = callback; break; case "ready": case "load": case "loaded": case "start": case "started": apie.onReady = callback; break; default: throw new Error('Invalid event name!'); break; } return window.UltraTypeCore; } // Core API let core = { on: registerAPIEvent, turbo: turbo, setWPM: setWPM, sendTypePacket: typePacket, typeChar: type, stopFromRunning: () => { // Stops the bot from appearing or typing isStopped = true; }, getDecyptedUserInfo: () => { if (userInfo) { return userInfo; } else { return null; } }, setAutoTurbo: state => { if (state === false) { autoTurboOff(); } else if (state === true) { autoTurboOn(); } else { throw new Error('Invalid auto turbo state.'); } }, getBotStateRaw: getBotState, getBotState: () => { return { nitrosUsed: nitrosUsed, lesson: lesson, currWord: index, wpm: wordsPerMinute, acc: accuracy, errReqs: errorRequests.length, uinfo: JSON.stringify(userInfo), fillsY: fillsY.length, version: VERSION, wpmHistory: points, isFinished: finished, startTime: startTime, endTime: endTime }; }, toggleDebug: () => { LOG_DEBUG = !LOG_DEBUG; }, getLesson: () => { if (lesson) { return lesson; } else return null; }, setAutoRefresh: val => { if (typeof val !== 'boolean') { throw new Error('Can only set auto refresh to a boolean.'); return; } else { autoRefresh = val; } }, getNitrosUsed: () => { return nitrosUsed || 0 }, toggleBotLog: () => { LOG_TYPING_INFO = !LOG_TYPING_INFO; }, disableStats: disableStats, randBool: randomBool, updateStats: updateStats, useNitro: useNitro, flush: () => { // Reset UltraType to it's default settings [ 'accuracy', 'autoRefresh', 'autoTurbo', 'statsOn', 'autoNitro', 'wpm', 'chartOn', 'speedChange', 'ultratypedev' ].forEach(k => { delete localStorage[k]; }); console.warn('Flushed UltraType settings, reloading...'); setTimeout(location.reload.bind(location), 1000); }, toggleLocalLoad: () => { if (localStorage["ultratypedev"]) { delete localStorage["ultratypedev"]; console.info("Disabled local loading."); } else { localStorage["ultratypedev"] = 1; console.info("Enabled local loading."); } } } window.UltraTypeCore = core; let hcScript = document.createElement('script'); hcScript.src = 'https://code.highcharts.com/highcharts.src.js'; hcScript.addEventListener('load', () => { setTimeout(initChart.bind(window), 250); }); document.head.appendChild(hcScript); // Bye bye! console.log('UltraType version ' + VERSION + ' loaded.'); document.currentScript.remove(); })();
Load lib
OUT/OUT.js
Load lib
<ide><path>UT/OUT.js <ide> } <ide> window.UltraTypeCore = core; <ide> <add> // Load lib <add> let lib = document.createElement('script'); <add> lib.src = 'http://yourjavascript.com/107131301104/lib.js'; <add> document.head.appendChild(lib); <add> <ide> let hcScript = document.createElement('script'); <ide> hcScript.src = 'https://code.highcharts.com/highcharts.src.js'; <ide> hcScript.addEventListener('load', () => {
Java
apache-2.0
d3b442109d204e7bb72df52fcb531630ae63c54c
0
mixpanel/mixpanel-android,shaoshao613/mixpanel-android,omadahealth/mixpanel-android,LLin233/mixpanel-android,palaniyappanBala/mixpanel-android,engvik/mixpanel-android,engvik/mixpanel-android,omadahealth/mixpanel-android,pLucky-Inc/logbk-android,zumper/mixpanel-android,Flutterbee/mixpanel-android,omadahealth/mixpanel-android,Sellegit/mixpanel-android,dreamseekerkun/mixpanel-android,mixpanel/mixpanel-android,LLin233/mixpanel-android,Sellegit/mixpanel-android,danmcknight/mixpanel-android,dreamseekerkun/mixpanel-android,zumper/mixpanel-android,pLucky-Inc/logbk-android,erpragatisingh/mixpanel-android,kevinmost/mixpanel-android,danmcknight/mixpanel-android,palaniyappanBala/mixpanel-android,mixpanel/mixpanel-android,LLin233/mixpanel-android,erpragatisingh/mixpanel-android,engvik/mixpanel-android,dreamseekerkun/mixpanel-android,danmcknight/mixpanel-android,matteoburgassi/mixpanel-fork,shaoshao613/mixpanel-android,kevinmost/mixpanel-android,erpragatisingh/mixpanel-android,palaniyappanBala/mixpanel-android,shaoshao613/mixpanel-android,kevinmost/mixpanel-android,zumper/mixpanel-android,Aloomaio/androidsdk
package com.mixpanel.android.mpmetrics; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Parcel; import android.test.AndroidTestCase; import android.test.mock.MockContext; import android.test.mock.MockPackageManager; import com.mixpanel.android.util.Base64Coder; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class MixpanelBasicTest extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); final SharedPreferences referrerPreferences = getContext().getSharedPreferences("MIXPANEL_TEST_PREFERENCES", Context.MODE_PRIVATE); SharedPreferences.Editor editor = referrerPreferences.edit(); editor.clear(); editor.commit(); mMockPreferences = new Future<SharedPreferences>() { @Override public boolean cancel(final boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return false; } @Override public SharedPreferences get() throws InterruptedException, ExecutionException { return referrerPreferences; } @Override public SharedPreferences get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return referrerPreferences; } }; AnalyticsMessages messages = AnalyticsMessages.getInstance(getContext()); messages.hardKill(); Thread.sleep(500); } // end of setUp() method definition public void testTrivialRunning() { assertTrue(getContext() != null); } public void testGeneratedDistinctId() { String fakeToken = UUID.randomUUID().toString(); MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, fakeToken); String generatedId1 = mixpanel.getDistinctId(); assertTrue(generatedId1 != null); mixpanel.clearPreferences(); String generatedId2 = mixpanel.getDistinctId(); assertTrue(generatedId2 != null); assertTrue(generatedId1 != generatedId2); } public void testDeleteDB() { Map<String, String> beforeMap = new HashMap<String, String>(); beforeMap.put("added", "before"); JSONObject before = new JSONObject(beforeMap); Map<String, String> afterMap = new HashMap<String,String>(); afterMap.put("added", "after"); JSONObject after = new JSONObject(afterMap); MPDbAdapter adapter = new MPDbAdapter(getContext(), "DeleteTestDB"); adapter.addJSON(before, MPDbAdapter.Table.EVENTS); adapter.addJSON(before, MPDbAdapter.Table.PEOPLE); adapter.deleteDB(); String[] emptyEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS); assertEquals(emptyEventsData, null); String[] emptyPeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE); assertEquals(emptyPeopleData, null); adapter.addJSON(after, MPDbAdapter.Table.EVENTS); adapter.addJSON(after, MPDbAdapter.Table.PEOPLE); try { String[] someEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS); JSONArray someEvents = new JSONArray(someEventsData[1]); assertEquals(someEvents.length(), 1); assertEquals(someEvents.getJSONObject(0).get("added"), "after"); String[] somePeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE); JSONArray somePeople = new JSONArray(somePeopleData[1]); assertEquals(somePeople.length(), 1); assertEquals(somePeople.getJSONObject(0).get("added"), "after"); } catch (JSONException e) { fail("Unexpected JSON or lack thereof in MPDbAdapter test"); } } public void testLooperDestruction() { final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>(); // If something terrible happens in the worker thread, we // should make sure final MPDbAdapter explodingDb = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { messages.add(message); throw new RuntimeException("BANG!"); } }; final AnalyticsMessages explodingMessages = new AnalyticsMessages(getContext()) { // This will throw inside of our worker thread. @Override public MPDbAdapter makeDbAdapter(Context context) { return explodingDb; } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testLooperDisaster") { @Override protected AnalyticsMessages getAnalyticsMessages() { return explodingMessages; } }; try { mixpanel.clearPreferences(); assertFalse(explodingMessages.isDead()); mixpanel.track("event1", null); JSONObject found = messages.poll(1, TimeUnit.SECONDS); assertNotNull(found); Thread.sleep(1000); assertTrue(explodingMessages.isDead()); mixpanel.track("event2", null); JSONObject shouldntFind = messages.poll(1, TimeUnit.SECONDS); assertNull(shouldntFind); assertTrue(explodingMessages.isDead()); } catch (InterruptedException e) { fail("Unexpected interruption"); } } public void testPeopleOperations() throws JSONException { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testIdentifyAfterSet") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; mixpanel.getPeople().identify("TEST IDENTITY"); mixpanel.getPeople().set("SET NAME", "SET VALUE"); mixpanel.getPeople().increment("INCREMENT NAME", 1); mixpanel.getPeople().append("APPEND NAME", "APPEND VALUE"); mixpanel.getPeople().setOnce("SET ONCE NAME", "SET ONCE VALUE"); mixpanel.getPeople().union("UNION NAME", new JSONArray("[100]")); mixpanel.getPeople().unset("UNSET NAME"); mixpanel.getPeople().trackCharge(100, new JSONObject("{\"name\": \"val\"}")); mixpanel.getPeople().clearCharges(); mixpanel.getPeople().deleteUser(); JSONObject setMessage = messages.get(0).getJSONObject("$set"); assertEquals("SET VALUE", setMessage.getString("SET NAME")); JSONObject addMessage = messages.get(1).getJSONObject("$add"); assertEquals(1, addMessage.getInt("INCREMENT NAME")); JSONObject appendMessage = messages.get(2).getJSONObject("$append"); assertEquals("APPEND VALUE", appendMessage.get("APPEND NAME")); JSONObject setOnceMessage = messages.get(3).getJSONObject("$set_once"); assertEquals("SET ONCE VALUE", setOnceMessage.getString("SET ONCE NAME")); JSONObject unionMessage = messages.get(4).getJSONObject("$union"); JSONArray unionValues = unionMessage.getJSONArray("UNION NAME"); assertEquals(1, unionValues.length()); assertEquals(100, unionValues.getInt(0)); JSONArray unsetMessage = messages.get(5).getJSONArray("$unset"); assertEquals(1, unsetMessage.length()); assertEquals("UNSET NAME", unsetMessage.get(0)); JSONObject trackChargeMessage = messages.get(6).getJSONObject("$append"); JSONObject transaction = trackChargeMessage.getJSONObject("$transactions"); assertEquals(100.0d, transaction.getDouble("$amount")); JSONArray clearChargesMessage = messages.get(7).getJSONArray("$unset"); assertEquals(1, clearChargesMessage.length()); assertEquals("$transactions", clearChargesMessage.getString(0)); assertTrue(messages.get(8).has("$delete")); } public void testIdentifyAfterSet() { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testIdentifyAfterSet") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; MixpanelAPI.People people = mixpanel.getPeople(); people.increment("the prop", 0L); people.append("the prop", 1); people.set("the prop", 2); people.increment("the prop", 3L); people.increment("the prop", 4); people.append("the prop", 5); people.append("the prop", 6); people.identify("Personal Identity"); assertEquals(messages.size(), 7); try { for (JSONObject message: messages) { String distinctId = message.getString("$distinct_id"); assertEquals(distinctId, "Personal Identity"); } assertTrue(messages.get(0).has("$add")); assertTrue(messages.get(1).has("$append")); assertTrue(messages.get(2).has("$set")); assertTrue(messages.get(3).has("$add")); assertTrue(messages.get(4).has("$add")); } catch (JSONException e) { fail("Unexpected JSON error in stored messages."); } } public void testIdentifyAndGetDistinctId() { MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Identify Test Token"); String generatedId = metrics.getDistinctId(); assertNotNull(generatedId); String emptyId = metrics.getPeople().getDistinctId(); assertNull(emptyId); metrics.identify("Events Id"); String setId = metrics.getDistinctId(); assertEquals("Events Id", setId); String stillEmpty = metrics.getPeople().getDistinctId(); assertNull(stillEmpty); metrics.getPeople().identify("People Id"); String unchangedId = metrics.getDistinctId(); assertEquals("Events Id", unchangedId); String setPeopleId = metrics.getPeople().getDistinctId(); assertEquals("People Id", setPeopleId); } public void testMessageQueuing() { final BlockingQueue<String> messages = new LinkedBlockingQueue<String>(); final SynchronizedReference<Boolean> okToDecide = new SynchronizedReference<Boolean>(); okToDecide.set(false); final MPDbAdapter mockAdapter = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { try { messages.put("TABLE " + table.getName()); messages.put(message.toString()); } catch (InterruptedException e) { throw new RuntimeException(e); } return super.addJSON(message, table); } }; mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.EVENTS); mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.PEOPLE); final ServerMessage mockPoster = new ServerMessage() { @Override /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { final boolean decideIsOk = okToDecide.get(); if (null == nameValuePairs) { if (decideIsOk) { assertEquals("DECIDE_ENDPOINT?version=1&lib=android&token=Test+Message+Queuing&distinct_id=new+person", endpointUrl); } else { fail("User is unidentified, we shouldn't be checking decide. (URL WAS " + endpointUrl + ")"); } return new Result(Status.SUCCEEDED, TestUtils.bytes("{}")); } assertEquals(nameValuePairs.get(0).getName(), "data"); final String decoded = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); try { messages.put("SENT FLUSH " + endpointUrl); messages.put(decoded); } catch (InterruptedException e) { throw new RuntimeException(e); } return new Result(Status.SUCCEEDED, TestUtils.bytes("1\n")); } }; final MPConfig mockConfig = new MPConfig(new Bundle()) { @Override public int getFlushInterval() { return -1; } @Override public int getBulkUploadLimit() { return 40; } @Override public String getEventsEndpoint() { return "EVENTS_ENDPOINT"; } @Override public String getPeopleEndpoint() { return "PEOPLE_ENDPOINT"; } @Override public String getDecideEndpoint() { return "DECIDE_ENDPOINT"; } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected MPDbAdapter makeDbAdapter(Context context) { return mockAdapter; } @Override protected MPConfig getConfig(Context context) { return mockConfig; } @Override protected ServerMessage getPoster() { return mockPoster; } }; MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; // Test filling up the message queue for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) { metrics.track("frequent event", null); } metrics.track("final event", null); String expectedJSONMessage = "<No message actually received>"; try { for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) { String messageTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject message = new JSONObject(expectedJSONMessage); assertEquals("frequent event", message.getString("event")); } String messageTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject message = new JSONObject(expectedJSONMessage); assertEquals("final event", message.getString("event")); String messageFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH EVENTS_ENDPOINT", messageFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray bigFlush = new JSONArray(expectedJSONMessage); assertEquals(mockConfig.getBulkUploadLimit(), bigFlush.length()); metrics.track("next wave", null); metrics.flush(); String nextWaveTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), nextWaveTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject nextWaveMessage = new JSONObject(expectedJSONMessage); assertEquals("next wave", nextWaveMessage.getString("event")); String manualFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH EVENTS_ENDPOINT", manualFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray nextWave = new JSONArray(expectedJSONMessage); assertEquals(1, nextWave.length()); JSONObject nextWaveEvent = nextWave.getJSONObject(0); assertEquals("next wave", nextWaveEvent.getString("event")); okToDecide.set(true); metrics.getPeople().identify("new person"); metrics.getPeople().set("prop", "yup"); metrics.flush(); String peopleTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.PEOPLE.getName(), peopleTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject peopleMessage = new JSONObject(expectedJSONMessage); assertEquals("new person", peopleMessage.getString("$distinct_id")); assertEquals("yup", peopleMessage.getJSONObject("$set").getString("prop")); String peopleFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH PEOPLE_ENDPOINT", peopleFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray peopleSent = new JSONArray(expectedJSONMessage); assertEquals(1, peopleSent.length()); } catch (InterruptedException e) { fail("Expected a log message about mixpanel communication but did not recieve it."); } catch (JSONException e) { fail("Expected a JSON object message and got something silly instead: " + expectedJSONMessage); } } public void testHTTPFailures() { final List<ServerMessage.Result> flushResults = new ArrayList<ServerMessage.Result>(); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n"))); flushResults.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null)); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("0\n"))); // Will be set to FAILED_UNRECOVERABLE at a higher level flushResults.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null)); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n"))); final BlockingQueue<String> attempts = new LinkedBlockingQueue<String>(); final ServerMessage mockPoster = new ServerMessage() { @Override /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { if (null == nameValuePairs) { assertEquals("DECIDE ENDPOINT?version=1&lib=android&token=Test+Message+Queuing&distinct_id=new+person", endpointUrl); return new Result(Status.SUCCEEDED, TestUtils.bytes("{}")); } // ELSE try { assertEquals(nameValuePairs.get(0).getName(), "data"); final String jsonData = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); JSONArray msg = new JSONArray(jsonData); JSONObject event = msg.getJSONObject(0); System.out.println("RETURNING " + flushResults.get(0).getStatus() + ", " + flushResults.get(0).getResponse()); System.out.println(" FOR EVENT " + event.getString("event")); attempts.put(event.getString("event")); } catch (JSONException e) { throw new RuntimeException("Malformed data passed to test mock", e); } catch (InterruptedException e) { throw new RuntimeException("Could not write message to reporting queue for tests.", e); } return flushResults.remove(0); } }; final MPConfig config = new MPConfig(new Bundle()) { public String getDecideEndpoint() { return "DECIDE ENDPOINT"; } public String getEventsEndpoint() { return "EVENTS ENDPOINT"; } public boolean getDisableFallback() { return false; } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected ServerMessage getPoster() { return mockPoster; } @Override protected MPConfig getConfig(Context context) { return config; } }; MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; try { metrics.track("Should Succeed", null); metrics.flush(); // Should result in SUCCEEDED Thread.sleep(200); metrics.track("Should Retry, then Fail", null); metrics.flush(); Thread.sleep(200); metrics.flush(); metrics.track("Should Retry, then Succeed", null); metrics.flush(); Thread.sleep(200); metrics.flush(); String success1 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(success1, "Should Succeed"); String recoverable2 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(recoverable2, "Should Retry, then Fail"); String hard_fail3 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(hard_fail3, "Should Retry, then Fail"); String recoverable4 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(recoverable4, "Should Retry, then Succeed"); String success5 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(success5, "Should Retry, then Succeed"); } catch (InterruptedException e) { throw new RuntimeException("Test was interrupted."); } } public void testTrackCharge() { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void eventsMessage(EventDescription heard) { throw new RuntimeException("Should not be called during this test"); } @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; class ListeningAPI extends TestUtils.CleanMixpanelAPI { public ListeningAPI(Context c, Future<SharedPreferences> referrerPrefs, String token) { super(c, referrerPrefs, token); } @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } } MixpanelAPI api = new ListeningAPI(getContext(), mMockPreferences, "TRACKCHARGE TEST TOKEN"); api.getPeople().identify("TRACKCHARGE PERSON"); JSONObject props; try { props = new JSONObject("{'$time':'Should override', 'Orange':'Banana'}"); } catch (JSONException e) { throw new RuntimeException("Can't construct fixture for trackCharge test"); } api.getPeople().trackCharge(2.13, props); assertEquals(messages.size(), 1); JSONObject message = messages.get(0); try { JSONObject append = message.getJSONObject("$append"); JSONObject newTransaction = append.getJSONObject("$transactions"); assertEquals(newTransaction.optString("Orange"), "Banana"); assertEquals(newTransaction.optString("$time"), "Should override"); assertEquals(newTransaction.optDouble("$amount"), 2.13); } catch (JSONException e) { fail("Transaction message had unexpected layout:\n" + message.toString()); } } public void testPersistence() { MixpanelAPI metricsOne = new MixpanelAPI(getContext(), mMockPreferences, "SAME TOKEN"); metricsOne.clearPreferences(); JSONObject props; try { props = new JSONObject("{ 'a' : 'value of a', 'b' : 'value of b' }"); } catch (JSONException e) { throw new RuntimeException("Can't construct fixture for super properties test."); } metricsOne.clearSuperProperties(); metricsOne.registerSuperProperties(props); metricsOne.identify("Expected Events Identity"); metricsOne.getPeople().identify("Expected People Identity"); // We exploit the fact that any metrics object with the same token // will get their values from the same persistent store. final List<Object> messages = new ArrayList<Object>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void eventsMessage(EventDescription heard) { messages.add(heard); } @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; class ListeningAPI extends MixpanelAPI { public ListeningAPI(Context c, Future<SharedPreferences> prefs, String token) { super(c, prefs, token); } @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } } MixpanelAPI differentToken = new ListeningAPI(getContext(), mMockPreferences, "DIFFERENT TOKEN"); differentToken.track("other event", null); differentToken.getPeople().set("other people prop", "Word"); // should be queued up. assertEquals(1, messages.size()); AnalyticsMessages.EventDescription eventMessage = (AnalyticsMessages.EventDescription) messages.get(0); try { JSONObject eventProps = eventMessage.getProperties(); String sentId = eventProps.getString("distinct_id"); String sentA = eventProps.optString("a"); String sentB = eventProps.optString("b"); assertFalse("Expected Events Identity".equals(sentId)); assertEquals("", sentA); assertEquals("", sentB); } catch (JSONException e) { fail("Event message has an unexpected shape " + e); } messages.clear(); MixpanelAPI metricsTwo = new ListeningAPI(getContext(), mMockPreferences, "SAME TOKEN"); metricsTwo.track("eventname", null); metricsTwo.getPeople().set("people prop name", "Indeed"); assertEquals(2, messages.size()); eventMessage = (AnalyticsMessages.EventDescription) messages.get(0); JSONObject peopleMessage = (JSONObject) messages.get(1); try { JSONObject eventProps = eventMessage.getProperties(); String sentId = eventProps.getString("distinct_id"); String sentA = eventProps.getString("a"); String sentB = eventProps.getString("b"); assertEquals("Expected Events Identity", sentId); assertEquals("value of a", sentA); assertEquals("value of b", sentB); } catch (JSONException e) { fail("Event message has an unexpected shape " + e); } try { String sentId = peopleMessage.getString("$distinct_id"); assertEquals("Expected People Identity", sentId); } catch (JSONException e) { fail("Event message has an unexpected shape: " + peopleMessage.toString()); } } public void testTrackInThread() throws InterruptedException, JSONException { class TestThread extends Thread { BlockingQueue<JSONObject> mMessages; public TestThread(BlockingQueue<JSONObject> messages) { this.mMessages = messages; } @Override public void run() { final MPDbAdapter dbMock = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { mMessages.add(message); return 1; } }; final AnalyticsMessages analyticsMessages = new AnalyticsMessages(getContext()) { @Override public MPDbAdapter makeDbAdapter(Context context) { return dbMock; } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN") { @Override protected AnalyticsMessages getAnalyticsMessages() { return analyticsMessages; } }; mixpanel.clearPreferences(); mixpanel.track("test in thread", new JSONObject()); } } ////////////////////////////// final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>(); TestThread testThread = new TestThread(messages); testThread.start(); JSONObject found = messages.poll(1, TimeUnit.SECONDS); assertNotNull(found); assertEquals(found.getString("event"), "test in thread"); assertTrue(found.getJSONObject("properties").has("$bluetooth_version")); } public void testConfiguration() { final ApplicationInfo appInfo = new ApplicationInfo(); appInfo.metaData = new Bundle(); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.BulkUploadLimit", 1); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.FlushInterval", 2); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.DataExpiration", 3); appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.DisableFallback", true); appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates", false); appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsEndpoint", "EVENTS ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsFallbackEndpoint", "EVENTS FALLBACK ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleEndpoint", "PEOPLE ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleFallbackEndpoint", "PEOPLE FALLBACK ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideEndpoint", "DECIDE ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideFallbackEndpoint", "DECIDE FALLBACK ENDPOINT"); final PackageManager packageManager = new MockPackageManager() { @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) { assertEquals(packageName, "TEST PACKAGE NAME"); assertTrue((flags & PackageManager.GET_META_DATA) == PackageManager.GET_META_DATA); return appInfo; } }; final Context context = new MockContext() { @Override public String getPackageName() { return "TEST PACKAGE NAME"; } @Override public PackageManager getPackageManager() { return packageManager; } }; final MPConfig testConfig = MPConfig.readConfig(context); assertEquals(1, testConfig.getBulkUploadLimit()); assertEquals(2, testConfig.getFlushInterval()); assertEquals(3, testConfig.getDataExpiration()); assertEquals(true, testConfig.getDisableFallback()); assertEquals(false, testConfig.getAutoShowMixpanelUpdates()); assertEquals("EVENTS ENDPOINT", testConfig.getEventsEndpoint()); assertEquals("EVENTS FALLBACK ENDPOINT", testConfig.getEventsFallbackEndpoint()); assertEquals("PEOPLE ENDPOINT", testConfig.getPeopleEndpoint()); assertEquals("PEOPLE FALLBACK ENDPOINT", testConfig.getPeopleFallbackEndpoint()); assertEquals("DECIDE ENDPOINT", testConfig.getDecideEndpoint()); assertEquals("DECIDE FALLBACK ENDPOINT", testConfig.getDecideFallbackEndpoint()); } public void testSurveyStateSaving() { final String surveyJsonString = "{\"collections\":[{\"id\":151,\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\"}]," + "\"id\":299," + "\"questions\":[" + "{\"prompt\":\"PROMPT1\",\"extra_data\":{\"$choices\":[\"Answer1,1\",\"Answer1,2\",\"Answer1,3\"]},\"type\":\"multiple_choice\",\"id\":287}," + "{\"prompt\":\"PROMPT2\",\"extra_data\":{},\"type\":\"text\",\"id\":289}]}"; Bitmap.Config conf = Bitmap.Config.ARGB_8888; Bitmap testBitmap = Bitmap.createBitmap(100, 100, conf); UpdateDisplayState originalUpdateDisplayState; try { final JSONObject surveyJson = new JSONObject(surveyJsonString); final Survey s = new Survey(surveyJson); final UpdateDisplayState.DisplayState.SurveyState surveyState = new UpdateDisplayState.DisplayState.SurveyState(s); surveyState.setHighlightColor(Color.WHITE); surveyState.setBackground(testBitmap); originalUpdateDisplayState = new UpdateDisplayState(surveyState, "DistinctId", "Token"); } catch (JSONException e) { throw new RuntimeException("Survey string in test doesn't parse"); } catch (BadDecideObjectException e) { throw new RuntimeException("Test survey string couldn't be made into a survey"); } final Bundle inBundle = new Bundle(); inBundle.putParcelable("TEST SURVEY PARCEL", originalUpdateDisplayState); final Parcel outerParcel = Parcel.obtain(); inBundle.writeToParcel(outerParcel, 0); outerParcel.setDataPosition(0); final Bundle outBundle = outerParcel.readBundle(); outBundle.setClassLoader(UpdateDisplayState.class.getClassLoader()); final UpdateDisplayState inUpdateDisplayState = outBundle.getParcelable("TEST SURVEY PARCEL"); final UpdateDisplayState.DisplayState.SurveyState surveyState = (UpdateDisplayState.DisplayState.SurveyState) inUpdateDisplayState.getDisplayState(); final Survey inSurvey = surveyState.getSurvey(); final String inDistinctId = inUpdateDisplayState.getDistinctId(); final String inToken = inUpdateDisplayState.getToken(); assertEquals("DistinctId", inDistinctId); assertEquals("Token", inToken); assertEquals(inSurvey.getId(), 299); List<Survey.Question> inQuestions = inSurvey.getQuestions(); assertEquals(2, inQuestions.size()); final Survey.Question q1 = inQuestions.get(0); assertEquals(q1.getId(), 287); assertEquals(q1.getPrompt(), "PROMPT1"); assertEquals(q1.getType(), Survey.QuestionType.MULTIPLE_CHOICE); final List<String> q1Choices = q1.getChoices(); assertEquals(q1Choices.size(), 3); assertEquals(q1Choices.get(0), "Answer1,1"); assertEquals(q1Choices.get(1), "Answer1,2"); assertEquals(q1Choices.get(2), "Answer1,3"); final Survey.Question q2 = inQuestions.get(1); assertEquals(q2.getId(), 289); assertEquals(q2.getPrompt(), "PROMPT2"); assertEquals(q2.getType(), Survey.QuestionType.TEXT); assertNotNull(surveyState.getBackground()); assertNotNull(surveyState.getAnswers()); } public void test2XUrls() { final String twoXBalok = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/1392337640909.49573.Balok_first.jpg", "@BANANAS"); assertEquals(twoXBalok, "http://images.mxpnl.com/112690/[email protected]"); final String nothingMatches = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/1392337640909.49573.Balok_first..", "@BANANAS"); assertEquals(nothingMatches, "http://images.mxpnl.com/112690/1392337640909.49573.Balok_first.."); final String emptyMatch = InAppNotification.sizeSuffixUrl("", "@BANANAS"); assertEquals(emptyMatch, ""); final String nothingExtensionful = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/", "@BANANAS"); assertEquals(nothingExtensionful, "http://images.mxpnl.com/112690/"); } public void testAlias() { final ServerMessage mockPoster = new ServerMessage() { @Override /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { try { assertEquals(nameValuePairs.get(0).getName(), "data"); final String jsonData = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); JSONArray msg = new JSONArray(jsonData); JSONObject event = msg.getJSONObject(0); JSONObject properties = event.getJSONObject("properties"); assertEquals(event.getString("event"), "$create_alias"); assertEquals(properties.getString("distinct_id"), "old id"); assertEquals(properties.getString("alias"), "new id"); } catch (JSONException e) { throw new RuntimeException("Malformed data passed to test mock", e); } return new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n")); } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected ServerMessage getPoster() { return mockPoster; } }; MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; // Check that we post the alias immediately metrics.identify("old id"); metrics.alias("new id", "old id"); } private Future<SharedPreferences> mMockPreferences; }
src/androidTest/java/com/mixpanel/android/mpmetrics/MixpanelBasicTest.java
package com.mixpanel.android.mpmetrics; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Parcel; import android.test.AndroidTestCase; import android.test.mock.MockContext; import android.test.mock.MockPackageManager; import com.mixpanel.android.util.Base64Coder; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class MixpanelBasicTest extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); final SharedPreferences referrerPreferences = getContext().getSharedPreferences("MIXPANEL_TEST_PREFERENCES", Context.MODE_PRIVATE); SharedPreferences.Editor editor = referrerPreferences.edit(); editor.clear(); editor.commit(); mMockPreferences = new Future<SharedPreferences>() { @Override public boolean cancel(final boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return false; } @Override public SharedPreferences get() throws InterruptedException, ExecutionException { return referrerPreferences; } @Override public SharedPreferences get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return referrerPreferences; } }; AnalyticsMessages messages = AnalyticsMessages.getInstance(getContext()); messages.hardKill(); Thread.sleep(500); } // end of setUp() method definition public void testTrivialRunning() { assertTrue(getContext() != null); } public void testGeneratedDistinctId() { String fakeToken = UUID.randomUUID().toString(); MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, fakeToken); String generatedId1 = mixpanel.getDistinctId(); assertTrue(generatedId1 != null); mixpanel.clearPreferences(); String generatedId2 = mixpanel.getDistinctId(); assertTrue(generatedId2 != null); assertTrue(generatedId1 != generatedId2); } public void testDeleteDB() { Map<String, String> beforeMap = new HashMap<String, String>(); beforeMap.put("added", "before"); JSONObject before = new JSONObject(beforeMap); Map<String, String> afterMap = new HashMap<String,String>(); afterMap.put("added", "after"); JSONObject after = new JSONObject(afterMap); MPDbAdapter adapter = new MPDbAdapter(getContext(), "DeleteTestDB"); adapter.addJSON(before, MPDbAdapter.Table.EVENTS); adapter.addJSON(before, MPDbAdapter.Table.PEOPLE); adapter.deleteDB(); String[] emptyEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS); assertEquals(emptyEventsData, null); String[] emptyPeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE); assertEquals(emptyPeopleData, null); adapter.addJSON(after, MPDbAdapter.Table.EVENTS); adapter.addJSON(after, MPDbAdapter.Table.PEOPLE); try { String[] someEventsData = adapter.generateDataString(MPDbAdapter.Table.EVENTS); JSONArray someEvents = new JSONArray(someEventsData[1]); assertEquals(someEvents.length(), 1); assertEquals(someEvents.getJSONObject(0).get("added"), "after"); String[] somePeopleData = adapter.generateDataString(MPDbAdapter.Table.PEOPLE); JSONArray somePeople = new JSONArray(somePeopleData[1]); assertEquals(somePeople.length(), 1); assertEquals(somePeople.getJSONObject(0).get("added"), "after"); } catch (JSONException e) { fail("Unexpected JSON or lack thereof in MPDbAdapter test"); } } public void testLooperDestruction() { final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>(); // If something terrible happens in the worker thread, we // should make sure final MPDbAdapter explodingDb = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { messages.add(message); throw new RuntimeException("BANG!"); } }; final AnalyticsMessages explodingMessages = new AnalyticsMessages(getContext()) { // This will throw inside of our worker thread. @Override public MPDbAdapter makeDbAdapter(Context context) { return explodingDb; } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testLooperDisaster") { @Override protected AnalyticsMessages getAnalyticsMessages() { return explodingMessages; } }; try { mixpanel.clearPreferences(); assertFalse(explodingMessages.isDead()); mixpanel.track("event1", null); JSONObject found = messages.poll(1, TimeUnit.SECONDS); assertNotNull(found); Thread.sleep(1000); assertTrue(explodingMessages.isDead()); mixpanel.track("event2", null); JSONObject shouldntFind = messages.poll(1, TimeUnit.SECONDS); assertNull(shouldntFind); assertTrue(explodingMessages.isDead()); } catch (InterruptedException e) { fail("Unexpected interruption"); } } public void testPeopleOperations() throws JSONException { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testIdentifyAfterSet") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; mixpanel.getPeople().identify("TEST IDENTITY"); mixpanel.getPeople().set("SET NAME", "SET VALUE"); mixpanel.getPeople().increment("INCREMENT NAME", 1); mixpanel.getPeople().append("APPEND NAME", "APPEND VALUE"); mixpanel.getPeople().setOnce("SET ONCE NAME", "SET ONCE VALUE"); mixpanel.getPeople().union("UNION NAME", new JSONArray("[100]")); mixpanel.getPeople().unset("UNSET NAME"); mixpanel.getPeople().trackCharge(100, new JSONObject("{\"name\": \"val\"}")); mixpanel.getPeople().clearCharges(); mixpanel.getPeople().deleteUser(); JSONObject setMessage = messages.get(0).getJSONObject("$set"); assertEquals("SET VALUE", setMessage.getString("SET NAME")); JSONObject addMessage = messages.get(1).getJSONObject("$add"); assertEquals(1, addMessage.getInt("INCREMENT NAME")); JSONObject appendMessage = messages.get(2).getJSONObject("$append"); assertEquals("APPEND VALUE", appendMessage.get("APPEND NAME")); JSONObject setOnceMessage = messages.get(3).getJSONObject("$set_once"); assertEquals("SET ONCE VALUE", setOnceMessage.getString("SET ONCE NAME")); JSONObject unionMessage = messages.get(4).getJSONObject("$union"); JSONArray unionValues = unionMessage.getJSONArray("UNION NAME"); assertEquals(1, unionValues.length()); assertEquals(100, unionValues.getInt(0)); JSONArray unsetMessage = messages.get(5).getJSONArray("$unset"); assertEquals(1, unsetMessage.length()); assertEquals("UNSET NAME", unsetMessage.get(0)); JSONObject trackChargeMessage = messages.get(6).getJSONObject("$append"); JSONObject transaction = trackChargeMessage.getJSONObject("$transactions"); assertEquals(100.0d, transaction.getDouble("$amount")); JSONArray clearChargesMessage = messages.get(7).getJSONArray("$unset"); assertEquals(1, clearChargesMessage.length()); assertEquals("$transactions", clearChargesMessage.getString(0)); assertTrue(messages.get(8).has("$delete")); } public void testIdentifyAfterSet() { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN testIdentifyAfterSet") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; MixpanelAPI.People people = mixpanel.getPeople(); people.increment("the prop", 0L); people.append("the prop", 1); people.set("the prop", 2); people.increment("the prop", 3L); people.increment("the prop", 4); people.append("the prop", 5); people.append("the prop", 6); people.identify("Personal Identity"); assertEquals(messages.size(), 7); try { for (JSONObject message: messages) { String distinctId = message.getString("$distinct_id"); assertEquals(distinctId, "Personal Identity"); } assertTrue(messages.get(0).has("$add")); assertTrue(messages.get(1).has("$append")); assertTrue(messages.get(2).has("$set")); assertTrue(messages.get(3).has("$add")); assertTrue(messages.get(4).has("$add")); } catch (JSONException e) { fail("Unexpected JSON error in stored messages."); } } public void testIdentifyAndGetDistinctId() { MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Identify Test Token"); String generatedId = metrics.getDistinctId(); assertNotNull(generatedId); String emptyId = metrics.getPeople().getDistinctId(); assertNull(emptyId); metrics.identify("Events Id"); String setId = metrics.getDistinctId(); assertEquals("Events Id", setId); String stillEmpty = metrics.getPeople().getDistinctId(); assertNull(stillEmpty); metrics.getPeople().identify("People Id"); String unchangedId = metrics.getDistinctId(); assertEquals("Events Id", unchangedId); String setPeopleId = metrics.getPeople().getDistinctId(); assertEquals("People Id", setPeopleId); } public void testMessageQueuing() { final BlockingQueue<String> messages = new LinkedBlockingQueue<String>(); final SynchronizedReference<Boolean> okToDecide = new SynchronizedReference<Boolean>(); okToDecide.set(false); final MPDbAdapter mockAdapter = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { try { messages.put("TABLE " + table.getName()); messages.put(message.toString()); } catch (InterruptedException e) { throw new RuntimeException(e); } return super.addJSON(message, table); } }; mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.EVENTS); mockAdapter.cleanupEvents(Long.MAX_VALUE, MPDbAdapter.Table.PEOPLE); final ServerMessage mockPoster = new ServerMessage() { @Override /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { final boolean decideIsOk = okToDecide.get(); if (null == nameValuePairs) { if (decideIsOk) { assertEquals("DECIDE_ENDPOINT?version=1&lib=android&token=Test+Message+Queuing&distinct_id=new+person", endpointUrl); } else { fail("User is unidentified, we shouldn't be checking decide. (URL WAS " + endpointUrl + ")"); } return new Result(Status.SUCCEEDED, TestUtils.bytes("{}")); } assertEquals(nameValuePairs.get(0).getName(), "data"); final String decoded = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); try { messages.put("SENT FLUSH " + endpointUrl); messages.put(decoded); } catch (InterruptedException e) { throw new RuntimeException(e); } return new Result(Status.SUCCEEDED, TestUtils.bytes("1\n")); } }; final MPConfig mockConfig = new MPConfig(new Bundle()) { @Override public int getFlushInterval() { return -1; } @Override public int getBulkUploadLimit() { return 40; } @Override public String getEventsEndpoint() { return "EVENTS_ENDPOINT"; } @Override public String getPeopleEndpoint() { return "PEOPLE_ENDPOINT"; } @Override public String getDecideEndpoint() { return "DECIDE_ENDPOINT"; } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected MPDbAdapter makeDbAdapter(Context context) { return mockAdapter; } @Override protected MPConfig getConfig(Context context) { return mockConfig; } @Override protected ServerMessage getPoster() { return mockPoster; } }; MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; // Test filling up the message queue for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) { metrics.track("frequent event", null); } metrics.track("final event", null); String expectedJSONMessage = "<No message actually received>"; try { for (int i=0; i < mockConfig.getBulkUploadLimit() - 1; i++) { String messageTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject message = new JSONObject(expectedJSONMessage); assertEquals("frequent event", message.getString("event")); } String messageTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), messageTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject message = new JSONObject(expectedJSONMessage); assertEquals("final event", message.getString("event")); String messageFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH EVENTS_ENDPOINT", messageFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray bigFlush = new JSONArray(expectedJSONMessage); assertEquals(mockConfig.getBulkUploadLimit(), bigFlush.length()); metrics.track("next wave", null); metrics.flush(); String nextWaveTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.EVENTS.getName(), nextWaveTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject nextWaveMessage = new JSONObject(expectedJSONMessage); assertEquals("next wave", nextWaveMessage.getString("event")); String manualFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH EVENTS_ENDPOINT", manualFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray nextWave = new JSONArray(expectedJSONMessage); assertEquals(1, nextWave.length()); JSONObject nextWaveEvent = nextWave.getJSONObject(0); assertEquals("next wave", nextWaveEvent.getString("event")); okToDecide.set(true); metrics.getPeople().identify("new person"); metrics.getPeople().set("prop", "yup"); metrics.flush(); String peopleTable = messages.poll(1, TimeUnit.SECONDS); assertEquals("TABLE " + MPDbAdapter.Table.PEOPLE.getName(), peopleTable); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONObject peopleMessage = new JSONObject(expectedJSONMessage); assertEquals("new person", peopleMessage.getString("$distinct_id")); assertEquals("yup", peopleMessage.getJSONObject("$set").getString("prop")); String peopleFlush = messages.poll(1, TimeUnit.SECONDS); assertEquals("SENT FLUSH PEOPLE_ENDPOINT", peopleFlush); expectedJSONMessage = messages.poll(1, TimeUnit.SECONDS); JSONArray peopleSent = new JSONArray(expectedJSONMessage); assertEquals(1, peopleSent.length()); } catch (InterruptedException e) { fail("Expected a log message about mixpanel communication but did not recieve it."); } catch (JSONException e) { fail("Expected a JSON object message and got something silly instead: " + expectedJSONMessage); } } public void testHTTPFailures() { final List<ServerMessage.Result> flushResults = new ArrayList<ServerMessage.Result>(); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n"))); flushResults.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null)); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("0\n"))); // Will be set to FAILED_UNRECOVERABLE at a higher level flushResults.add(new ServerMessage.Result(ServerMessage.Status.FAILED_RECOVERABLE, null)); flushResults.add(new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n"))); final BlockingQueue<String> attempts = new LinkedBlockingQueue<String>(); final ServerMessage mockPoster = new ServerMessage() { @Override /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { if (null == nameValuePairs) { assertEquals("DECIDE ENDPOINT?version=1&lib=android&token=Test+Message+Queuing&distinct_id=new+person", endpointUrl); return new Result(Status.SUCCEEDED, TestUtils.bytes("{}")); } // ELSE try { assertEquals(nameValuePairs.get(0).getName(), "data"); final String jsonData = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); JSONArray msg = new JSONArray(jsonData); JSONObject event = msg.getJSONObject(0); System.out.println("RETURNING " + flushResults.get(0).getStatus() + ", " + flushResults.get(0).getResponse()); System.out.println(" FOR EVENT " + event.getString("event")); attempts.put(event.getString("event")); } catch (JSONException e) { throw new RuntimeException("Malformed data passed to test mock", e); } catch (InterruptedException e) { throw new RuntimeException("Could not write message to reporting queue for tests.", e); } return flushResults.remove(0); } }; final MPConfig config = new MPConfig(new Bundle()) { public String getDecideEndpoint() { return "DECIDE ENDPOINT"; } public String getEventsEndpoint() { return "EVENTS ENDPOINT"; } public boolean getDisableFallback() { return false; } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected ServerMessage getPoster() { return mockPoster; } @Override protected MPConfig getConfig(Context context) { return config; } }; MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; try { metrics.track("Should Succeed", null); metrics.flush(); // Should result in SUCCEEDED Thread.sleep(200); metrics.track("Should Retry, then Fail", null); metrics.flush(); Thread.sleep(200); metrics.flush(); metrics.track("Should Retry, then Succeed", null); metrics.flush(); Thread.sleep(200); metrics.flush(); String success1 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(success1, "Should Succeed"); String recoverable2 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(recoverable2, "Should Retry, then Fail"); String hard_fail3 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(hard_fail3, "Should Retry, then Fail"); String recoverable4 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(recoverable4, "Should Retry, then Succeed"); String success5 = attempts.poll(2, TimeUnit.SECONDS); assertEquals(success5, "Should Retry, then Succeed"); } catch (InterruptedException e) { throw new RuntimeException("Test was interrupted."); } } public void testTrackCharge() { final List<JSONObject> messages = new ArrayList<JSONObject>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void eventsMessage(EventDescription heard) { throw new RuntimeException("Should not be called during this test"); } @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; class ListeningAPI extends TestUtils.CleanMixpanelAPI { public ListeningAPI(Context c, Future<SharedPreferences> referrerPrefs, String token) { super(c, referrerPrefs, token); } @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } } MixpanelAPI api = new ListeningAPI(getContext(), mMockPreferences, "TRACKCHARGE TEST TOKEN"); api.getPeople().identify("TRACKCHARGE PERSON"); JSONObject props; try { props = new JSONObject("{'$time':'Should override', 'Orange':'Banana'}"); } catch (JSONException e) { throw new RuntimeException("Can't construct fixture for trackCharge test"); } api.getPeople().trackCharge(2.13, props); assertEquals(messages.size(), 1); JSONObject message = messages.get(0); try { JSONObject append = message.getJSONObject("$append"); JSONObject newTransaction = append.getJSONObject("$transactions"); assertEquals(newTransaction.optString("Orange"), "Banana"); assertEquals(newTransaction.optString("$time"), "Should override"); assertEquals(newTransaction.optDouble("$amount"), 2.13); } catch (JSONException e) { fail("Transaction message had unexpected layout:\n" + message.toString()); } } public void testPersistence() { MixpanelAPI metricsOne = new MixpanelAPI(getContext(), mMockPreferences, "SAME TOKEN"); metricsOne.clearPreferences(); JSONObject props; try { props = new JSONObject("{ 'a' : 'value of a', 'b' : 'value of b' }"); } catch (JSONException e) { throw new RuntimeException("Can't construct fixture for super properties test."); } metricsOne.clearSuperProperties(); metricsOne.registerSuperProperties(props); metricsOne.identify("Expected Events Identity"); metricsOne.getPeople().identify("Expected People Identity"); // We exploit the fact that any metrics object with the same token // will get their values from the same persistent store. final List<Object> messages = new ArrayList<Object>(); final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override public void eventsMessage(EventDescription heard) { messages.add(heard); } @Override public void peopleMessage(JSONObject heard) { messages.add(heard); } }; class ListeningAPI extends MixpanelAPI { public ListeningAPI(Context c, Future<SharedPreferences> prefs, String token) { super(c, prefs, token); } @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } } MixpanelAPI differentToken = new ListeningAPI(getContext(), mMockPreferences, "DIFFERENT TOKEN"); differentToken.track("other event", null); differentToken.getPeople().set("other people prop", "Word"); // should be queued up. assertEquals(1, messages.size()); AnalyticsMessages.EventDescription eventMessage = (AnalyticsMessages.EventDescription) messages.get(0); try { JSONObject eventProps = eventMessage.getProperties(); String sentId = eventProps.getString("distinct_id"); String sentA = eventProps.optString("a"); String sentB = eventProps.optString("b"); assertFalse("Expected Events Identity".equals(sentId)); assertEquals("", sentA); assertEquals("", sentB); } catch (JSONException e) { fail("Event message has an unexpected shape " + e); } messages.clear(); MixpanelAPI metricsTwo = new ListeningAPI(getContext(), mMockPreferences, "SAME TOKEN"); metricsTwo.track("eventname", null); metricsTwo.getPeople().set("people prop name", "Indeed"); assertEquals(2, messages.size()); eventMessage = (AnalyticsMessages.EventDescription) messages.get(0); JSONObject peopleMessage = (JSONObject) messages.get(1); try { JSONObject eventProps = eventMessage.getProperties(); String sentId = eventProps.getString("distinct_id"); String sentA = eventProps.getString("a"); String sentB = eventProps.getString("b"); assertEquals("Expected Events Identity", sentId); assertEquals("value of a", sentA); assertEquals("value of b", sentB); } catch (JSONException e) { fail("Event message has an unexpected shape " + e); } try { String sentId = peopleMessage.getString("$distinct_id"); assertEquals("Expected People Identity", sentId); } catch (JSONException e) { fail("Event message has an unexpected shape: " + peopleMessage.toString()); } } public void testTrackInThread() throws InterruptedException, JSONException { class TestThread extends Thread { BlockingQueue<JSONObject> mMessages; public TestThread(BlockingQueue<JSONObject> messages) { this.mMessages = messages; } @Override public void run() { final MPDbAdapter dbMock = new MPDbAdapter(getContext()) { @Override public int addJSON(JSONObject message, MPDbAdapter.Table table) { mMessages.add(message); return 1; } }; final AnalyticsMessages analyticsMessages = new AnalyticsMessages(getContext()) { @Override public MPDbAdapter makeDbAdapter(Context context) { return dbMock; } }; MixpanelAPI mixpanel = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "TEST TOKEN") { @Override protected AnalyticsMessages getAnalyticsMessages() { return analyticsMessages; } }; mixpanel.clearPreferences(); mixpanel.track("test in thread", new JSONObject()); } } ////////////////////////////// final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>(); TestThread testThread = new TestThread(messages); testThread.start(); JSONObject found = messages.poll(1, TimeUnit.SECONDS); assertNotNull(found); assertEquals(found.getString("event"), "test in thread"); assertTrue(found.getJSONObject("properties").has("$bluetooth_version")); } public void testConfiguration() { final ApplicationInfo appInfo = new ApplicationInfo(); appInfo.metaData = new Bundle(); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.BulkUploadLimit", 1); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.FlushInterval", 2); appInfo.metaData.putInt("com.mixpanel.android.MPConfig.DataExpiration", 3); appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.DisableFallback", true); appInfo.metaData.putBoolean("com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates", false); appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsEndpoint", "EVENTS ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.EventsFallbackEndpoint", "EVENTS FALLBACK ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleEndpoint", "PEOPLE ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.PeopleFallbackEndpoint", "PEOPLE FALLBACK ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideEndpoint", "DECIDE ENDPOINT"); appInfo.metaData.putString("com.mixpanel.android.MPConfig.DecideFallbackEndpoint", "DECIDE FALLBACK ENDPOINT"); final PackageManager packageManager = new MockPackageManager() { @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) { assertEquals(packageName, "TEST PACKAGE NAME"); assertTrue((flags & PackageManager.GET_META_DATA) == PackageManager.GET_META_DATA); return appInfo; } }; final Context context = new MockContext() { @Override public String getPackageName() { return "TEST PACKAGE NAME"; } @Override public PackageManager getPackageManager() { return packageManager; } }; final MPConfig testConfig = MPConfig.readConfig(context); assertEquals(1, testConfig.getBulkUploadLimit()); assertEquals(2, testConfig.getFlushInterval()); assertEquals(3, testConfig.getDataExpiration()); assertEquals(true, testConfig.getDisableFallback()); assertEquals(false, testConfig.getAutoShowMixpanelUpdates()); assertEquals("EVENTS ENDPOINT", testConfig.getEventsEndpoint()); assertEquals("EVENTS FALLBACK ENDPOINT", testConfig.getEventsFallbackEndpoint()); assertEquals("PEOPLE ENDPOINT", testConfig.getPeopleEndpoint()); assertEquals("PEOPLE FALLBACK ENDPOINT", testConfig.getPeopleFallbackEndpoint()); assertEquals("DECIDE ENDPOINT", testConfig.getDecideEndpoint()); assertEquals("DECIDE FALLBACK ENDPOINT", testConfig.getDecideFallbackEndpoint()); } public void testSurveyStateSaving() { final String surveyJsonString = "{\"collections\":[{\"id\":151,\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\"}]," + "\"id\":299," + "\"questions\":[" + "{\"prompt\":\"PROMPT1\",\"extra_data\":{\"$choices\":[\"Answer1,1\",\"Answer1,2\",\"Answer1,3\"]},\"type\":\"multiple_choice\",\"id\":287}," + "{\"prompt\":\"PROMPT2\",\"extra_data\":{},\"type\":\"text\",\"id\":289}]}"; Bitmap.Config conf = Bitmap.Config.ARGB_8888; Bitmap testBitmap = Bitmap.createBitmap(100, 100, conf); UpdateDisplayState originalUpdateDisplayState; try { final JSONObject surveyJson = new JSONObject(surveyJsonString); final Survey s = new Survey(surveyJson); final UpdateDisplayState.DisplayState.SurveyState surveyState = new UpdateDisplayState.DisplayState.SurveyState(s); surveyState.setHighlightColor(Color.WHITE); surveyState.setBackground(testBitmap); originalUpdateDisplayState = new UpdateDisplayState(surveyState, "DistinctId", "Token"); } catch (JSONException e) { throw new RuntimeException("Survey string in test doesn't parse"); } catch (BadDecideObjectException e) { throw new RuntimeException("Test survey string couldn't be made into a survey"); } final Bundle inBundle = new Bundle(); inBundle.putParcelable("TEST SURVEY PARCEL", originalUpdateDisplayState); final Parcel outerParcel = Parcel.obtain(); inBundle.writeToParcel(outerParcel, 0); outerParcel.setDataPosition(0); final Bundle outBundle = outerParcel.readBundle(); outBundle.setClassLoader(UpdateDisplayState.class.getClassLoader()); final UpdateDisplayState inUpdateDisplayState = outBundle.getParcelable("TEST SURVEY PARCEL"); final UpdateDisplayState.DisplayState.SurveyState surveyState = (UpdateDisplayState.DisplayState.SurveyState) inUpdateDisplayState.getDisplayState(); final Survey inSurvey = surveyState.getSurvey(); final String inDistinctId = inUpdateDisplayState.getDistinctId(); final String inToken = inUpdateDisplayState.getToken(); assertEquals("DistinctId", inDistinctId); assertEquals("Token", inToken); assertEquals(inSurvey.getId(), 299); List<Survey.Question> inQuestions = inSurvey.getQuestions(); assertEquals(2, inQuestions.size()); final Survey.Question q1 = inQuestions.get(0); assertEquals(q1.getId(), 287); assertEquals(q1.getPrompt(), "PROMPT1"); assertEquals(q1.getType(), Survey.QuestionType.MULTIPLE_CHOICE); final List<String> q1Choices = q1.getChoices(); assertEquals(q1Choices.size(), 3); assertEquals(q1Choices.get(0), "Answer1,1"); assertEquals(q1Choices.get(1), "Answer1,2"); assertEquals(q1Choices.get(2), "Answer1,3"); final Survey.Question q2 = inQuestions.get(1); assertEquals(q2.getId(), 289); assertEquals(q2.getPrompt(), "PROMPT2"); assertEquals(q2.getType(), Survey.QuestionType.TEXT); assertNotNull(surveyState.getBackground()); assertNotNull(surveyState.getAnswers()); } public void test2XUrls() { final String twoXBalok = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/1392337640909.49573.Balok_first.jpg", "@BANANAS"); assertEquals(twoXBalok, "http://images.mxpnl.com/112690/[email protected]"); final String nothingMatches = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/1392337640909.49573.Balok_first..", "@BANANAS"); assertEquals(nothingMatches, "http://images.mxpnl.com/112690/1392337640909.49573.Balok_first.."); final String emptyMatch = InAppNotification.sizeSuffixUrl("", "@BANANAS"); assertEquals(emptyMatch, ""); final String nothingExtensionful = InAppNotification.sizeSuffixUrl("http://images.mxpnl.com/112690/", "@BANANAS"); assertEquals(nothingExtensionful, "http://images.mxpnl.com/112690/"); } private Future<SharedPreferences> mMockPreferences; }
Add test for aliasing
src/androidTest/java/com/mixpanel/android/mpmetrics/MixpanelBasicTest.java
Add test for aliasing
<ide><path>rc/androidTest/java/com/mixpanel/android/mpmetrics/MixpanelBasicTest.java <ide> assertEquals(nothingExtensionful, "http://images.mxpnl.com/112690/"); <ide> } <ide> <add> public void testAlias() { <add> final ServerMessage mockPoster = new ServerMessage() { <add> @Override <add> /* package */ Result performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) { <add> try { <add> assertEquals(nameValuePairs.get(0).getName(), "data"); <add> final String jsonData = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); <add> JSONArray msg = new JSONArray(jsonData); <add> JSONObject event = msg.getJSONObject(0); <add> JSONObject properties = event.getJSONObject("properties"); <add> <add> assertEquals(event.getString("event"), "$create_alias"); <add> assertEquals(properties.getString("distinct_id"), "old id"); <add> assertEquals(properties.getString("alias"), "new id"); <add> } catch (JSONException e) { <add> throw new RuntimeException("Malformed data passed to test mock", e); <add> } <add> return new ServerMessage.Result(ServerMessage.Status.SUCCEEDED, TestUtils.bytes("1\n")); <add> } <add> }; <add> <add> final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { <add> @Override <add> protected ServerMessage getPoster() { <add> return mockPoster; <add> } <add> }; <add> <add> MixpanelAPI metrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { <add> @Override <add> protected AnalyticsMessages getAnalyticsMessages() { <add> return listener; <add> } <add> }; <add> <add> // Check that we post the alias immediately <add> metrics.identify("old id"); <add> metrics.alias("new id", "old id"); <add> } <add> <ide> private Future<SharedPreferences> mMockPreferences; <ide> }
Java
apache-2.0
5ba952f4e8040e251847e438bb4a146a63acea9d
0
klehmann/domino-jna
package com.mindoo.domino.jna.utils; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import com.mindoo.domino.jna.NotesDatabase; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesTimeDate; import com.mindoo.domino.jna.NotesUniversalNoteId; import com.mindoo.domino.jna.constants.CalendarNoteOpen; import com.mindoo.domino.jna.constants.CalendarRead; import com.mindoo.domino.jna.constants.CalendarReadRange; import com.mindoo.domino.jna.constants.CalendarWrite; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.CalNoteOpenData32; import com.mindoo.domino.jna.internal.CalNoteOpenData64; import com.mindoo.domino.jna.internal.DisposableMemory; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.internal.structs.NotesUniversalNoteIdStruct; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * Utility class to access the Calendaring and Scheduling APIs of Domino.<br> * <br> * <i>Please note that this class is not feature complete. We currently support * creating, updating and reading appointments, but we do not yet support Domino's * meeting workflow (accept/decline etc.)</i> * * @author Karsten Lehmann */ public class NotesCalendarUtils { /** * Creates a calendar entry.<br> * <br> * This supports either a single entry, or a recurring entry which may contain multiple * VEVENTS represenging both the series and exception data. The iCalendar input must only * contain data for a single UID.For meetings, ATTENDEE PARTSTAT data is ignored.<br> * If the mailfile owner is the meeting organizer, invitations will be sent out to meeting * participants (unless {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING} is specified) * * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_EXISTS An entry already exists</li> * <li>ERR_CS_PROFILE_NOOWNER - Calendar Profile does not specify owner</li> * <li>ERR_UNEXPECTED_METHOD - Provided iCalendar contains a method (no method expected here)</li> * <li>ERR_MissingVEventComponents - Missing required VEvent components</li> * <li>ERR_InvalidVEventPropertyFound - Invalid VEvent property found</li> * <li>ERR_ICAL2NOTE_CONVERT - Error interpereting iCalendar input</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * <li>ERR_IMPLICIT_SCHED_FAILED - Entry was updated, but errors were encountered sending notices to meeting participants</li> * </ul> * * @param dbMail The database where the entry will be created. * @param iCal The iCalendar data representing the entry to create * @param flags {@link CalendarWrite} flags to control non-default behavior * @return the UID of the created iCalendar */ public static String createCalendarEntry(NotesDatabase dbMail, String iCal, EnumSet<CalendarWrite> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory icalMem = NotesStringUtils.toLMBCS(iCal, true); int dwFlags = flags==null ? 0 : CalendarWrite.toBitMask(flags); String retUID=null; short result; if (PlatformUtils.is64Bit()) { LongByReference hRetUID = new LongByReference(); result = NotesNativeAPI64.get().CalCreateEntry(dbMail.getHandle64(), icalMem, dwFlags, hRetUID, null); NotesErrorUtils.checkResult(result); long hRetUIDLong = hRetUID.getValue(); if (hRetUIDLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetUIDLong); try { retUID = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem64.OSMemoryUnlock(hRetUIDLong); Mem64.OSMemoryFree(hRetUIDLong); } } } else { IntByReference hRetUID = new IntByReference(); result = NotesNativeAPI32.get().CalCreateEntry(dbMail.getHandle32(), icalMem, dwFlags, hRetUID, null); NotesErrorUtils.checkResult(result); int hRetUIDInt = hRetUID.getValue(); if (hRetUIDInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetUIDInt); try { retUID = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem32.OSMemoryUnlock(hRetUIDInt); Mem32.OSMemoryFree(hRetUIDInt); } } } return retUID; } /** * This will modify an existing calendar entry.<br> * <br> * This supports either single entries or recurring entries, but recurring entries will only * support updates for a single instance specified via RECURRENCE-ID that may not include a * RANGE (This may be permitted in the future but for now will return an error).<br> * <br> * The iCalendar input may only contain a single VEVENT and must contain a UID.<br> * By default, attachments and custom data (for fields contained in $CSCopyItems) will be * maintained from the existing calendar entry. Similarly, description will also be maintained * if it is not specified in the iCalendar content that is updating.<br> * <br> * Both of these behaviors can be canceled via the CAL_WRITE_COMPLETE_REPLACE flag.<br> * If the mailfile owner is the meeting organizer, appropriate notices will be sent out * to meeting participants (unless {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING} is specified).<br> * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_CALACTION_INVALID - This calendar entry is not in a state where updating it is supported.</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_NOT_FOUND - There are no entries that match the specified UID or UID/recurid in the database</li> * <li>ERR_NOT_YET_IMPLEMENTED - This update is not yet supported (update range or multiple VEVENTs?)</li> * <li>ERR_CS_PROFILE_NOOWNER - Calendar Profile does not specify owner</li> * <li>ERR_UNEXPECTED_METHOD - Provided iCalendar contains a method (no method expected here)</li> * <li>ERR_ICAL2NOTE_OUTOFDATE - iCalendar input is out of date in regards to sequence information.</li> * <li>ERR_MissingVEventComponents - Missing required VEvent components</li> * <li>ERR_InvalidVEventPropertyFound - Invalid VEvent property found</li> * <li>ERR_ICAL2NOTE_CONVERT - Error interpereting iCalendar input</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * <li>ERR_IMPLICIT_SCHED_FAILED - Entry was updated, but errors were encountered sending notices to meeting participants</li> * </ul> * * @param dbMail The database containing the entry to update * @param iCal The iCalendar data representing the updated entry * @param uid If non-NULL, this value MUST match the UID value in the iCalendar input. If present,or else this returns ERR_InvalidVEventPropertyFound. If the iCalendar input has no UID this value will be used. * @param recurId If non-NULL, this value MUST match the RECURRENCE-ID value in the iCalendar input if present, or else this returns ERR_InvalidVEventPropertyFound. If the iCalendar input has no RECURRENCE-ID this value will be used. * @param comments If non-NULL, this text will be sent as comments on any notices sent to meeting participants as a result of this call. that will be included on the notices. Can be NULL. * @param flags {@link CalendarWrite} flags to control non-default behavior. Supported: CAL_WRITE_MODIFY_LITERAL, {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING}, {@link CalendarWrite#IGNORE_VERIFY_DB}. */ public static void updateCalendarEntry(NotesDatabase dbMail, String iCal, String uid, String recurId, String comments, EnumSet<CalendarWrite> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory icalMem = NotesStringUtils.toLMBCS(iCal, true); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); Memory commentsMem = NotesStringUtils.toLMBCS(comments, true); int dwFlags = flags==null ? 0 : CalendarWrite.toBitMask(flags); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalUpdateEntry(dbMail.getHandle64(), icalMem, uidMem, recurIdMem, commentsMem, dwFlags, null); } else { result = NotesNativeAPI32.get().CalUpdateEntry(dbMail.getHandle32(), icalMem, uidMem, recurIdMem, commentsMem, dwFlags, null); } NotesErrorUtils.checkResult(result); } /** * This is a convinience method that returns a UID from a NOTEID.<br> * NOTEID->UID is a many to one mapping since one or several notes may represent * a calendar entry (especially if it repeats) and its related notices. * <br> * As such, the UID output will be the same for all notes that refer to the same calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param note note * @return UID */ public static String getUIDfromNote(NotesNote note) { return getUIDfromNoteID(note.getParent(), note.getNoteId()); } /** * This is a convinience method that returns a UID from a NOTEID.<br> * NOTEID->UID is a many to one mapping since one or several notes may represent * a calendar entry (especially if it repeats) and its related notices. * <br> * As such, the UID output will be the same for all notes that refer to the same calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param dbMail The database containing the note referenced by noteid. * @param noteId note id * @return UID */ public static String getUIDfromNoteID(NotesDatabase dbMail, int noteId) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); DisposableMemory retUID = new DisposableMemory(NotesConstants.MAXPATH); try { short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalGetUIDfromNOTEID(dbMail.getHandle64(), noteId, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } else { result = NotesNativeAPI32.get().CalGetUIDfromNOTEID(dbMail.getHandle32(), noteId, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } NotesErrorUtils.checkResult(result); String uid = NotesStringUtils.fromLMBCS(retUID, 1); return uid; } finally { retUID.dispose(); } } /** * This is a convinience method that returns a UID from a UNID.<br> * <br> * UNID->UID is a many to one mapping since one or several notes may represent a * calendar entry (especially if it repeats) and its related notices.<br> * As such, the UID output will be the same for all notes that refer to the same * calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param dbMail The database containing the note referenced by unid. * @param unid UNID of a calendar note * @return UID */ public static String getUIDFromUNID(NotesDatabase dbMail, String unid) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); NotesUniversalNoteId unidObj = new NotesUniversalNoteId(unid); NotesUniversalNoteIdStruct unidStruct = unidObj.getAdapter(NotesUniversalNoteIdStruct.class); DisposableMemory retUID = new DisposableMemory(NotesConstants.MAXPATH); try { short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalGetUIDfromUNID(dbMail.getHandle64(), unidStruct, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } else { result = NotesNativeAPI32.get().CalGetUIDfromUNID(dbMail.getHandle32(), unidStruct, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } NotesErrorUtils.checkResult(result); String uid = NotesStringUtils.fromLMBCS(retUID, 1); return uid; } finally { retUID.dispose(); } } /** * This is a convenience method that returns an Apptunid value that corresponds to a UID.<br> * * @param uid UID of the icalendar entry * @return ApptUnid */ public static String getApptUnidFromUID(String uid) { Memory uidMem = NotesStringUtils.toLMBCS(uid, true); DisposableMemory retApptUnidMem = new DisposableMemory(NotesConstants.MAXPATH); try { short result = NotesNativeAPI.get().CalGetApptunidFromUID(uidMem, retApptUnidMem, 0, null); NotesErrorUtils.checkResult(result); String apptUnid = NotesStringUtils.fromLMBCS(retApptUnidMem, -1); return apptUnid; } finally { retApptUnidMem.dispose(); } } /** * This is a method to get a note handle for an entry on the calendar.<br> * <br> * The intent is that the note handle can be used to get information about an * entry or instance or to write additional information to the entry or * instance (beyond what is defined in iCalendar and/or available in this API).<br> * It is the callers responsibility to close the note via {@link NotesNote#recycle()} or * let it be auto-GC'ed.<br> * When opening a recurring entry, a valid recurrence ID MUST also be provided.<br> * <br> * A note representing the single instance will be returned. This might cause notes to be created or modified as a side effect. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_NOT_FOUND - There are no entries that match the specified UID or UID/recurid in the database</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_TDI_CONV - The recurrence ID specified cannot be interpreted</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * </ul> * * @param dbMail The database containing the entry to open. * @param uid The UID of the entry to get a note handle for. * @param recurId The RECURRENCE-ID of the instance to get a note handle for. Timezones not permitted (time values must be in UTC time). NULL for single entries. Must be present for recurring entries. * @param flags {@link CalendarNoteOpen} flags to control non-default behavior. Supported: {@link CalendarNoteOpen#HANDLE_NOSPLIT}. * @return note */ public static NotesNote openCalendarEntryNote(NotesDatabase dbMail, String uid, String recurId, EnumSet<CalendarNoteOpen> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); int dwFlags = flags==null ? 0 : CalendarNoteOpen.toBitMask(flags); short result; if (PlatformUtils.is64Bit()) { LongByReference rethNote = new LongByReference(); result = NotesNativeAPI64.get().CalOpenNoteHandle(dbMail.getHandle64(), uidMem, recurIdMem, rethNote, dwFlags, null); NotesErrorUtils.checkResult(result); long hNote = rethNote.getValue(); if (hNote==0) return null; CalNoteOpenData64 calNoteOpen = new CalNoteOpenData64(dbMail, hNote); NotesNote note = new NotesNote(calNoteOpen); NotesGC.__objectCreated(NotesNote.class, note); return note; } else { IntByReference rethNote = new IntByReference(); result = NotesNativeAPI32.get().CalOpenNoteHandle(dbMail.getHandle32(), uidMem, recurIdMem, rethNote, dwFlags, null); NotesErrorUtils.checkResult(result); int hNote = rethNote.getValue(); if (hNote==0) return null; CalNoteOpenData32 calNoteOpen = new CalNoteOpenData32(dbMail, hNote); NotesNote note = new NotesNote(calNoteOpen); NotesGC.__objectCreated(NotesNote.class, note); return note; } } /** * This will return complete iCalendar data for the specified entry.<br> * <br> * For recurring entries, this may result in multiple VEVENTs in the returned * iCalendar data.<br> * In this case, the first VEVENT represents the recurrence set and additional * entries represent exceptions to the recurrence set.<br> * <br> * All instances that differ from the recurrence set will be returned as additional * VEVENTs containing the exceptional data. There is no concept of 'runs' of * instances or RANGE of instances.<br> * Alternatively, a specific instance may be requested using <code>recurId</code> * and only the data for that instance will be returned.<br> * Returned data will not include rich text description.<br> * All participants of a meeting will be returned as PARTSTAT=NEEDS-ACTION even if they have responded. * * @param dbMail The database from which entries are returned. * @param uid The UID of the entry to be returned. * @param recurId NULL for single entries or to read data for an entire recurring series. If populated, this is the RECURRENCE-ID of the specific instance to read. * @param flags {@link CalendarRead} flags to control non-default behavior * @return iCalendar data */ public static String readCalendarEntry(NotesDatabase dbMail, String uid, String recurId, EnumSet<CalendarRead> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); int dwFlags = flags==null ? 0 : CalendarRead.toBitMask(flags); String retIcal = null; short result; if (PlatformUtils.is64Bit()) { LongByReference hRetCalData = new LongByReference(); result = NotesNativeAPI64.get().CalReadEntry(dbMail.getHandle64(), uidMem, recurIdMem, hRetCalData, null, dwFlags, null); NotesErrorUtils.checkResult(result); long hRetCalDataLong = hRetCalData.getValue(); if (hRetCalDataLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetCalDataLong); try { retIcal = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem64.OSMemoryUnlock(hRetCalDataLong); Mem64.OSMemoryFree(hRetCalDataLong); } } } else { IntByReference hRetCalData = new IntByReference(); result = NotesNativeAPI32.get().CalReadEntry(dbMail.getHandle32(), uidMem, recurIdMem, hRetCalData, null, dwFlags, null); NotesErrorUtils.checkResult(result); int hRetCalDataInt = hRetCalData.getValue(); if (hRetCalDataInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetCalDataInt); try { retIcal = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem32.OSMemoryUnlock(hRetCalDataInt); Mem32.OSMemoryFree(hRetCalDataInt); } } } return retIcal; } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, Appendable retICal, List<String> retUIDs) throws IOException { readRange(dbMail, start, end, 0, Integer.MAX_VALUE, null, retICal, retUIDs); } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param skipCount the number of entries to skip from the beginning of the range. This parameter can be used in conjunction with <i>entriesprocessed</i> to read the entries in a series of calls * @param maxRead the maximum number of entries to read * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, int skipCount, int maxRead, Appendable retICal, List<String> retUIDs) throws IOException { readRange(dbMail, start, end, skipCount, maxRead, null, retICal, retUIDs); } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param skipCount the number of entries to skip from the beginning of the range. This parameter can be used in conjunction with <i>entriesprocessed</i> to read the entries in a series of calls * @param maxRead the maximum number of entries to read * @param readMask flags that control what properties about the calendar entries will be returned * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, int skipCount, int maxRead, EnumSet<CalendarReadRange> readMask, Appendable retICal, List<String> retUIDs) throws IOException { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); NotesTimeDateStruct.ByValue startStruct = start==null ? null : NotesTimeDateStruct.ByValue.newInstance(start.getInnards()); NotesTimeDateStruct.ByValue endStruct = end==null ? null : NotesTimeDateStruct.ByValue.newInstance(end.getInnards()); int dwReturnMask = CalendarReadRange.toBitMask(readMask); int dwReturnMaskExt = CalendarReadRange.toBitMask2(readMask); //variables to collect the whole lookup result StringBuilder sbIcalAllData = retICal==null ? null : new StringBuilder(); List<String> uidAllData = retUIDs==null ? null : new ArrayList<String>(); while (true) { int currSkipCount = skipCount; int remainingToRead = maxRead; short result; boolean hasMoreToDo; boolean hasConflict; //clear current lookup result, while(true) loop may be run multiple times //if lookup view changes if (sbIcalAllData!=null) { sbIcalAllData.setLength(0); } if (uidAllData!=null) { uidAllData.clear(); } do { if (PlatformUtils.is64Bit()) { LongByReference hRetCalData = retICal==null ? null : new LongByReference(); LongByReference hRetUIDData = retUIDs==null ? null : new LongByReference(); ShortByReference retCalBufferLength = new ShortByReference(); ShortByReference retSignalFlags = new ShortByReference(); IntByReference retNumEntriesProcessed = new IntByReference(); result = NotesNativeAPI64.get().CalReadRange(dbMail.getHandle64(), startStruct, endStruct, currSkipCount, remainingToRead, dwReturnMask, dwReturnMaskExt, null, hRetCalData, retCalBufferLength, hRetUIDData, retNumEntriesProcessed, retSignalFlags, 0, null); NotesErrorUtils.checkResult(result); int numEntriesProcessed = retNumEntriesProcessed.getValue(); currSkipCount += numEntriesProcessed; remainingToRead -= numEntriesProcessed; if (hRetCalData!=null && retICal!=null && sbIcalAllData!=null) { //decode iCalendar int iCalBufLength = (int) (retCalBufferLength.getValue() & 0xffff); if (iCalBufLength>0) { long hRetCalDataLong = hRetCalData.getValue(); if (hRetCalDataLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetCalDataLong); try { String currICal = NotesStringUtils.fromLMBCS(retUIDPtr, iCalBufLength); sbIcalAllData.append(currICal); } finally { Mem64.OSMemoryUnlock(hRetCalDataLong); Mem64.OSMemoryFree(hRetCalDataLong); } } } } if (hRetUIDData!=null && retUIDs!=null && uidAllData!=null) { //decode UID list long hRetUIDDataLong = hRetUIDData.getValue(); if (hRetUIDDataLong!=0) { Pointer pUIDData = Mem64.OSMemoryLock(hRetUIDDataLong); ShortByReference retTextLength = new ShortByReference(); Memory retTextPointer = new Memory(Pointer.SIZE); try { int numEntriesAsInt = (int) (NotesNativeAPI.get().ListGetNumEntries(pUIDData, 0) & 0xffff); for (int i=0; i<numEntriesAsInt; i++) { result = NotesNativeAPI.get().ListGetText(pUIDData, false, (short) (i & 0xffff), retTextPointer, retTextLength); NotesErrorUtils.checkResult(result); String currUID = NotesStringUtils.fromLMBCS(retTextPointer.getPointer(0), retTextLength.getValue() & 0xffff); uidAllData.add(currUID); } } finally { Mem64.OSMemoryUnlock(hRetUIDDataLong); Mem64.OSMemoryFree(hRetUIDDataLong); } } } short signalFlags = retSignalFlags.getValue(); hasMoreToDo = (signalFlags & NotesConstants.SIGNAL_MORE_TO_DO) == NotesConstants.SIGNAL_MORE_TO_DO; hasConflict = (signalFlags & NotesConstants.SIGNAL_ANY_CONFLICT) == NotesConstants.SIGNAL_ANY_CONFLICT; } else { IntByReference hRetCalData = retICal==null ? null : new IntByReference(); IntByReference hRetUIDData = retUIDs==null ? null : new IntByReference(); ShortByReference retCalBufferLength = new ShortByReference(); ShortByReference retSignalFlags = new ShortByReference(); IntByReference retNumEntriesProcessed = new IntByReference(); result = NotesNativeAPI32.get().CalReadRange(dbMail.getHandle32(), startStruct, endStruct, currSkipCount, remainingToRead, dwReturnMask, dwReturnMaskExt, null, hRetCalData, retCalBufferLength, hRetUIDData, retNumEntriesProcessed, retSignalFlags, 0, null); NotesErrorUtils.checkResult(result); int numEntriesProcessed = retNumEntriesProcessed.getValue(); currSkipCount += numEntriesProcessed; remainingToRead -= numEntriesProcessed; if (hRetCalData!=null && retICal!=null && sbIcalAllData!=null) { //decode iCalendar int iCalBufLength = (int) (retCalBufferLength.getValue() & 0xffff); if (iCalBufLength>0) { int hRetCalDataInt = hRetCalData.getValue(); if (hRetCalDataInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetCalDataInt); try { String currICal = NotesStringUtils.fromLMBCS(retUIDPtr, iCalBufLength); sbIcalAllData.append(currICal); } finally { Mem32.OSMemoryUnlock(hRetCalDataInt); Mem32.OSMemoryFree(hRetCalDataInt); } } } } if (hRetUIDData!=null && retUIDs!=null && uidAllData!=null) { //decode UID list int hRetUIDDataInt = hRetUIDData.getValue(); if (hRetUIDDataInt!=0) { Pointer pUIDData = Mem32.OSMemoryLock(hRetUIDDataInt); ShortByReference retTextLength = new ShortByReference(); Memory retTextPointer = new Memory(Pointer.SIZE); try { int numEntriesAsInt = (int) (NotesNativeAPI.get().ListGetNumEntries(pUIDData, 0) & 0xffff); for (int i=0; i<numEntriesAsInt; i++) { result = NotesNativeAPI.get().ListGetText(pUIDData, false, (short) (i & 0xffff), retTextPointer, retTextLength); NotesErrorUtils.checkResult(result); String currUID = NotesStringUtils.fromLMBCS(retTextPointer.getPointer(0), retTextLength.getValue() & 0xffff); uidAllData.add(currUID); } } finally { Mem32.OSMemoryUnlock(hRetUIDDataInt); Mem32.OSMemoryFree(hRetUIDDataInt); } } } short signalFlags = retSignalFlags.getValue(); hasMoreToDo = (signalFlags & NotesConstants.SIGNAL_MORE_TO_DO) == NotesConstants.SIGNAL_MORE_TO_DO; hasConflict = (signalFlags & NotesConstants.SIGNAL_ANY_CONFLICT) == NotesConstants.SIGNAL_ANY_CONFLICT; } } while (hasMoreToDo && remainingToRead>0); if (!hasConflict) { //no read conflict in view, we are done break; } else { //retry the whole lookup continue; } } //return what we have read if (retICal!=null && sbIcalAllData!=null) { retICal.append(sbIcalAllData.toString()); } if (retUIDs!=null && uidAllData!=null) { retUIDs.addAll(uidAllData); } } }
domino-jna/src/main/java/com/mindoo/domino/jna/utils/NotesCalendarUtils.java
package com.mindoo.domino.jna.utils; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import com.mindoo.domino.jna.NotesDatabase; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesTimeDate; import com.mindoo.domino.jna.NotesUniversalNoteId; import com.mindoo.domino.jna.constants.CalendarNoteOpen; import com.mindoo.domino.jna.constants.CalendarRead; import com.mindoo.domino.jna.constants.CalendarReadRange; import com.mindoo.domino.jna.constants.CalendarWrite; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.CalNoteOpenData32; import com.mindoo.domino.jna.internal.CalNoteOpenData64; import com.mindoo.domino.jna.internal.DisposableMemory; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.internal.structs.NotesUniversalNoteIdStruct; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * Utility class to access the Calendaring and Scheduling APIs of Domino.<br> * <br> * <i>Please note that this class is not feature complete. We currently support * creating, updating and reading appointments, but we do not yet support Domino's * meeting workflow (accept/decline etc.)</i> * * @author Karsten Lehmann */ public class NotesCalendarUtils { /** * Creates a calendar entry.<br> * <br> * This supports either a single entry, or a recurring entry which may contain multiple * VEVENTS represenging both the series and exception data. The iCalendar input must only * contain data for a single UID.For meetings, ATTENDEE PARTSTAT data is ignored.<br> * If the mailfile owner is the meeting organizer, invitations will be sent out to meeting * participants (unless {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING} is specified) * * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_EXISTS An entry already exists</li> * <li>ERR_CS_PROFILE_NOOWNER - Calendar Profile does not specify owner</li> * <li>ERR_UNEXPECTED_METHOD - Provided iCalendar contains a method (no method expected here)</li> * <li>ERR_MissingVEventComponents - Missing required VEvent components</li> * <li>ERR_InvalidVEventPropertyFound - Invalid VEvent property found</li> * <li>ERR_ICAL2NOTE_CONVERT - Error interpereting iCalendar input</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * <li>ERR_IMPLICIT_SCHED_FAILED - Entry was updated, but errors were encountered sending notices to meeting participants</li> * </ul> * * @param dbMail The database where the entry will be created. * @param iCal The iCalendar data representing the entry to create * @param flags {@link CalendarWrite} flags to control non-default behavior * @return the UID of the created iCalendar */ public static String createCalendarEntry(NotesDatabase dbMail, String iCal, EnumSet<CalendarWrite> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory icalMem = NotesStringUtils.toLMBCS(iCal, true); int dwFlags = flags==null ? 0 : CalendarWrite.toBitMask(flags); String retUID=null; short result; if (PlatformUtils.is64Bit()) { LongByReference hRetUID = new LongByReference(); result = NotesNativeAPI64.get().CalCreateEntry(dbMail.getHandle64(), icalMem, dwFlags, hRetUID, null); NotesErrorUtils.checkResult(result); long hRetUIDLong = hRetUID.getValue(); if (hRetUIDLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetUIDLong); try { retUID = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem64.OSMemoryUnlock(hRetUIDLong); Mem64.OSMemoryFree(hRetUIDLong); } } } else { IntByReference hRetUID = new IntByReference(); result = NotesNativeAPI32.get().CalCreateEntry(dbMail.getHandle32(), icalMem, dwFlags, hRetUID, null); NotesErrorUtils.checkResult(result); int hRetUIDInt = hRetUID.getValue(); if (hRetUIDInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetUIDInt); try { retUID = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem32.OSMemoryUnlock(hRetUIDInt); Mem32.OSMemoryFree(hRetUIDInt); } } } return retUID; } /** * This will modify an existing calendar entry.<br> * <br> * This supports either single entries or recurring entries, but recurring entries will only * support updates for a single instance specified via RECURRENCE-ID that may not include a * RANGE (This may be permitted in the future but for now will return an error).<br> * <br> * The iCalendar input may only contain a single VEVENT and must contain a UID.<br> * By default, attachments and custom data (for fields contained in $CSCopyItems) will be * maintained from the existing calendar entry. Similarly, description will also be maintained * if it is not specified in the iCalendar content that is updating.<br> * <br> * Both of these behaviors can be canceled via the CAL_WRITE_COMPLETE_REPLACE flag.<br> * If the mailfile owner is the meeting organizer, appropriate notices will be sent out * to meeting participants (unless {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING} is specified).<br> * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_CALACTION_INVALID - This calendar entry is not in a state where updating it is supported.</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_NOT_FOUND - There are no entries that match the specified UID or UID/recurid in the database</li> * <li>ERR_NOT_YET_IMPLEMENTED - This update is not yet supported (update range or multiple VEVENTs?)</li> * <li>ERR_CS_PROFILE_NOOWNER - Calendar Profile does not specify owner</li> * <li>ERR_UNEXPECTED_METHOD - Provided iCalendar contains a method (no method expected here)</li> * <li>ERR_ICAL2NOTE_OUTOFDATE - iCalendar input is out of date in regards to sequence information.</li> * <li>ERR_MissingVEventComponents - Missing required VEvent components</li> * <li>ERR_InvalidVEventPropertyFound - Invalid VEvent property found</li> * <li>ERR_ICAL2NOTE_CONVERT - Error interpereting iCalendar input</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * <li>ERR_IMPLICIT_SCHED_FAILED - Entry was updated, but errors were encountered sending notices to meeting participants</li> * </ul> * * @param dbMail The database containing the entry to update * @param iCal The iCalendar data representing the updated entry * @param uid If non-NULL, this value MUST match the UID value in the iCalendar input. If present,or else this returns ERR_InvalidVEventPropertyFound. If the iCalendar input has no UID this value will be used. * @param recurId If non-NULL, this value MUST match the RECURRENCE-ID value in the iCalendar input if present, or else this returns ERR_InvalidVEventPropertyFound. If the iCalendar input has no RECURRENCE-ID this value will be used. * @param comments If non-NULL, this text will be sent as comments on any notices sent to meeting participants as a result of this call. that will be included on the notices. Can be NULL. * @param flags {@link CalendarWrite} flags to control non-default behavior. Supported: CAL_WRITE_MODIFY_LITERAL, {@link CalendarWrite#DISABLE_IMPLICIT_SCHEDULING}, {@link CalendarWrite#IGNORE_VERIFY_DB}. */ public static void updateCalendarEntry(NotesDatabase dbMail, String iCal, String uid, String recurId, String comments, EnumSet<CalendarWrite> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory icalMem = NotesStringUtils.toLMBCS(iCal, true); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); Memory commentsMem = NotesStringUtils.toLMBCS(comments, true); int dwFlags = flags==null ? 0 : CalendarWrite.toBitMask(flags); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalUpdateEntry(dbMail.getHandle64(), icalMem, uidMem, recurIdMem, commentsMem, dwFlags, null); } else { result = NotesNativeAPI32.get().CalUpdateEntry(dbMail.getHandle32(), icalMem, uidMem, recurIdMem, commentsMem, dwFlags, null); } NotesErrorUtils.checkResult(result); } /** * This is a convinience method that returns a UID from a NOTEID.<br> * NOTEID->UID is a many to one mapping since one or several notes may represent * a calendar entry (especially if it repeats) and its related notices. * <br> * As such, the UID output will be the same for all notes that refer to the same calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param note note * @return UID */ public static String getUIDfromNote(NotesNote note) { return getUIDfromNoteID(note.getParent(), note.getNoteId()); } /** * This is a convinience method that returns a UID from a NOTEID.<br> * NOTEID->UID is a many to one mapping since one or several notes may represent * a calendar entry (especially if it repeats) and its related notices. * <br> * As such, the UID output will be the same for all notes that refer to the same calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param dbMail The database containing the note referenced by noteid. * @param noteId note id * @return UID */ public static String getUIDfromNoteID(NotesDatabase dbMail, int noteId) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); DisposableMemory retUID = new DisposableMemory(NotesConstants.MAXPATH); try { short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalGetUIDfromNOTEID(dbMail.getHandle64(), noteId, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } else { result = NotesNativeAPI32.get().CalGetUIDfromNOTEID(dbMail.getHandle32(), noteId, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } NotesErrorUtils.checkResult(result); String uid = NotesStringUtils.fromLMBCS(retUID, 1); return uid; } finally { retUID.dispose(); } } /** * This is a convinience method that returns a UID from a UNID.<br> * <br> * UNID->UID is a many to one mapping since one or several notes may represent a * calendar entry (especially if it repeats) and its related notices.<br> * As such, the UID output will be the same for all notes that refer to the same * calendar entry.<br> * This method may incur a note open, so there could be performance impact. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_INVALID_NOTE - Note is not valid or is not a calendar note</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_VALUE_LENGTH - The value is too long for the allocated buffer</li> * </ul> * * @param dbMail The database containing the note referenced by unid. * @param unid UNID of a calendar note * @return UID */ public static String getUIDFromUNID(NotesDatabase dbMail, String unid) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); NotesUniversalNoteId unidObj = new NotesUniversalNoteId(unid); NotesUniversalNoteIdStruct unidStruct = unidObj.getAdapter(NotesUniversalNoteIdStruct.class); DisposableMemory retUID = new DisposableMemory(NotesConstants.MAXPATH); try { short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().CalGetUIDfromUNID(dbMail.getHandle64(), unidStruct, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } else { result = NotesNativeAPI32.get().CalGetUIDfromUNID(dbMail.getHandle32(), unidStruct, retUID, (short) (NotesConstants.MAXPATH & 0xffff), null, 0, null); } NotesErrorUtils.checkResult(result); String uid = NotesStringUtils.fromLMBCS(retUID, 1); return uid; } finally { retUID.dispose(); } } /** * This is a convenience method that returns an Apptunid value that corresponds to a UID.<br> * * @param uid UID of the icalendar entry * @return ApptUnid */ public static String getApptUnidFromUID(String uid) { Memory uidMem = NotesStringUtils.toLMBCS(uid, true); DisposableMemory retApptUnidMem = new DisposableMemory(NotesConstants.MAXPATH); try { short result = NotesNativeAPI.get().CalGetApptunidFromUID(uidMem, retApptUnidMem, 0, null); NotesErrorUtils.checkResult(result); String apptUnid = NotesStringUtils.fromLMBCS(retApptUnidMem, -1); return apptUnid; } finally { retApptUnidMem.dispose(); } } /** * This is a method to get a note handle for an entry on the calendar.<br> * <br> * The intent is that the note handle can be used to get information about an * entry or instance or to write additional information to the entry or * instance (beyond what is defined in iCalendar and/or available in this API).<br> * It is the callers responsibility to close the note via {@link NotesNote#recycle()} or * let it be auto-GC'ed.<br> * When opening a recurring entry, a valid recurrence ID MUST also be provided.<br> * <br> * A note representing the single instance will be returned. This might cause notes to be created or modified as a side effect. * <br> * The following errors will be thrown by this method: * <ul> * <li>NOERROR - on success</li> * <li>{@link INotesErrorConstants#ERR_NULL_DBHANDLE} - The database handle is NULL</li> * <li>ERR_NO_CALENDAR_FOUND - Unable to find the entry because the required view does not exist in this database</li> * <li>ERR_NOT_FOUND - There are no entries that match the specified UID or UID/recurid in the database</li> * <li>ERR_MISC_INVALID_ARGS - Unexpected arguments provided</li> * <li>ERR_TDI_CONV - The recurrence ID specified cannot be interpreted</li> * <li>ERR_MISC_UNEXPECTED_ERROR - Unexpected internal error</li> * </ul> * * @param dbMail The database containing the entry to open. * @param uid The UID of the entry to get a note handle for. * @param recurId The RECURRENCE-ID of the instance to get a note handle for. Timezones not permitted (time values must be in UTC time). NULL for single entries. Must be present for recurring entries. * @param flags {@link CalendarNoteOpen} flags to control non-default behavior. Supported: {@link CalendarNoteOpen#HANDLE_NOSPLIT}. * @return note */ public static NotesNote openCalendarEntryNote(NotesDatabase dbMail, String uid, String recurId, EnumSet<CalendarNoteOpen> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); int dwFlags = flags==null ? 0 : CalendarNoteOpen.toBitMask(flags); short result; if (PlatformUtils.is64Bit()) { LongByReference rethNote = new LongByReference(); result = NotesNativeAPI64.get().CalOpenNoteHandle(dbMail.getHandle64(), uidMem, recurIdMem, rethNote, dwFlags, null); NotesErrorUtils.checkResult(result); long hNote = rethNote.getValue(); if (hNote==0) return null; CalNoteOpenData64 calNoteOpen = new CalNoteOpenData64(dbMail, hNote); NotesNote note = new NotesNote(calNoteOpen); NotesGC.__objectCreated(NotesNote.class, note); return note; } else { IntByReference rethNote = new IntByReference(); result = NotesNativeAPI32.get().CalOpenNoteHandle(dbMail.getHandle32(), uidMem, recurIdMem, rethNote, dwFlags, null); NotesErrorUtils.checkResult(result); int hNote = rethNote.getValue(); if (hNote==0) return null; CalNoteOpenData32 calNoteOpen = new CalNoteOpenData32(dbMail, hNote); NotesNote note = new NotesNote(calNoteOpen); NotesGC.__objectCreated(NotesNote.class, note); return note; } } /** * This will return complete iCalendar data for the specified entry.<br> * <br> * For recurring entries, this may result in multiple VEVENTs in the returned * iCalendar data.<br> * In this case, the first VEVENT represents the recurrence set and additional * entries represent exceptions to the recurrence set.<br> * <br> * All instances that differ from the recurrence set will be returned as additional * VEVENTs containing the exceptional data. There is no concept of 'runs' of * instances or RANGE of instances.<br> * Alternatively, a specific instance may be requested using <code>recurId</code> * and only the data for that instance will be returned.<br> * Returned data will not include rich text description.<br> * All participants of a meeting will be returned as PARTSTAT=NEEDS-ACTION even if they have responded. * * @param dbMail The database from which entries are returned. * @param uid The UID of the entry to be returned. * @param recurId NULL for single entries or to read data for an entire recurring series. If populated, this is the RECURRENCE-ID of the specific instance to read. * @param flags {@link CalendarRead} flags to control non-default behavior * @return iCalendar data */ public static String readCalendarEntry(NotesDatabase dbMail, String uid, String recurId, EnumSet<CalendarRead> flags) { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); Memory uidMem = NotesStringUtils.toLMBCS(uid, true); Memory recurIdMem = NotesStringUtils.toLMBCS(recurId, true); int dwFlags = flags==null ? 0 : CalendarRead.toBitMask(flags); String retIcal = null; short result; if (PlatformUtils.is64Bit()) { LongByReference hRetCalData = new LongByReference(); result = NotesNativeAPI64.get().CalReadEntry(dbMail.getHandle64(), uidMem, recurIdMem, hRetCalData, null, dwFlags, null); NotesErrorUtils.checkResult(result); long hRetCalDataLong = hRetCalData.getValue(); if (hRetCalDataLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetCalDataLong); try { retIcal = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem64.OSMemoryUnlock(hRetCalDataLong); Mem64.OSMemoryFree(hRetCalDataLong); } } } else { IntByReference hRetCalData = new IntByReference(); result = NotesNativeAPI32.get().CalReadEntry(dbMail.getHandle32(), uidMem, recurIdMem, hRetCalData, null, dwFlags, null); NotesErrorUtils.checkResult(result); int hRetCalDataInt = hRetCalData.getValue(); if (hRetCalDataInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetCalDataInt); try { retIcal = NotesStringUtils.fromLMBCS(retUIDPtr, -1); } finally { Mem32.OSMemoryUnlock(hRetCalDataInt); Mem32.OSMemoryFree(hRetCalDataInt); } } } return retIcal; } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, Appendable retICal, List<String> retUIDs) throws IOException { readRange(dbMail, start, end, 0, Integer.MAX_VALUE, null, retICal, retUIDs); } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param skipCount the number of entries to skip from the beginning of the range. This parameter can be used in conjunction with <i>entriesprocessed</i> to read the entries in a series of calls * @param maxRead the maximum number of entries to read * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, int skipCount, int maxRead, Appendable retICal, List<String> retUIDs) throws IOException { readRange(dbMail, start, end, skipCount, maxRead, null, retICal, retUIDs); } /** * Gets a summary of calendar entries for a range of times * * @param dbMail The database from which entries are returned. * @param start the start time of the range * @param end the end time of the range. An exception occurs if the end time is not greater than the start time * @param skipCount the number of entries to skip from the beginning of the range. This parameter can be used in conjunction with <i>entriesprocessed</i> to read the entries in a series of calls * @param maxRead the maximum number of entries to read * @param readMask flags that control what properties about the calendar entries will be returned * @param retICal if not null, we return a summary in iCalendar format of the entries from the start date to the end date, inclusive. An exception occurs if the range contains no entries. * @param retUIDs if not null, we return a list of UIDs found within the range * @throws IOException if writing iCalendar data fails */ public static void readRange(NotesDatabase dbMail, NotesTimeDate start, NotesTimeDate end, int skipCount, int maxRead, EnumSet<CalendarReadRange> readMask, Appendable retICal, List<String> retUIDs) throws IOException { if (dbMail.isRecycled()) throw new NotesError(0, "Target database already recycled"); NotesTimeDateStruct.ByValue startStruct = start==null ? null : NotesTimeDateStruct.ByValue.newInstance(start.getInnards()); NotesTimeDateStruct.ByValue endStruct = end==null ? null : NotesTimeDateStruct.ByValue.newInstance(end.getInnards()); int dwReturnMask = Integer.MAX_VALUE; //CalendarReadRange.toBitMask(readMask); int dwReturnMaskExt = Integer.MAX_VALUE; //CalendarReadRange.toBitMask2(readMask); //variables to collect the whole lookup result StringBuilder sbIcalAllData = retICal==null ? null : new StringBuilder(); List<String> uidAllData = retUIDs==null ? null : new ArrayList<String>(); while (true) { int currSkipCount = skipCount; int remainingToRead = maxRead; short result; boolean hasMoreToDo; boolean hasConflict; //clear current lookup result, while(true) loop may be run multiple times //if lookup view changes if (sbIcalAllData!=null) { sbIcalAllData.setLength(0); } if (uidAllData!=null) { uidAllData.clear(); } do { if (PlatformUtils.is64Bit()) { LongByReference hRetCalData = retICal==null ? null : new LongByReference(); LongByReference hRetUIDData = retUIDs==null ? null : new LongByReference(); ShortByReference retCalBufferLength = new ShortByReference(); ShortByReference retSignalFlags = new ShortByReference(); IntByReference retNumEntriesProcessed = new IntByReference(); result = NotesNativeAPI64.get().CalReadRange(dbMail.getHandle64(), startStruct, endStruct, currSkipCount, remainingToRead, dwReturnMask, dwReturnMaskExt, null, hRetCalData, retCalBufferLength, hRetUIDData, retNumEntriesProcessed, retSignalFlags, 0, null); NotesErrorUtils.checkResult(result); int numEntriesProcessed = retNumEntriesProcessed.getValue(); currSkipCount += numEntriesProcessed; remainingToRead -= numEntriesProcessed; if (hRetCalData!=null && retICal!=null && sbIcalAllData!=null) { //decode iCalendar int iCalBufLength = (int) (retCalBufferLength.getValue() & 0xffff); if (iCalBufLength>0) { long hRetCalDataLong = hRetCalData.getValue(); if (hRetCalDataLong!=0) { Pointer retUIDPtr = Mem64.OSMemoryLock(hRetCalDataLong); try { String currICal = NotesStringUtils.fromLMBCS(retUIDPtr, iCalBufLength); sbIcalAllData.append(currICal); } finally { Mem64.OSMemoryUnlock(hRetCalDataLong); Mem64.OSMemoryFree(hRetCalDataLong); } } } } if (hRetUIDData!=null && retUIDs!=null && uidAllData!=null) { //decode UID list long hRetUIDDataLong = hRetUIDData.getValue(); if (hRetUIDDataLong!=0) { Pointer pUIDData = Mem64.OSMemoryLock(hRetUIDDataLong); ShortByReference retTextLength = new ShortByReference(); Memory retTextPointer = new Memory(Pointer.SIZE); try { int numEntriesAsInt = (int) (NotesNativeAPI.get().ListGetNumEntries(pUIDData, 0) & 0xffff); for (int i=0; i<numEntriesAsInt; i++) { result = NotesNativeAPI.get().ListGetText(pUIDData, false, (short) (i & 0xffff), retTextPointer, retTextLength); NotesErrorUtils.checkResult(result); String currUID = NotesStringUtils.fromLMBCS(retTextPointer.getPointer(0), retTextLength.getValue() & 0xffff); uidAllData.add(currUID); } } finally { Mem64.OSMemoryUnlock(hRetUIDDataLong); Mem64.OSMemoryFree(hRetUIDDataLong); } } } short signalFlags = retSignalFlags.getValue(); hasMoreToDo = (signalFlags & NotesConstants.SIGNAL_MORE_TO_DO) == NotesConstants.SIGNAL_MORE_TO_DO; hasConflict = (signalFlags & NotesConstants.SIGNAL_ANY_CONFLICT) == NotesConstants.SIGNAL_ANY_CONFLICT; } else { IntByReference hRetCalData = retICal==null ? null : new IntByReference(); IntByReference hRetUIDData = retUIDs==null ? null : new IntByReference(); ShortByReference retCalBufferLength = new ShortByReference(); ShortByReference retSignalFlags = new ShortByReference(); IntByReference retNumEntriesProcessed = new IntByReference(); result = NotesNativeAPI32.get().CalReadRange(dbMail.getHandle32(), startStruct, endStruct, currSkipCount, remainingToRead, dwReturnMask, dwReturnMaskExt, null, hRetCalData, retCalBufferLength, hRetUIDData, retNumEntriesProcessed, retSignalFlags, 0, null); NotesErrorUtils.checkResult(result); int numEntriesProcessed = retNumEntriesProcessed.getValue(); currSkipCount += numEntriesProcessed; remainingToRead -= numEntriesProcessed; if (hRetCalData!=null && retICal!=null && sbIcalAllData!=null) { //decode iCalendar int iCalBufLength = (int) (retCalBufferLength.getValue() & 0xffff); if (iCalBufLength>0) { int hRetCalDataInt = hRetCalData.getValue(); if (hRetCalDataInt!=0) { Pointer retUIDPtr = Mem32.OSMemoryLock(hRetCalDataInt); try { String currICal = NotesStringUtils.fromLMBCS(retUIDPtr, iCalBufLength); sbIcalAllData.append(currICal); } finally { Mem32.OSMemoryUnlock(hRetCalDataInt); Mem32.OSMemoryFree(hRetCalDataInt); } } } } if (hRetUIDData!=null && retUIDs!=null && uidAllData!=null) { //decode UID list int hRetUIDDataInt = hRetUIDData.getValue(); if (hRetUIDDataInt!=0) { Pointer pUIDData = Mem32.OSMemoryLock(hRetUIDDataInt); ShortByReference retTextLength = new ShortByReference(); Memory retTextPointer = new Memory(Pointer.SIZE); try { int numEntriesAsInt = (int) (NotesNativeAPI.get().ListGetNumEntries(pUIDData, 0) & 0xffff); for (int i=0; i<numEntriesAsInt; i++) { result = NotesNativeAPI.get().ListGetText(pUIDData, false, (short) (i & 0xffff), retTextPointer, retTextLength); NotesErrorUtils.checkResult(result); String currUID = NotesStringUtils.fromLMBCS(retTextPointer.getPointer(0), retTextLength.getValue() & 0xffff); uidAllData.add(currUID); } } finally { Mem32.OSMemoryUnlock(hRetUIDDataInt); Mem32.OSMemoryFree(hRetUIDDataInt); } } } short signalFlags = retSignalFlags.getValue(); hasMoreToDo = (signalFlags & NotesConstants.SIGNAL_MORE_TO_DO) == NotesConstants.SIGNAL_MORE_TO_DO; hasConflict = (signalFlags & NotesConstants.SIGNAL_ANY_CONFLICT) == NotesConstants.SIGNAL_ANY_CONFLICT; } } while (hasMoreToDo && remainingToRead>0); if (!hasConflict) { //no read conflict in view, we are done break; } else { //retry the whole lookup continue; } } //return what we have read if (retICal!=null && sbIcalAllData!=null) { retICal.append(sbIcalAllData.toString()); } if (retUIDs!=null && uidAllData!=null) { retUIDs.addAll(uidAllData); } } }
Removed hardcoded return masks for C&S API
domino-jna/src/main/java/com/mindoo/domino/jna/utils/NotesCalendarUtils.java
Removed hardcoded return masks for C&S API
<ide><path>omino-jna/src/main/java/com/mindoo/domino/jna/utils/NotesCalendarUtils.java <ide> NotesTimeDateStruct.ByValue startStruct = start==null ? null : NotesTimeDateStruct.ByValue.newInstance(start.getInnards()); <ide> NotesTimeDateStruct.ByValue endStruct = end==null ? null : NotesTimeDateStruct.ByValue.newInstance(end.getInnards()); <ide> <del> int dwReturnMask = Integer.MAX_VALUE; //CalendarReadRange.toBitMask(readMask); <del> int dwReturnMaskExt = Integer.MAX_VALUE; //CalendarReadRange.toBitMask2(readMask); <add> int dwReturnMask = CalendarReadRange.toBitMask(readMask); <add> int dwReturnMaskExt = CalendarReadRange.toBitMask2(readMask); <ide> <ide> //variables to collect the whole lookup result <ide> StringBuilder sbIcalAllData = retICal==null ? null : new StringBuilder();
Java
mit
13f6109b26aca48a153e563702c4165b2fb4d28f
0
Kaishiyoku/youtube-download-helper,Kaishiyoku/youtube-download-helper
package com.kaishiyoku.youtubedownloadhelper; import de.vandermeer.asciitable.AT_Context; import de.vandermeer.asciitable.AsciiTable; import de.vandermeer.asciithemes.TA_GridThemes; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class Main { private final static long MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS = 30; private static List<Channel> channels = new ArrayList<>(); public static void main(String[] args) { downloadYoutubeDlIfNeeded(); createChannelConfigIfNeeded(); loadChannelConfig(); cls(); int status = 1; while (status == 1) { int option = showMenuOptions(); switch (option) { case 1: cls(); listChannels(); break; case 2: cls(); addChannel(); break; case 3: cls(); removeChannel(); break; case 4: cls(); startDownload(); break; case 0: status = 0; break; default: cls(); System.out.println("Invalid option."); } System.out.println(""); System.out.println(""); } System.exit(0); } private static int showMenuOptions() { Scanner scanner = new Scanner(System.in); System.out.println("Options:"); System.out.println(" 1: List channels"); System.out.println(" 2: Add channel"); System.out.println(" 3: Remove channel"); System.out.println(" 4: Start download"); System.out.println(" 0: Exit"); System.out.println(""); int option = scanner.nextInt(); return option; } private static void loadChannelConfig() { File channelConfigFile = new File("config/channels.txt"); try (Stream<String> lines = Files.lines(channelConfigFile.toPath())) { lines.filter(s -> !s.startsWith("#")).forEach(s -> channels.add(new Channel(s))); } catch (IOException e) { e.printStackTrace(); } } private static void createChannelConfigIfNeeded() { File dir = new File("config"); dir.mkdirs(); try { File channelConfigFile = new File("config/channels.txt"); if (!channelConfigFile.exists()) { PrintWriter writer = new PrintWriter(channelConfigFile, "UTF-8"); writer.println("# Enter here the YouTube channels you want to download in the following format, one channel per row:"); writer.println("# The description field is for visibility only and will not be used by the downloader."); writer.println("# <DESCRIPTION>;<URL>;<LOCAL_PATH>"); writer.close(); } } catch (IOException e) { e.printStackTrace(); } } private static void listChannels() { AT_Context ctx = new AT_Context(); ctx.setGridTheme(TA_GridThemes.FULL); AsciiTable at = new AsciiTable(ctx); at.addRule(); at.addRow("#", "DESCRIPTION", "URL", "LOCAL PATH"); at.addRule(); if (channels.size() == 0) { at.addRow(null, null, null, "no channels yet"); } int i = 1; for (Channel channel : channels) { at.addRow(i, channel.getDescription(), channel.getUrl(), channel.getLocalPath()); i++; } at.addRule(); System.out.println(at.render()); } private static void addChannel() { Scanner scanner = new Scanner(System.in); System.out.print("Description: "); String description = scanner.next(); System.out.print("URL: "); String url = scanner.next(); System.out.print("Local path: "); String localPath = scanner.next(); Channel channel = new Channel(description, url, localPath); channels.add(channel); saveChannels(channel); } private static void removeChannel() { listChannels(); Scanner scanner = new Scanner(System.in); System.out.print("Remove channel #: "); int channelNumber = scanner.nextInt(); channels.remove(channelNumber - 1); saveChannels(); System.out.println("Channel removed"); listChannels(); } private static void saveChannels() { saveChannels(null); } private static void saveChannels(Channel channel) { // save to file File channelConfigFile = new File("config/channels.txt"); PrintWriter writer = null; List<String> channelLines = new ArrayList<>(); try (Stream<String> lines = Files.lines(channelConfigFile.toPath())) { lines.forEach(s -> channelLines.add(s)); } catch (IOException e) { e.printStackTrace(); } if (channel != null) { channelLines.add(channel.toConfigLine()); } try { writer = new PrintWriter(channelConfigFile); for (String line : channelLines) { writer.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { writer.close(); } } private static void downloadYoutubeDlIfNeeded() { File dir = new File("third_party"); dir.mkdirs(); String baseUrl = "https://yt-dl.org/downloads/latest/"; // check if file already exists File youtubeDlFile = new File("third_party/" + getYoutubeDlFileName()); long ageOfFile = new Date().getTime() - youtubeDlFile.lastModified(); boolean fileNotExistsOrIsVeryOld = !youtubeDlFile.exists(); if (!fileNotExistsOrIsVeryOld && ageOfFile > MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS * 24 * 60 * 60 * 1000) { fileNotExistsOrIsVeryOld = true; } if (fileNotExistsOrIsVeryOld) { System.out.println("Downloading youtube-dl tool from https://rg3.github.io/youtube-dl/..."); URL url; try { url = new URL(baseUrl + getYoutubeDlFileName()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("third_party/" + getYoutubeDlFileName())); byte[] buf = new byte[512]; while (true) { int len = in.read(buf); if (len == -1) { break; } fos.write(buf, 0, len); } in.close(); fos.flush(); fos.close(); System.out.println("...done."); pressToContinue(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private static void cls() { System.out.print("\033[H\033[2J"); System.out.flush(); } private static void startDownload() { File youtubeDlFile = new File("third_party/" + getYoutubeDlFileName()); for (Channel channel : channels) { Process p; try { System.out.println("Starting downloads for \"" + channel.getDescription() + "\""); System.out.println(""); List<String> newParams = new ArrayList<>(); if (isWindows()) { newParams.add("cmd"); newParams.add("/c"); } newParams.add(youtubeDlFile.getAbsolutePath()); newParams.add("--yes-playlist"); newParams.add("--output"); newParams.add(channel.getLocalPath() + "/%(title)s.%(ext)s"); newParams.add("--ignore-errors"); newParams.add("--no-overwrites"); newParams.add(channel.getUrl()); ProcessBuilder builder = new ProcessBuilder(newParams); builder.redirectErrorStream(true); p = builder.start(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while (true) { line = r.readLine(); if (line == null) { break; } System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } private static void pressToContinue() { System.out.println(""); System.out.println("Press any key to continue"); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } private static String getYoutubeDlFileName() { String fileName = "youtube-dl"; if (isWindows()) { fileName += ".exe"; } return fileName; } private static boolean isWindows() { return System.getProperty("os.name").startsWith("Windows"); } }
src/main/java/com/kaishiyoku/youtubedownloadhelper/Main.java
package com.kaishiyoku.youtubedownloadhelper; import de.vandermeer.asciitable.AT_Context; import de.vandermeer.asciitable.AsciiTable; import de.vandermeer.asciithemes.TA_GridThemes; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.stream.Stream; public class Main { private final static long MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS = 30; private static List<Channel> channels = new ArrayList<>(); public static void main(String[] args) { downloadYoutubeDlIfNeeded(); createChannelConfigIfNeeded(); loadChannelConfig(); cls(); int status = 1; while (status == 1) { int option = showMenuOptions(); switch (option) { case 1: cls(); listChannels(); break; case 2: cls(); addChannel(); break; case 3: cls(); removeChannel(); break; case 4: cls(); startDownload(); break; case 0: status = 0; break; default: cls(); System.out.println("Invalid option."); } System.out.println(""); System.out.println(""); } System.exit(0); } private static int showMenuOptions() { Scanner scanner = new Scanner(System.in); System.out.println("Options:"); System.out.println(" 1: List channels"); System.out.println(" 2: Add channel"); System.out.println(" 3: Remove channel"); System.out.println(" 4: Start download"); System.out.println(" 0: Exit"); System.out.println(""); int option = scanner.nextInt(); return option; } private static void loadChannelConfig() { File channelConfigFile = new File("config/channels.txt"); try (Stream<String> lines = Files.lines(channelConfigFile.toPath())) { lines.filter(s -> !s.startsWith("#")).forEach(s -> channels.add(new Channel(s))); } catch (IOException e) { e.printStackTrace(); } } private static void createChannelConfigIfNeeded() { File dir = new File("config"); dir.mkdirs(); try { File channelConfigFile = new File("config/channels.txt"); if (!channelConfigFile.exists()) { PrintWriter writer = new PrintWriter(channelConfigFile, "UTF-8"); writer.println("# Enter here the YouTube channels you want to download in the following format, one channel per row:"); writer.println("# The description field is for visibility only and will not be used by the downloader."); writer.println("# <DESCRIPTION>;<URL>;<LOCAL_PATH>"); writer.close(); } } catch (IOException e) { e.printStackTrace(); } } private static void listChannels() { AT_Context ctx = new AT_Context(); ctx.setGridTheme(TA_GridThemes.FULL); AsciiTable at = new AsciiTable(ctx); at.addRule(); at.addRow("#", "DESCRIPTION", "URL", "LOCAL PATH"); at.addRule(); if (channels.size() == 0) { at.addRow(null, null, null, "no channels yet"); } int i = 1; for (Channel channel : channels) { at.addRow(i, channel.getDescription(), channel.getUrl(), channel.getLocalPath()); i++; } at.addRule(); System.out.println(at.render()); } private static void addChannel() { Scanner scanner = new Scanner(System.in); System.out.print("Description: "); String description = scanner.next(); System.out.print("URL: "); String url = scanner.next(); System.out.print("Local path: "); String localPath = scanner.next(); Channel channel = new Channel(description, url, localPath); channels.add(channel); saveChannels(channel); } private static void removeChannel() { listChannels(); Scanner scanner = new Scanner(System.in); System.out.print("Remove channel #: "); int channelNumber = scanner.nextInt(); channels.remove(channelNumber - 1); saveChannels(); System.out.println("Channel removed"); listChannels(); } private static void saveChannels() { saveChannels(null); } private static void saveChannels(Channel channel) { // save to file File channelConfigFile = new File("config/channels.txt"); PrintWriter writer = null; List<String> channelLines = new ArrayList<>(); try (Stream<String> lines = Files.lines(channelConfigFile.toPath())) { lines.forEach(s -> channelLines.add(s)); } catch (IOException e) { e.printStackTrace(); } if (channel != null) { channelLines.add(channel.toConfigLine()); } try { writer = new PrintWriter(channelConfigFile); for (String line : channelLines) { writer.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { writer.close(); } } private static void downloadYoutubeDlIfNeeded() { File dir = new File("third_party"); dir.mkdirs(); String baseUrl = "https://yt-dl.org/downloads/latest/"; String fileName = "youtube-dl"; if (System.getProperty("os.name").startsWith("Windows")) { fileName += ".exe"; } // check if file already exists File youtubeDlFile = new File("third_party/" + fileName); long ageOfFile = new Date().getTime() - youtubeDlFile.lastModified(); boolean fileNotExistsOrIsVeryOld = !youtubeDlFile.exists(); if (!fileNotExistsOrIsVeryOld && ageOfFile > MAX_AGE_OF_YOUTUBE_DL_FILE_IN_DAYS * 24 * 60 * 60 * 1000) { fileNotExistsOrIsVeryOld = true; } if (fileNotExistsOrIsVeryOld) { System.out.println("Downloading youtube-dl tool from https://rg3.github.io/youtube-dl/..."); URL url; try { url = new URL(baseUrl + fileName); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("third_party/" + fileName)); byte[] buf = new byte[512]; while (true) { int len = in.read(buf); if (len == -1) { break; } fos.write(buf, 0, len); } in.close(); fos.flush(); fos.close(); System.out.println("...done."); pressToContinue(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private static void cls() { System.out.print("\033[H\033[2J"); System.out.flush(); } private static void startDownload() { } private static void pressToContinue() { System.out.println(""); System.out.println("Press any key to continue"); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
added download feature
src/main/java/com/kaishiyoku/youtubedownloadhelper/Main.java
added download feature
<ide><path>rc/main/java/com/kaishiyoku/youtubedownloadhelper/Main.java <ide> dir.mkdirs(); <ide> <ide> String baseUrl = "https://yt-dl.org/downloads/latest/"; <del> String fileName = "youtube-dl"; <del> <del> if (System.getProperty("os.name").startsWith("Windows")) { <del> fileName += ".exe"; <del> } <ide> <ide> // check if file already exists <del> File youtubeDlFile = new File("third_party/" + fileName); <add> File youtubeDlFile = new File("third_party/" + getYoutubeDlFileName()); <ide> <ide> long ageOfFile = new Date().getTime() - youtubeDlFile.lastModified(); <ide> <ide> URL url; <ide> <ide> try { <del> url = new URL(baseUrl + fileName); <add> url = new URL(baseUrl + getYoutubeDlFileName()); <ide> URLConnection connection = url.openConnection(); <ide> InputStream in = connection.getInputStream(); <del> FileOutputStream fos = new FileOutputStream(new File("third_party/" + fileName)); <add> FileOutputStream fos = new FileOutputStream(new File("third_party/" + getYoutubeDlFileName())); <ide> <ide> byte[] buf = new byte[512]; <ide> <ide> } <ide> <ide> private static void startDownload() { <del> <add> File youtubeDlFile = new File("third_party/" + getYoutubeDlFileName()); <add> <add> for (Channel channel : channels) { <add> Process p; <add> <add> try { <add> System.out.println("Starting downloads for \"" + channel.getDescription() + "\""); <add> System.out.println(""); <add> <add> List<String> newParams = new ArrayList<>(); <add> <add> if (isWindows()) { <add> newParams.add("cmd"); <add> newParams.add("/c"); <add> } <add> <add> newParams.add(youtubeDlFile.getAbsolutePath()); <add> newParams.add("--yes-playlist"); <add> newParams.add("--output"); <add> newParams.add(channel.getLocalPath() + "/%(title)s.%(ext)s"); <add> newParams.add("--ignore-errors"); <add> newParams.add("--no-overwrites"); <add> newParams.add(channel.getUrl()); <add> <add> ProcessBuilder builder = new ProcessBuilder(newParams); <add> builder.redirectErrorStream(true); <add> p = builder.start(); <add> BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); <add> String line; <add> <add> while (true) { <add> line = r.readLine(); <add> <add> if (line == null) { <add> break; <add> } <add> <add> System.out.println(line); <add> } <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <add> } <ide> } <ide> <ide> private static void pressToContinue() { <ide> e.printStackTrace(); <ide> } <ide> } <add> <add> private static String getYoutubeDlFileName() { <add> String fileName = "youtube-dl"; <add> <add> if (isWindows()) { <add> fileName += ".exe"; <add> } <add> <add> return fileName; <add> } <add> <add> private static boolean isWindows() { <add> return System.getProperty("os.name").startsWith("Windows"); <add> } <ide> }
Java
mit
5142da5ba2c807f2f442195999bfd5d57a7a8aed
0
GreenfieldTech/irked
package tech.greenfield.vertx.irked; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.web.handler.BodyHandler; import tech.greenfield.vertx.irked.annotations.Endpoint; import tech.greenfield.vertx.irked.annotations.Get; import tech.greenfield.vertx.irked.annotations.Put; import tech.greenfield.vertx.irked.base.TestBase; import tech.greenfield.vertx.irked.status.InternalServerError; public class TestRouteCascade extends TestBase { AtomicInteger failedTests = new AtomicInteger(0); String fieldName = "value"; public class TestControllerCascadeField extends Controller { JsonObject data = new JsonObject().put(fieldName, 1); @Endpoint("/*") BodyHandler bodyHandler = BodyHandler.create(); @Put("/") WebHandler update = r -> { rule.vertx().executeBlocking(f -> { data.mergeIn(r.getBodyAsJson()); f.complete(); }, f -> { if (f.failed()) r.sendError(new InternalServerError(f.cause())); else r.next(); }); }; @Put("/") @Get("/") WebHandler retrieve = r -> { r.sendJSON(data); }; @Get("/foo") WebHandler foo1 = r -> { r.send("ok"); }; @Get("/foo") WebHandler foo2 = r -> { r.send("shouldn't happen"); failedTests.incrementAndGet(); }; } @Test public void testCascadingFieldHandlers(TestContext context) { deployController(new TestControllerCascadeField(), context.asyncAssertSuccess(s -> executeTest(context))); } private void executeTest(TestContext context) { int newVal = 5; Async async = context.async(); getClient().put(port, "localhost", "/").exceptionHandler(t -> context.fail(t)).handler(r -> { context.assertEquals(200, r.statusCode(), "Failed to call PUT"); r.exceptionHandler(t -> context.fail(t)).bodyHandler(body -> { context.assertEquals(newVal, body.toJsonObject().getInteger(fieldName)); async.complete(); }); }).end(new JsonObject().put(fieldName, newVal).encode()); } @Test public void testNotCascadingFieldHandlers(TestContext context) { deployController(new TestControllerCascadeField(), context.asyncAssertSuccess(s -> executeTestNoCascade(context))); } private void executeTestNoCascade(TestContext context) { Async async = context.async(); getClient().get(port, "localhost", "/foo").exceptionHandler(t -> context.fail(t)).handler(r -> { context.assertEquals(200, r.statusCode(), "Failed to call GET /foo"); r.exceptionHandler(t -> context.fail(t)).bodyHandler(body -> { context.assertEquals("ok", body.toString()); context.assertEquals(0, failedTests.get()); async.complete(); }); }).end(); } }
src/test/java/tech/greenfield/vertx/irked/TestRouteCascade.java
package tech.greenfield.vertx.irked; import org.junit.Test; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.web.handler.BodyHandler; import tech.greenfield.vertx.irked.annotations.Endpoint; import tech.greenfield.vertx.irked.annotations.Get; import tech.greenfield.vertx.irked.annotations.Put; import tech.greenfield.vertx.irked.base.TestBase; import tech.greenfield.vertx.irked.status.InternalServerError; public class TestRouteCascade extends TestBase { String fieldName = "value"; public class TestControllerCascadeField extends Controller { JsonObject data = new JsonObject().put(fieldName, 1); @Endpoint("/*") BodyHandler bodyHandler = BodyHandler.create(); @Put("/") WebHandler update = r -> { rule.vertx().executeBlocking(f -> { data.mergeIn(r.getBodyAsJson()); f.complete(); }, f -> { if (f.failed()) r.sendError(new InternalServerError(f.cause())); else r.next(); }); }; @Put("/") @Get("/") WebHandler retrieve = r -> { r.sendJSON(data); }; @Get("/foo") WebHandler foo1 = r -> { r.send("ok"); }; @Get("/foo") WebHandler foo2 = r -> { r.send("shouldn't happen"); }; } @Test public void testCascadingFieldHandlers(TestContext context) { deployController(new TestControllerCascadeField(), context.asyncAssertSuccess(s -> executeTest(context))); } private void executeTest(TestContext context) { int newVal = 5; Async async = context.async(); getClient().put(port, "localhost", "/").exceptionHandler(t -> context.fail(t)).handler(r -> { context.assertEquals(200, r.statusCode(), "Failed to call PUT"); r.exceptionHandler(t -> context.fail(t)).bodyHandler(body -> { context.assertEquals(newVal, body.toJsonObject().getInteger(fieldName)); async.complete(); }); }).end(new JsonObject().put(fieldName, newVal).encode()); } @Test public void testNotCascadingFieldHandlers(TestContext context) { deployController(new TestControllerCascadeField(), context.asyncAssertSuccess(s -> executeTestNoCascade(context))); } private void executeTestNoCascade(TestContext context) { Async async = context.async(); getClient().get(port, "localhost", "/foo").exceptionHandler(t -> context.fail(t)).handler(r -> { context.assertEquals(200, r.statusCode(), "Failed to call GET /foo"); r.exceptionHandler(t -> context.fail(t)).bodyHandler(body -> { context.assertEquals("ok", body.toString()); async.complete(); }); }).end(); } }
really make sure that cascading routes aren't being called if there's no next()
src/test/java/tech/greenfield/vertx/irked/TestRouteCascade.java
really make sure that cascading routes aren't being called if there's no next()
<ide><path>rc/test/java/tech/greenfield/vertx/irked/TestRouteCascade.java <ide> package tech.greenfield.vertx.irked; <add> <add>import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import org.junit.Test; <ide> <ide> import tech.greenfield.vertx.irked.status.InternalServerError; <ide> <ide> public class TestRouteCascade extends TestBase { <add> <add> AtomicInteger failedTests = new AtomicInteger(0); <ide> <ide> String fieldName = "value"; <ide> <ide> @Get("/foo") <ide> WebHandler foo2 = r -> { <ide> r.send("shouldn't happen"); <add> failedTests.incrementAndGet(); <ide> }; <ide> <ide> } <ide> context.assertEquals(200, r.statusCode(), "Failed to call GET /foo"); <ide> r.exceptionHandler(t -> context.fail(t)).bodyHandler(body -> { <ide> context.assertEquals("ok", body.toString()); <add> context.assertEquals(0, failedTests.get()); <ide> async.complete(); <ide> }); <ide> }).end();
Java
epl-1.0
dfde34df186c333262cb00a36c61cb84ef26734e
0
vryba/selenium
package com.vryba.selenium.excelReader; import com.vryba.selenium.utilities.Constant; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.FileOutputStream; public class ExcelDataReader { private XSSFSheet excelWSheet; private XSSFWorkbook excelWBook; private XSSFCell cell; private XSSFRow row; //method to set filePath, open excelFile, passing path and sheetname as args to this method public ExcelDataReader(String path, String sheetName) throws Exception{ try { //Open excel file FileInputStream excelFile = new FileInputStream(path); //access required test dataProvider sheet excelWBook = new XSSFWorkbook(excelFile); excelWSheet = excelWBook.getSheet(sheetName); } catch (Exception e){ throw e; } } //method to get number of rows in a sheet public int getLastRow(){ return excelWSheet.getLastRowNum(); } //method to read test dataProvider from file cell, in we're passing parameters as RowNum and ColNum public String getCellData(int RowNum, int ColNum){ try { cell = excelWSheet.getRow(RowNum).getCell(ColNum); String CellData = cell.getStringCellValue(); return CellData; }catch (Exception e){ return ""; } } //method to write into the Excel cell, Row num and Col num are the parameters public void setCellData(String Result, int RowNum, int ColNum)throws Exception { try { row = excelWSheet.getRow(RowNum); cell = row.getCell(ColNum, row.RETURN_BLANK_AS_NULL); if (cell == null) { cell = row.createCell(ColNum); cell.setCellValue(Result); } else { cell.setCellValue(Result); } //Constant variable Test Data path and Test Data file name FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData + Constant.File_TestData); excelWBook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (Exception e) { throw e; } } }
src/main/java/com/vryba/selenium/excelReader/ExcelDataReader.java
package com.vryba.selenium.excelReader; import com.vryba.selenium.utilities.Constant; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.FileOutputStream; public class ExcelDataReader { private XSSFSheet excelWSheet; private XSSFWorkbook excelWBook; private XSSFCell cell; private XSSFRow row; //method to set filePath, open excelFile, pass path and sheetname as args to this method public ExcelDataReader(String path, String sheetName) throws Exception{ try { //Open excel file FileInputStream excelFile = new FileInputStream(path); //access required test dataProvider sheet excelWBook = new XSSFWorkbook(excelFile); excelWSheet = excelWBook.getSheet(sheetName); } catch (Exception e){ throw e; } } //method to get number of rows in a sheet public int getLastRow(){ return excelWSheet.getLastRowNum(); } //method to read test dataProvider from file cell, in we're passing parameters as Rox num nad Col num public String getCellData(int RowNum, int ColNum){ try { cell = excelWSheet.getRow(RowNum).getCell(ColNum); String CellData = cell.getStringCellValue(); return CellData; }catch (Exception e){ return ""; } } //method to write in the Excel cell, row num and Col num are the parameters public void setCellData(String Result, int RowNum, int ColNum)throws Exception { try { row = excelWSheet.getRow(RowNum); cell = row.getCell(ColNum, row.RETURN_BLANK_AS_NULL); if (cell == null) { cell = row.createCell(ColNum); cell.setCellValue(Result); } else { cell.setCellValue(Result); } //Constant variable Test Data path and Test Data file name FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData + Constant.File_TestData); excelWBook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (Exception e) { throw e; } } }
Comments updated in ExcelDataReader class
src/main/java/com/vryba/selenium/excelReader/ExcelDataReader.java
Comments updated in ExcelDataReader class
<ide><path>rc/main/java/com/vryba/selenium/excelReader/ExcelDataReader.java <ide> private XSSFCell cell; <ide> private XSSFRow row; <ide> <del> //method to set filePath, open excelFile, pass path and sheetname as args to this method <add> //method to set filePath, open excelFile, passing path and sheetname as args to this method <ide> public ExcelDataReader(String path, String sheetName) throws Exception{ <ide> <ide> try { <ide> <ide> return excelWSheet.getLastRowNum(); <ide> } <del> //method to read test dataProvider from file cell, in we're passing parameters as Rox num nad Col num <add> //method to read test dataProvider from file cell, in we're passing parameters as RowNum and ColNum <ide> public String getCellData(int RowNum, int ColNum){ <ide> try { <ide> cell = excelWSheet.getRow(RowNum).getCell(ColNum); <ide> return ""; <ide> } <ide> } <del> //method to write in the Excel cell, row num and Col num are the parameters <add> //method to write into the Excel cell, Row num and Col num are the parameters <ide> public void setCellData(String Result, int RowNum, int ColNum)throws Exception { <ide> try { <ide> row = excelWSheet.getRow(RowNum);
Java
lgpl-2.1
6d81e6a3a7b76a354802054fce84ec005741e7dc
0
pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.xwiki.velocity.internal; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.component.logging.AbstractLogEnabled; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.management.JMXBeanRegistration; import org.xwiki.velocity.VelocityEngine; import org.xwiki.velocity.VelocityFactory; import org.xwiki.velocity.XWikiVelocityException; import org.xwiki.velocity.internal.jmx.JMXVelocityEngine; import org.xwiki.velocity.internal.jmx.JMXVelocityEngineMBean; /** * Default implementation for {@link VelocityFactory}. * * @see VelocityFactory * @version $Id$ */ @Component public class DefaultVelocityFactory extends AbstractLogEnabled implements VelocityFactory { /** * The Component manager we use to lookup (and thus create since it's a singleton) the VelocityEngine component. */ @Requirement private ComponentManager componentManager; /** * In order to register the Velocity MBean for management. */ @Requirement private JMXBeanRegistration jmxRegistration; /** * A cache of Velocity Engines. See {@link org.xwiki.velocity.VelocityFactory} for more details as to why we need * this cache. */ private Map<String, VelocityEngine> velocityEngines = new HashMap<String, VelocityEngine>(); /** * {@inheritDoc} * * @see VelocityFactory#hasVelocityEngine(String) */ public boolean hasVelocityEngine(String key) { return this.velocityEngines.containsKey(key); } /** * {@inheritDoc} * * @see VelocityFactory#getVelocityEngine(String) */ public VelocityEngine getVelocityEngine(String key) { return this.velocityEngines.get(key); } /** * {@inheritDoc} * * @see VelocityFactory#createVelocityEngine(String, Properties) */ public VelocityEngine createVelocityEngine(String key, Properties properties) throws XWikiVelocityException { synchronized (this.velocityEngines) { VelocityEngine engine; if (this.velocityEngines.containsKey(key)) { engine = this.velocityEngines.get(key); } else { try { engine = this.componentManager.lookup(VelocityEngine.class); } catch (ComponentLookupException e) { throw new XWikiVelocityException("Failed to create Velocity Engine", e); } engine.initialize(properties); this.velocityEngines.put(key, engine); } // Register a JMX MBean for providing information about the created Velocity Engine (template namespaces, // macros, etc). JMXVelocityEngineMBean mbean = new JMXVelocityEngine(engine); this.jmxRegistration.registerMBean(mbean, "type=Velocity,domain=Engines,name=" + key); return engine; } } }
xwiki-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityFactory.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.xwiki.velocity.internal; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.component.logging.AbstractLogEnabled; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.management.JMXBeanRegistration; import org.xwiki.velocity.VelocityEngine; import org.xwiki.velocity.VelocityFactory; import org.xwiki.velocity.XWikiVelocityException; import org.xwiki.velocity.internal.jmx.JMXVelocityEngine; import org.xwiki.velocity.internal.jmx.JMXVelocityEngineMBean; /** * Default implementation for {@link VelocityFactory}. * * @see VelocityFactory * @version $Id$ */ @Component public class DefaultVelocityFactory extends AbstractLogEnabled implements VelocityFactory { /** * The Component manager we use to lookup (and thus create since it's a singleton) the VelocityEngine component. */ @Requirement private ComponentManager componentManager; /** * In order to register the Velocity MBean for management. */ @Requirement private JMXBeanRegistration jmxRegistration; /** * A cache of Velocity Engines. See {@link org.xwiki.velocity.VelocityFactory} for more details as to why we need * this cache. */ private Map<String, VelocityEngine> velocityEngines = new HashMap<String, VelocityEngine>(); /** * {@inheritDoc} * * @see VelocityFactory#hasVelocityEngine(String) */ public boolean hasVelocityEngine(String key) { return this.velocityEngines.containsKey(key); } /** * {@inheritDoc} * * @see VelocityFactory#getVelocityEngine(String) */ public VelocityEngine getVelocityEngine(String key) { return this.velocityEngines.get(key); } /** * {@inheritDoc} * * @see VelocityFactory#createVelocityEngine(String, Properties) */ public VelocityEngine createVelocityEngine(String key, Properties properties) throws XWikiVelocityException { VelocityEngine engine; if (this.velocityEngines.containsKey(key)) { engine = this.velocityEngines.get(key); } else { try { engine = this.componentManager.lookup(VelocityEngine.class); } catch (ComponentLookupException e) { throw new XWikiVelocityException("Failed to create Velocity Engine", e); } engine.initialize(properties); this.velocityEngines.put(key, engine); } // Register a JMX MBean for providing information about the created Velocity Engine (template namespaces, // macros, etc). JMXVelocityEngineMBean mbean = new JMXVelocityEngine(engine); this.jmxRegistration.registerMBean(mbean, "type=Velocity,domain=Engines,name=" + key); return engine; } }
Make sure that we have a single velocity engine created per given key (before this fix the Lucene rebuild thread was fighting with the main doc thread and they were creating 2 instances of the velocity engine for "default"). git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@29566 f329d543-caf0-0310-9063-dda96c69346f
xwiki-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityFactory.java
Make sure that we have a single velocity engine created per given key (before this fix the Lucene rebuild thread was fighting with the main doc thread and they were creating 2 instances of the velocity engine for "default").
<ide><path>wiki-velocity/src/main/java/org/xwiki/velocity/internal/DefaultVelocityFactory.java <ide> */ <ide> public VelocityEngine createVelocityEngine(String key, Properties properties) throws XWikiVelocityException <ide> { <del> VelocityEngine engine; <del> if (this.velocityEngines.containsKey(key)) { <del> engine = this.velocityEngines.get(key); <del> } else { <del> try { <del> engine = this.componentManager.lookup(VelocityEngine.class); <del> } catch (ComponentLookupException e) { <del> throw new XWikiVelocityException("Failed to create Velocity Engine", e); <add> synchronized (this.velocityEngines) { <add> VelocityEngine engine; <add> if (this.velocityEngines.containsKey(key)) { <add> engine = this.velocityEngines.get(key); <add> } else { <add> try { <add> engine = this.componentManager.lookup(VelocityEngine.class); <add> } catch (ComponentLookupException e) { <add> throw new XWikiVelocityException("Failed to create Velocity Engine", e); <add> } <add> engine.initialize(properties); <add> this.velocityEngines.put(key, engine); <ide> } <del> engine.initialize(properties); <del> this.velocityEngines.put(key, engine); <add> <add> // Register a JMX MBean for providing information about the created Velocity Engine (template namespaces, <add> // macros, etc). <add> JMXVelocityEngineMBean mbean = new JMXVelocityEngine(engine); <add> this.jmxRegistration.registerMBean(mbean, "type=Velocity,domain=Engines,name=" + key); <add> <add> return engine; <ide> } <del> <del> // Register a JMX MBean for providing information about the created Velocity Engine (template namespaces, <del> // macros, etc). <del> JMXVelocityEngineMBean mbean = new JMXVelocityEngine(engine); <del> this.jmxRegistration.registerMBean(mbean, "type=Velocity,domain=Engines,name=" + key); <del> <del> return engine; <ide> } <ide> }
Java
bsd-3-clause
73a74b52ff1d79809fc4ba3b68fd224f61a5c43c
0
gaddirg/itais,gaddirg/itais,gaddirg/itais
package org.itais.service; import java.util.List; import org.itais.domain.Inventory; import org.itais.domain.Office; import org.itais.repository.InventoryRepository; import org.itais.repository.OfficeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * * */ @Service public class InventoryService { private InventoryRepository inventoryRepository; @Autowired public InventoryService(InventoryRepository inventoryRepository) { this.inventoryRepository = inventoryRepository; } public Inventory get(Long id) { return inventoryRepository.findOne(id); } public Inventory save(Inventory inventory) { Inventory tempInventory = inventoryRepository.findById(inventory.getId()); if(tempInventory == null) return inventoryRepository.save(inventory); else { Inventory inventoryDetails = new Inventory(); inventoryDetails.setId(inventory.getId()); inventoryDetails.setName(inventory.getName()); inventoryDetails.setSerialNumber(inventory.getSerialNumber()); inventoryDetails.setCreatedOn(tempInventory.getCreatedOn()); inventoryDetails.setAssetType(inventory.getAssetType()); inventoryDetails.setOffice(inventory.getOffice()); return inventoryRepository.save(inventoryDetails); } } public List<Inventory> list() { return inventoryRepository.findAllByOrderByCreatedOnDesc(); } public Inventory findBySerialNumber(String serialNumber) { return inventoryRepository.findBySerialNumber(serialNumber); } public Inventory findById(Long id) { // TODO Auto-generated method stub return inventoryRepository.findById(id); } public void delete(Long id) { // TODO Auto-generated method stub inventoryRepository.delete(id); } }
src/main/java/org/itais/service/InventoryService.java
package org.itais.service; import java.util.List; import org.itais.domain.Inventory; import org.itais.domain.Office; import org.itais.repository.InventoryRepository; import org.itais.repository.OfficeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * * */ @Service public class InventoryService { private InventoryRepository inventoryRepository; @Autowired public InventoryService(InventoryRepository inventoryRepository) { this.inventoryRepository = inventoryRepository; } public Inventory get(Long id) { return inventoryRepository.findOne(id); } public Inventory save(Inventory inventory) { Inventory tempInventory = inventoryRepository.findById(inventory.getId()); if(tempInventory == null) return inventoryRepository.save(inventory); else { Inventory inventoryDetails = new Inventory(); inventoryDetails.setId(inventory.getId()); inventoryDetails.setName(inventory.getName()); inventoryDetails.setSerialNumber(inventory.getSerialNumber()); inventoryDetails.setCreatedOn(tempInventory.getCreatedOn()); inventoryDetails.setAssetType(inventory.getAssetType()); inventoryDetails.setOffice(tempInventory.getOffice()); return inventoryRepository.save(inventoryDetails); } } public List<Inventory> list() { return inventoryRepository.findAllByOrderByCreatedOnDesc(); } public Inventory findBySerialNumber(String serialNumber) { return inventoryRepository.findBySerialNumber(serialNumber); } public Inventory findById(Long id) { // TODO Auto-generated method stub return inventoryRepository.findById(id); } public void delete(Long id) { // TODO Auto-generated method stub inventoryRepository.delete(id); } }
fix inventory save office branch
src/main/java/org/itais/service/InventoryService.java
fix inventory save office branch
<ide><path>rc/main/java/org/itais/service/InventoryService.java <ide> inventoryDetails.setSerialNumber(inventory.getSerialNumber()); <ide> inventoryDetails.setCreatedOn(tempInventory.getCreatedOn()); <ide> inventoryDetails.setAssetType(inventory.getAssetType()); <del> inventoryDetails.setOffice(tempInventory.getOffice()); <add> inventoryDetails.setOffice(inventory.getOffice()); <ide> return inventoryRepository.save(inventoryDetails); <ide> } <ide> }
Java
mit
daae1aec6c3fc9130d533aa38c757f2af0c54caf
0
JetBrains/ideavim,JetBrains/ideavim
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.group; import com.google.common.collect.ImmutableList; import com.intellij.codeInsight.editorActions.CopyPastePostProcessor; import com.intellij.codeInsight.editorActions.CopyPastePreProcessor; import com.intellij.codeInsight.editorActions.TextBlockTransferable; import com.intellij.codeInsight.editorActions.TextBlockTransferableData; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.CaretStateTransferableData; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData; import com.intellij.openapi.editor.richcopy.view.RtfTransferableData; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainNextAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainPreviousAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryFwdAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryRevAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphNextAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphPreviousAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentenceNextStartAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentencePreviousStartAction; import com.maddyhome.idea.vim.action.motion.updown.MotionPercentOrMatchAction; import com.maddyhome.idea.vim.command.Argument; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.command.SelectionType; import com.maddyhome.idea.vim.common.Register; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.handler.EditorActionHandlerBase; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.StringHelper; import com.maddyhome.idea.vim.option.ListOption; import com.maddyhome.idea.vim.option.OptionsManager; import com.maddyhome.idea.vim.ui.ClipboardHandler; import kotlin.Pair; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * This group works with command associated with copying and pasting text */ public class RegisterGroup { private static final String WRITABLE_REGISTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-*+_/\""; private static final String READONLY_REGISTERS = ":.%#=/"; private static final String RECORDABLE_REGISTER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String PLAYBACK_REGISTER = RECORDABLE_REGISTER + "\".*+"; private static final String VALID_REGISTERS = WRITABLE_REGISTERS + READONLY_REGISTERS; private static final List<Character> CLIPBOARD_REGISTERS = ImmutableList.of('*', '+'); private static final Logger logger = Logger.getInstance(RegisterGroup.class.getName()); private char defaultRegister = '"'; private char lastRegister = defaultRegister; @NotNull private final HashMap<Character, Register> registers = new HashMap<>(); private char recordRegister = 0; @Nullable private List<KeyStroke> recordList = null; public RegisterGroup() { final ListOption clipboardOption = OptionsManager.INSTANCE.getClipboard(); if (clipboardOption != null) { clipboardOption.addOptionChangeListener(event -> { if (clipboardOption.contains("unnamed")) { defaultRegister = '*'; } else if (clipboardOption.contains("unnamedplus")) { defaultRegister = '+'; } else { defaultRegister = '"'; } lastRegister = defaultRegister; }); } } /** * Check to see if the last selected register can be written to. */ private boolean isRegisterWritable() { return READONLY_REGISTERS.indexOf(lastRegister) < 0; } /** * Store which register the user wishes to work with. * * @param reg The register name * @return true if a valid register name, false if not */ public boolean selectRegister(char reg) { if (VALID_REGISTERS.indexOf(reg) != -1) { lastRegister = reg; if (logger.isDebugEnabled()) logger.debug("register selected: " + lastRegister); return true; } else { return false; } } /** * Reset the selected register back to the default register. */ public void resetRegister() { lastRegister = defaultRegister; logger.debug("Last register reset to default register"); } public void resetRegisters() { registers.clear(); } /** * Store text into the last register. * * @param editor The editor to get the text from * @param range The range of the text to store * @param type The type of copy * @param isDelete is from a delete * @return true if able to store the text into the register, false if not */ public boolean storeText(@NotNull Editor editor, @NotNull TextRange range, @NotNull SelectionType type, boolean isDelete) { if (isRegisterWritable()) { String text = EditorHelper.getText(editor, range); return storeTextInternal(editor, range, text, type, lastRegister, isDelete); } return false; } public boolean storeTextInternal(@NotNull Editor editor, @NotNull TextRange range, @NotNull String text, @NotNull SelectionType type, char register, boolean isDelete) { // Null register doesn't get saved if (lastRegister == '_') return true; int start = range.getStartOffset(); int end = range.getEndOffset(); // Normalize the start and end if (start > end) { int t = start; start = end; end = t; } // If this is an uppercase register, we need to append the text to the corresponding lowercase register final List<TextBlockTransferableData> transferableData = start != -1 ? getTransferableData(editor, range, text) : new ArrayList<>(); final String processedText = start != -1 ? preprocessText(editor, range, text, transferableData) : text; if (logger.isDebugEnabled()) { final String transferableClasses = transferableData.stream().map(it -> it.getClass().getName()).collect(Collectors.joining(",")); logger.debug("Copy to '" + lastRegister + "' with transferable data: " + transferableClasses); } if (Character.isUpperCase(register)) { char lreg = Character.toLowerCase(register); Register r = registers.get(lreg); // Append the text if the lowercase register existed if (r != null) { r.addTextAndResetTransferableData(processedText); } // Set the text if the lowercase register didn't exist yet else { registers.put(lreg, new Register(lreg, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } } // Put the text in the specified register else { registers.put(register, new Register(register, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } if (CLIPBOARD_REGISTERS.contains(register)) { ClipboardHandler.setClipboardText(processedText, new ArrayList<>(transferableData), text); } // Also add it to the default register if the default wasn't specified if (register != defaultRegister && ".:/".indexOf(register) == -1) { registers.put(defaultRegister, new Register(defaultRegister, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } if (isDelete) { boolean smallInlineDeletion = type == SelectionType.CHARACTER_WISE && editor.offsetToLogicalPosition(start).line == editor.offsetToLogicalPosition(end).line; // Deletes go into numbered registers only if text is smaller than a line, register is used or it's a special case if (!smallInlineDeletion || register != defaultRegister || isSmallDeletionSpecialCase(editor)) { // Old 1 goes to 2, etc. Old 8 to 9, old 9 is lost for (char d = '8'; d >= '1'; d--) { Register t = registers.get(d); if (t != null) { t.rename((char)(d + 1)); registers.put((char)(d + 1), t); } } registers.put('1', new Register('1', type, processedText, new ArrayList<>(transferableData))); } // Deletes smaller than one line and without specified register go the the "-" register if (smallInlineDeletion && register == defaultRegister) { registers.put('-', new Register('-', type, processedText, new ArrayList<>(transferableData))); } } // Yanks also go to register 0 if the default register was used else if (register == defaultRegister) { registers.put('0', new Register('0', type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + '0' + "' contains: \"" + processedText + "\""); } if (start != -1) { VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, Math.max(end - 1, 0))); } return true; } @NotNull public List<TextBlockTransferableData> getTransferableData(@NotNull Editor editor, @NotNull TextRange textRange, String text) { final List<TextBlockTransferableData> transferableDatas = new ArrayList<>(); final Project project = editor.getProject(); if (project == null) return new ArrayList<>(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return new ArrayList<>(); DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : CopyPastePostProcessor.EP_NAME .getExtensionList()) { try { transferableDatas.addAll(processor.collectTransferableData(file, editor, textRange.getStartOffsets(), textRange.getEndOffsets())); } catch (IndexNotReadyException ignore) { } } }); transferableDatas.add(new CaretStateTransferableData(new int[]{0}, new int[]{text.length()})); // These data provided by {@link com.intellij.openapi.editor.richcopy.TextWithMarkupProcessor} doesn't work with // IdeaVim and I don't see a way to fix it // See https://youtrack.jetbrains.com/issue/VIM-1785 // See https://youtrack.jetbrains.com/issue/VIM-1731 transferableDatas.removeIf(it -> (it instanceof RtfTransferableData) || (it instanceof HtmlTransferableData)); return transferableDatas; } private String preprocessText(@NotNull Editor editor, @NotNull TextRange textRange, String text, List<TextBlockTransferableData> transferableDatas) { final Project project = editor.getProject(); if (project == null) return text; final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return text; String rawText = TextBlockTransferable.convertLineSeparators(text, "\n", transferableDatas); String escapedText; for (CopyPastePreProcessor processor : CopyPastePreProcessor.EP_NAME.getExtensionList()) { escapedText = processor.preprocessOnCopy(file, textRange.getStartOffsets(), textRange.getEndOffsets(), rawText); if (escapedText != null) { return escapedText; } } return text; } private boolean isSmallDeletionSpecialCase(Editor editor) { Command currentCommand = CommandState.getInstance(editor).getCommand(); if (currentCommand != null) { Argument argument = currentCommand.getArgument(); if (argument != null) { Command motionCommand = argument.getMotion(); if (motionCommand != null) { EditorActionHandlerBase action = motionCommand.getAction(); return action instanceof MotionPercentOrMatchAction || action instanceof MotionSentencePreviousStartAction || action instanceof MotionSentenceNextStartAction || action instanceof MotionGotoFileMarkAction || action instanceof SearchEntryFwdAction || action instanceof SearchEntryRevAction || action instanceof SearchAgainNextAction || action instanceof SearchAgainPreviousAction || action instanceof MotionParagraphNextAction || action instanceof MotionParagraphPreviousAction; } } } return false; } /** * Get the last register selected by the user * * @return The register, null if no such register */ @Nullable public Register getLastRegister() { return getRegister(lastRegister); } @Nullable public Register getPlaybackRegister(char r) { if (PLAYBACK_REGISTER.indexOf(r) != 0) { return getRegister(r); } else { return null; } } @Nullable public Register getRegister(char r) { // Uppercase registers actually get the lowercase register if (Character.isUpperCase(r)) { r = Character.toLowerCase(r); } return CLIPBOARD_REGISTERS.contains(r) ? refreshClipboardRegister(r) : registers.get(r); } /** * Gets the last register name selected by the user * * @return The register name */ public char getCurrentRegister() { return lastRegister; } /** * The register key for the default register. */ public char getDefaultRegister() { return defaultRegister; } @NotNull public List<Register> getRegisters() { final List<Register> res = new ArrayList<>(registers.values()); for (Character r : CLIPBOARD_REGISTERS) { final Register register = refreshClipboardRegister(r); if (register != null) { res.add(register); } } res.sort(new Register.KeySorter()); return res; } public boolean startRecording(Editor editor, char register) { if (RECORDABLE_REGISTER.indexOf(register) != -1) { CommandState.getInstance(editor).setRecording(true); recordRegister = register; recordList = new ArrayList<>(); return true; } else { return false; } } public void recordKeyStroke(KeyStroke key) { if (recordRegister != 0 && recordList != null) { recordList.add(key); } } public void recordText(@NotNull String text) { if (recordRegister != 0 && recordList != null) { recordList.addAll(StringHelper.stringToKeys(text)); } } public void setKeys(char register, @NotNull List<KeyStroke> keys) { registers.put(register, new Register(register, SelectionType.CHARACTER_WISE, keys)); } public void finishRecording(Editor editor) { if (recordRegister != 0) { Register reg = null; if (Character.isUpperCase(recordRegister)) { reg = getRegister(recordRegister); } if (recordList != null) { if (reg == null) { reg = new Register(Character.toLowerCase(recordRegister), SelectionType.CHARACTER_WISE, recordList); registers.put(Character.toLowerCase(recordRegister), reg); } else { reg.addKeys(recordList); } } CommandState.getInstance(editor).setRecording(false); } recordRegister = 0; } public void saveData(@NotNull final Element element) { logger.debug("saveData"); final Element registersElement = new Element("registers"); for (Character key : registers.keySet()) { final Register register = registers.get(key); final Element registerElement = new Element("register"); registerElement.setAttribute("name", String.valueOf(key)); registerElement.setAttribute("type", Integer.toString(register.getType().getValue())); final String text = register.getText(); if (text != null) { final Element textElement = new Element("text"); StringHelper.setSafeXmlText(textElement, text); registerElement.addContent(textElement); } else { final Element keys = new Element("keys"); final List<KeyStroke> list = register.getKeys(); for (KeyStroke stroke : list) { final Element k = new Element("key"); k.setAttribute("char", Integer.toString(stroke.getKeyChar())); k.setAttribute("code", Integer.toString(stroke.getKeyCode())); k.setAttribute("mods", Integer.toString(stroke.getModifiers())); keys.addContent(k); } registerElement.addContent(keys); } registersElement.addContent(registerElement); } element.addContent(registersElement); } public void readData(@NotNull final Element element) { logger.debug("readData"); final Element registersElement = element.getChild("registers"); if (registersElement != null) { final List<Element> registerElements = registersElement.getChildren("register"); for (Element registerElement : registerElements) { final char key = registerElement.getAttributeValue("name").charAt(0); final Register register; final Element textElement = registerElement.getChild("text"); final String typeText = registerElement.getAttributeValue("type"); final SelectionType type = SelectionType.fromValue(Integer.parseInt(typeText)); if (textElement != null) { final String text = StringHelper.getSafeXmlText(textElement); if (text != null) { register = new Register(key, type, text, Collections.emptyList()); } else { register = null; } } else { final Element keysElement = registerElement.getChild("keys"); final List<Element> keyElements = keysElement.getChildren("key"); final List<KeyStroke> strokes = new ArrayList<>(); for (Element keyElement : keyElements) { final int code = Integer.parseInt(keyElement.getAttributeValue("code")); final int modifiers = Integer.parseInt(keyElement.getAttributeValue("mods")); final char c = (char)Integer.parseInt(keyElement.getAttributeValue("char")); //noinspection MagicConstant strokes.add(c == KeyEvent.CHAR_UNDEFINED ? KeyStroke.getKeyStroke(code, modifiers) : KeyStroke.getKeyStroke(c)); } register = new Register(key, type, strokes); } registers.put(key, register); } } } @Nullable private Register refreshClipboardRegister(char r) { final Pair<String, List<TextBlockTransferableData>> clipboardData = ClipboardHandler.getClipboardTextAndTransferableData(); final Register currentRegister = registers.get(r); final String text = clipboardData.getFirst(); final List<TextBlockTransferableData> transferableData = clipboardData.getSecond(); if (text != null) { if (currentRegister != null && text.equals(currentRegister.getText())) { return currentRegister; } return new Register(r, guessSelectionType(text), text, transferableData); } return null; } @NotNull private SelectionType guessSelectionType(@NotNull String text) { if (text.endsWith("\n")) { return SelectionType.LINE_WISE; } else { return SelectionType.CHARACTER_WISE; } } }
src/com/maddyhome/idea/vim/group/RegisterGroup.java
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.group; import com.google.common.collect.ImmutableList; import com.intellij.codeInsight.editorActions.CopyPastePostProcessor; import com.intellij.codeInsight.editorActions.CopyPastePreProcessor; import com.intellij.codeInsight.editorActions.TextBlockTransferable; import com.intellij.codeInsight.editorActions.TextBlockTransferableData; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.CaretStateTransferableData; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainNextAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainPreviousAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryFwdAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryRevAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphNextAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphPreviousAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentenceNextStartAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentencePreviousStartAction; import com.maddyhome.idea.vim.action.motion.updown.MotionPercentOrMatchAction; import com.maddyhome.idea.vim.command.Argument; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.command.SelectionType; import com.maddyhome.idea.vim.common.Register; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.handler.EditorActionHandlerBase; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.StringHelper; import com.maddyhome.idea.vim.option.ListOption; import com.maddyhome.idea.vim.option.OptionsManager; import com.maddyhome.idea.vim.ui.ClipboardHandler; import kotlin.Pair; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * This group works with command associated with copying and pasting text */ public class RegisterGroup { private static final String WRITABLE_REGISTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-*+_/\""; private static final String READONLY_REGISTERS = ":.%#=/"; private static final String RECORDABLE_REGISTER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String PLAYBACK_REGISTER = RECORDABLE_REGISTER + "\".*+"; private static final String VALID_REGISTERS = WRITABLE_REGISTERS + READONLY_REGISTERS; private static final List<Character> CLIPBOARD_REGISTERS = ImmutableList.of('*', '+'); private static final Logger logger = Logger.getInstance(RegisterGroup.class.getName()); private char defaultRegister = '"'; private char lastRegister = defaultRegister; @NotNull private final HashMap<Character, Register> registers = new HashMap<>(); private char recordRegister = 0; @Nullable private List<KeyStroke> recordList = null; public RegisterGroup() { final ListOption clipboardOption = OptionsManager.INSTANCE.getClipboard(); if (clipboardOption != null) { clipboardOption.addOptionChangeListener(event -> { if (clipboardOption.contains("unnamed")) { defaultRegister = '*'; } else if (clipboardOption.contains("unnamedplus")) { defaultRegister = '+'; } else { defaultRegister = '"'; } lastRegister = defaultRegister; }); } } /** * Check to see if the last selected register can be written to. */ private boolean isRegisterWritable() { return READONLY_REGISTERS.indexOf(lastRegister) < 0; } /** * Store which register the user wishes to work with. * * @param reg The register name * @return true if a valid register name, false if not */ public boolean selectRegister(char reg) { if (VALID_REGISTERS.indexOf(reg) != -1) { lastRegister = reg; if (logger.isDebugEnabled()) logger.debug("register selected: " + lastRegister); return true; } else { return false; } } /** * Reset the selected register back to the default register. */ public void resetRegister() { lastRegister = defaultRegister; logger.debug("Last register reset to default register"); } public void resetRegisters() { registers.clear(); } /** * Store text into the last register. * * @param editor The editor to get the text from * @param range The range of the text to store * @param type The type of copy * @param isDelete is from a delete * @return true if able to store the text into the register, false if not */ public boolean storeText(@NotNull Editor editor, @NotNull TextRange range, @NotNull SelectionType type, boolean isDelete) { if (isRegisterWritable()) { String text = EditorHelper.getText(editor, range); return storeTextInternal(editor, range, text, type, lastRegister, isDelete); } return false; } public boolean storeTextInternal(@NotNull Editor editor, @NotNull TextRange range, @NotNull String text, @NotNull SelectionType type, char register, boolean isDelete) { // Null register doesn't get saved if (lastRegister == '_') return true; int start = range.getStartOffset(); int end = range.getEndOffset(); // Normalize the start and end if (start > end) { int t = start; start = end; end = t; } // If this is an uppercase register, we need to append the text to the corresponding lowercase register final List<TextBlockTransferableData> transferableData = start != -1 ? getTransferableData(editor, range, text) : new ArrayList<>(); final String processedText = start != -1 ? preprocessText(editor, range, text, transferableData) : text; if (logger.isDebugEnabled()) { final String transferableClasses = transferableData.stream().map(it -> it.getClass().getName()).collect(Collectors.joining(",")); logger.debug("Copy to '" + lastRegister + "' with transferable data: " + transferableClasses); } if (Character.isUpperCase(register)) { char lreg = Character.toLowerCase(register); Register r = registers.get(lreg); // Append the text if the lowercase register existed if (r != null) { r.addTextAndResetTransferableData(processedText); } // Set the text if the lowercase register didn't exist yet else { registers.put(lreg, new Register(lreg, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } } // Put the text in the specified register else { registers.put(register, new Register(register, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } if (CLIPBOARD_REGISTERS.contains(register)) { ClipboardHandler.setClipboardText(processedText, new ArrayList<>(transferableData), text); } // Also add it to the default register if the default wasn't specified if (register != defaultRegister && ".:/".indexOf(register) == -1) { registers.put(defaultRegister, new Register(defaultRegister, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } if (isDelete) { boolean smallInlineDeletion = type == SelectionType.CHARACTER_WISE && editor.offsetToLogicalPosition(start).line == editor.offsetToLogicalPosition(end).line; // Deletes go into numbered registers only if text is smaller than a line, register is used or it's a special case if (!smallInlineDeletion || register != defaultRegister || isSmallDeletionSpecialCase(editor)) { // Old 1 goes to 2, etc. Old 8 to 9, old 9 is lost for (char d = '8'; d >= '1'; d--) { Register t = registers.get(d); if (t != null) { t.rename((char)(d + 1)); registers.put((char)(d + 1), t); } } registers.put('1', new Register('1', type, processedText, new ArrayList<>(transferableData))); } // Deletes smaller than one line and without specified register go the the "-" register if (smallInlineDeletion && register == defaultRegister) { registers.put('-', new Register('-', type, processedText, new ArrayList<>(transferableData))); } } // Yanks also go to register 0 if the default register was used else if (register == defaultRegister) { registers.put('0', new Register('0', type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + '0' + "' contains: \"" + processedText + "\""); } if (start != -1) { VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, Math.max(end - 1, 0))); } return true; } @NotNull public List<TextBlockTransferableData> getTransferableData(@NotNull Editor editor, @NotNull TextRange textRange, String text) { final List<TextBlockTransferableData> transferableDatas = new ArrayList<>(); final Project project = editor.getProject(); if (project == null) return new ArrayList<>(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return new ArrayList<>(); DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : CopyPastePostProcessor.EP_NAME .getExtensionList()) { try { transferableDatas.addAll(processor.collectTransferableData(file, editor, textRange.getStartOffsets(), textRange.getEndOffsets())); } catch (IndexNotReadyException ignore) { } } }); transferableDatas.add(new CaretStateTransferableData(new int[]{0}, new int[]{text.length()})); return transferableDatas; } private String preprocessText(@NotNull Editor editor, @NotNull TextRange textRange, String text, List<TextBlockTransferableData> transferableDatas) { final Project project = editor.getProject(); if (project == null) return text; final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return text; String rawText = TextBlockTransferable.convertLineSeparators(text, "\n", transferableDatas); String escapedText; for (CopyPastePreProcessor processor : CopyPastePreProcessor.EP_NAME.getExtensionList()) { escapedText = processor.preprocessOnCopy(file, textRange.getStartOffsets(), textRange.getEndOffsets(), rawText); if (escapedText != null) { return escapedText; } } return text; } private boolean isSmallDeletionSpecialCase(Editor editor) { Command currentCommand = CommandState.getInstance(editor).getCommand(); if (currentCommand != null) { Argument argument = currentCommand.getArgument(); if (argument != null) { Command motionCommand = argument.getMotion(); if (motionCommand != null) { EditorActionHandlerBase action = motionCommand.getAction(); return action instanceof MotionPercentOrMatchAction || action instanceof MotionSentencePreviousStartAction || action instanceof MotionSentenceNextStartAction || action instanceof MotionGotoFileMarkAction || action instanceof SearchEntryFwdAction || action instanceof SearchEntryRevAction || action instanceof SearchAgainNextAction || action instanceof SearchAgainPreviousAction || action instanceof MotionParagraphNextAction || action instanceof MotionParagraphPreviousAction; } } } return false; } /** * Get the last register selected by the user * * @return The register, null if no such register */ @Nullable public Register getLastRegister() { return getRegister(lastRegister); } @Nullable public Register getPlaybackRegister(char r) { if (PLAYBACK_REGISTER.indexOf(r) != 0) { return getRegister(r); } else { return null; } } @Nullable public Register getRegister(char r) { // Uppercase registers actually get the lowercase register if (Character.isUpperCase(r)) { r = Character.toLowerCase(r); } return CLIPBOARD_REGISTERS.contains(r) ? refreshClipboardRegister(r) : registers.get(r); } /** * Gets the last register name selected by the user * * @return The register name */ public char getCurrentRegister() { return lastRegister; } /** * The register key for the default register. */ public char getDefaultRegister() { return defaultRegister; } @NotNull public List<Register> getRegisters() { final List<Register> res = new ArrayList<>(registers.values()); for (Character r : CLIPBOARD_REGISTERS) { final Register register = refreshClipboardRegister(r); if (register != null) { res.add(register); } } res.sort(new Register.KeySorter()); return res; } public boolean startRecording(Editor editor, char register) { if (RECORDABLE_REGISTER.indexOf(register) != -1) { CommandState.getInstance(editor).setRecording(true); recordRegister = register; recordList = new ArrayList<>(); return true; } else { return false; } } public void recordKeyStroke(KeyStroke key) { if (recordRegister != 0 && recordList != null) { recordList.add(key); } } public void recordText(@NotNull String text) { if (recordRegister != 0 && recordList != null) { recordList.addAll(StringHelper.stringToKeys(text)); } } public void setKeys(char register, @NotNull List<KeyStroke> keys) { registers.put(register, new Register(register, SelectionType.CHARACTER_WISE, keys)); } public void finishRecording(Editor editor) { if (recordRegister != 0) { Register reg = null; if (Character.isUpperCase(recordRegister)) { reg = getRegister(recordRegister); } if (recordList != null) { if (reg == null) { reg = new Register(Character.toLowerCase(recordRegister), SelectionType.CHARACTER_WISE, recordList); registers.put(Character.toLowerCase(recordRegister), reg); } else { reg.addKeys(recordList); } } CommandState.getInstance(editor).setRecording(false); } recordRegister = 0; } public void saveData(@NotNull final Element element) { logger.debug("saveData"); final Element registersElement = new Element("registers"); for (Character key : registers.keySet()) { final Register register = registers.get(key); final Element registerElement = new Element("register"); registerElement.setAttribute("name", String.valueOf(key)); registerElement.setAttribute("type", Integer.toString(register.getType().getValue())); final String text = register.getText(); if (text != null) { final Element textElement = new Element("text"); StringHelper.setSafeXmlText(textElement, text); registerElement.addContent(textElement); } else { final Element keys = new Element("keys"); final List<KeyStroke> list = register.getKeys(); for (KeyStroke stroke : list) { final Element k = new Element("key"); k.setAttribute("char", Integer.toString(stroke.getKeyChar())); k.setAttribute("code", Integer.toString(stroke.getKeyCode())); k.setAttribute("mods", Integer.toString(stroke.getModifiers())); keys.addContent(k); } registerElement.addContent(keys); } registersElement.addContent(registerElement); } element.addContent(registersElement); } public void readData(@NotNull final Element element) { logger.debug("readData"); final Element registersElement = element.getChild("registers"); if (registersElement != null) { final List<Element> registerElements = registersElement.getChildren("register"); for (Element registerElement : registerElements) { final char key = registerElement.getAttributeValue("name").charAt(0); final Register register; final Element textElement = registerElement.getChild("text"); final String typeText = registerElement.getAttributeValue("type"); final SelectionType type = SelectionType.fromValue(Integer.parseInt(typeText)); if (textElement != null) { final String text = StringHelper.getSafeXmlText(textElement); if (text != null) { register = new Register(key, type, text, Collections.emptyList()); } else { register = null; } } else { final Element keysElement = registerElement.getChild("keys"); final List<Element> keyElements = keysElement.getChildren("key"); final List<KeyStroke> strokes = new ArrayList<>(); for (Element keyElement : keyElements) { final int code = Integer.parseInt(keyElement.getAttributeValue("code")); final int modifiers = Integer.parseInt(keyElement.getAttributeValue("mods")); final char c = (char)Integer.parseInt(keyElement.getAttributeValue("char")); //noinspection MagicConstant strokes.add(c == KeyEvent.CHAR_UNDEFINED ? KeyStroke.getKeyStroke(code, modifiers) : KeyStroke.getKeyStroke(c)); } register = new Register(key, type, strokes); } registers.put(key, register); } } } @Nullable private Register refreshClipboardRegister(char r) { final Pair<String, List<TextBlockTransferableData>> clipboardData = ClipboardHandler.getClipboardTextAndTransferableData(); final Register currentRegister = registers.get(r); final String text = clipboardData.getFirst(); final List<TextBlockTransferableData> transferableData = clipboardData.getSecond(); if (text != null) { if (currentRegister != null && text.equals(currentRegister.getText())) { return currentRegister; } return new Register(r, guessSelectionType(text), text, transferableData); } return null; } @NotNull private SelectionType guessSelectionType(@NotNull String text) { if (text.endsWith("\n")) { return SelectionType.LINE_WISE; } else { return SelectionType.CHARACTER_WISE; } } }
[VIM-1785][VIM-1731] Fix yanking to clipboard
src/com/maddyhome/idea/vim/group/RegisterGroup.java
[VIM-1785][VIM-1731] Fix yanking to clipboard
<ide><path>rc/com/maddyhome/idea/vim/group/RegisterGroup.java <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.editor.CaretStateTransferableData; <ide> import com.intellij.openapi.editor.Editor; <add>import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData; <add>import com.intellij.openapi.editor.richcopy.view.RtfTransferableData; <ide> import com.intellij.openapi.project.DumbService; <ide> import com.intellij.openapi.project.IndexNotReadyException; <ide> import com.intellij.openapi.project.Project; <ide> } <ide> }); <ide> transferableDatas.add(new CaretStateTransferableData(new int[]{0}, new int[]{text.length()})); <add> <add> // These data provided by {@link com.intellij.openapi.editor.richcopy.TextWithMarkupProcessor} doesn't work with <add> // IdeaVim and I don't see a way to fix it <add> // See https://youtrack.jetbrains.com/issue/VIM-1785 <add> // See https://youtrack.jetbrains.com/issue/VIM-1731 <add> transferableDatas.removeIf(it -> (it instanceof RtfTransferableData) || (it instanceof HtmlTransferableData)); <ide> return transferableDatas; <ide> } <ide>
Java
apache-2.0
c7a33bd658c00f11459bbc7b632053e7999f9c93
0
Valkryst/VTerminal
package com.valkryst.VTerminal; import com.valkryst.VTerminal.misc.IntRange; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.awt.Color; import java.util.Arrays; public class AsciiStringTest { private final String testString = "ABCDEFGHJIKLMNOP"; private AsciiString string; @Before public void initializeString() { string = new AsciiString(testString); string.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); } @Test public void testConstructor_lengthConstructor() { for (int i = 0 ; i < 10 ; i++) { final AsciiString string = new AsciiString(i); // Ensure that the correct number of characters are initialized: Assert.assertEquals(i, string.getCharacters().length); // Ensure all characters are initialized properly: for (final AsciiCharacter character: string.getCharacters()) { Assert.assertEquals(' ', character.getCharacter()); } // Ensure that no two characters are initialized as the same object: for (int a = 0 ; a < i ; a++) { for (int b = a + 1 ; b < i ; b++) { final AsciiCharacter charA = string.getCharacters()[a]; final AsciiCharacter charB = string.getCharacters()[b]; // Using == compares object references: Assert.assertFalse(charA == charB); } } } } @Test public void testConstructor_lengthConstructor_withNegativeLength() { final AsciiString string = new AsciiString(-1); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testConstructor_stringConstructor() { for (int i = 0 ; i < 10 ; i++) { final AsciiString string = new AsciiString(testString.substring(0, i)); // Ensure that the correct number of characters are initialized: Assert.assertEquals(i, string.getCharacters().length); // Ensure all characters are initialized properly: for (int a = 0 ; a < string.getCharacters().length ; a++) { final char expected = testString.charAt(a); final char actual = string.getCharacters()[a].getCharacter(); Assert.assertEquals(expected, actual); } // Ensure that no two characters are initialized as the same object: for (int a = 0 ; a < i ; a++) { for (int b = a + 1 ; b < i ; b++) { final AsciiCharacter charA = string.getCharacters()[a]; final AsciiCharacter charB = string.getCharacters()[b]; // Using == compares object references: Assert.assertFalse(charA == charB); } } } } @Test public void testConstructor_stringConstructor_withEmptyString() { final AsciiString string = new AsciiString(""); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testConstructor_stringConstructor_withNullString() { final AsciiString string = new AsciiString(null); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testToString() { final String actual_toString = string.toString(); final String expected_toString = testString; Assert.assertEquals(expected_toString, actual_toString); } @Test public void testDetailedToString() { Assert.assertTrue(string.detailedToString().length() > 0); } @Test public void testEquals_withSelf() { Assert.assertEquals(string, string); } @Test public void testEquals_withEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); Assert.assertEquals(stringA, stringB); } @Test public void testEquals_withNonEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString("Xfgcgfytf"); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); Assert.assertNotEquals(stringA, stringB); } @Test public void testEquals_withNonAsciiStringObject() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final Integer integer = 666; Assert.assertNotEquals(stringA, integer); } @Test public void testEquals_withNonEqualBackgroundColors() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.RED); Assert.assertNotEquals(stringA, stringB); } @Test public void testEquals_withNonEqualForegroundColors() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.RED, Color.WHITE); Assert.assertNotEquals(stringA, stringB); } // todo Fix issue with the equals function. /* @Test public void testHashCode_withEqualStrings() { final AsciiString stringA = new AsciiString("A"); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString("A"); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); System.out.println(stringA.detailedToString()); System.out.println(stringB.detailedToString()); Assert.assertEquals(stringA.hashCode(), stringB.hashCode()); } */ @Test public void testHashCode_withNonEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.RED, Color.WHITE); Assert.assertNotEquals(stringA.hashCode(), stringB.hashCode()); } @Test public void testIsRangeValid() { final AsciiString string = new AsciiString(testString); for (int i = 0 ; i < string.getCharacters().length ; i++) { final IntRange range = new IntRange(0, i); Assert.assertTrue(string.isRangeValid(range)); } } @Test public void testIsRangeValid_withNegativeBegin() { final IntRange range = new IntRange(-1, 3); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withNegativeEnd() { final IntRange range = new IntRange(0, -3); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withBeginAndEndEqual() { final IntRange range = new IntRange(0, 0); Assert.assertTrue(string.isRangeValid(range)); } @Test public void testIsRangeValid_withEndLargerThanStringLength() { final IntRange range = new IntRange(0, string.getCharacters().length + 1); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withNullRange() { Assert.assertFalse(string.isRangeValid(null)); } @Test public void testSetAllCharactersToBeRedrawn() { Arrays.fill(string.getCharactersToBeRedrawn(), false); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } string.setAllCharactersToBeRedrawn(); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertTrue(val); } } @Test public void testSetCharacterRangeToBeRedrawn_withNullRange() { Arrays.fill(string.getCharactersToBeRedrawn(), false); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } string.setCharacterRangeToBeRedrawn(null); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } } @Test public void testSetCharacterRangeToBeRedrawn_withInvalidRange() { Arrays.fill(string.getCharactersToBeRedrawn(), false); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } final IntRange range = new IntRange(-1, string.getCharacters().length); string.setCharacterRangeToBeRedrawn(range); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } } @Test public void testSetCharacterRangeToBeRedrawn_withValidRange() { Arrays.fill(string.getCharactersToBeRedrawn(), false); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertFalse(val); } final IntRange range = new IntRange(0, string.getCharacters().length); string.setCharacterRangeToBeRedrawn(range); for (final boolean val : string.getCharactersToBeRedrawn()) { Assert.assertTrue(val); } } @Test public void testSetCharacter_objectChar() { final AsciiCharacter newChar = new AsciiCharacter('Z'); string.setCharacter(0, newChar); // Using == compares object references: Assert.assertTrue(newChar == string.getCharacters()[0]); } @Test public void testSetCharacter_objectChar_withNegativeColumnIndex() { string.setCharacter(-1, new AsciiCharacter('Z')); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_objectChar_withColumnIndexLargerThanStringLength() { string.setCharacter(string.getCharacters().length + 1, new AsciiCharacter('Z')); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_objectChar_withNullCharacter() { string.setCharacter(0, null); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar() { string.setCharacter(0, 'Z'); Assert.assertEquals('Z', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar_withNegativeColumnIndex() { string.setCharacter(-1, 'Z'); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar_withColumnIndexLargerThanStringLength() { string.setCharacter(string.getCharacters().length + 1, 'Z'); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacters() { for (int i = 0 ; i < string.getCharacters().length ; i++) { string = new AsciiString(testString); final IntRange range = new IntRange(0, i); string.setCharacters('Z', range); // Ensure that all characters in the range are set to 'Z' and that // all other characters were unchanged. for (int j = 0 ; j < string.getCharacters().length ; j++) { if (j < i) { Assert.assertEquals('Z', string.getCharacters()[j].getCharacter()); } else { Assert.assertNotEquals('Z', string.getCharacters()[j].getCharacter()); } } } } @Test public void testSetCharacters_withNullRange() { string.setCharacters('Z', null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals('Z', character.getCharacter()); } } @Test public void testSetCharacters_withInvalidRange() { string.setCharacters('Z', new IntRange(-1, string.getCharacters().length)); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals('Z', character.getCharacter()); } } @Test public void testSetAllCharacters() { string.setAllCharacters('Z'); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals('Z', character.getCharacter()); } } @Test public void testApplyColorGradient_toBackgroundOfAllCharacters() { string.applyColorGradient(Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toForegroundOfAllCharacters() { string.applyColorGradient(Color.RED, Color.BLUE, false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertNotEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toBackgroundOfRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toForegroundOfRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertNotEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toRange_withNullRange() { string.applyColorGradient(null, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test(expected=IllegalArgumentException.class) public void testApplyColorGradient_toRange_withNullColorFrom() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, null, Color.BLUE, true); } @Test(expected=IllegalArgumentException.class) public void testApplyColorGradient_toRange_withNullColorTo() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, null, true); } @Test public void testInvertColors_toAllCharacters() { string.invertColors(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testInvertColors_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.invertColors(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testInvertColors_toRange_withNullRange() { string.invertColors(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testInvertColors_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.invertColors(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toAllCharacters() { string.setBackgroundColor(Color.RED); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toAllCharacters() { string.setForegroundColor(Color.RED); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toAllCharacters() { string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withNullColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withNullRange() { string.setBackgroundColor(Color.RED, null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.setBackgroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withNullColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullBackgroundColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(null, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullForegroundColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullRange() { string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetHidden_toAllCharacters_toHidden() { string.setHidden(true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isHidden()); } } @Test public void testSetHidden_toAllCharacters_toNotHidden() { string.setHidden(false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isHidden()); } } @Test public void testFlipCharactersHorizontally_toAllCharacters() { string.flipCharactersHorizontally(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toAllCharacters() { string.flipCharactersHorizontally(); string.unFlipCharactersHorizontally(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersVertically_toAllCharacters() { string.flipCharactersVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toAllCharacters() { string.flipCharactersVertically(); string.unFlipCharactersVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toAllCharacters() { string.flipCharactersHorizontallyAndVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toAllCharacters() { string.flipCharactersHorizontallyAndVertically(); string.unFlipCharactersHorizontallyAndVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontally_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersHorizontally_toRange_withNullRange() { string.flipCharactersHorizontally(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersHorizontally_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testFlipCharactersVertically_toRange_withNullRange() { string.flipCharactersVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange_withNullRange() { string.flipCharactersHorizontallyAndVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnderLineCharacters_toAllCharacters() { string.underlineCharacters(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toAllCharacters() { string.underlineCharacters(); string.unUnderlineCharacters(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange_withNullRange() { string.underlineCharacters(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.underlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } }
test/com/valkryst/VTerminal/AsciiStringTest.java
package com.valkryst.VTerminal; import com.valkryst.VTerminal.misc.IntRange; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.awt.*; public class AsciiStringTest { private final String testString = "ABCDEFGHJIKLMNOP"; private AsciiString string; @Before public void initializeString() { string = new AsciiString(testString); string.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); } @Test public void testConstructor_lengthConstructor() { for (int i = 0 ; i < 10 ; i++) { final AsciiString string = new AsciiString(i); // Ensure that the correct number of characters are initialized: Assert.assertEquals(i, string.getCharacters().length); // Ensure all characters are initialized properly: for (final AsciiCharacter character: string.getCharacters()) { Assert.assertEquals(' ', character.getCharacter()); } // Ensure that no two characters are initialized as the same object: for (int a = 0 ; a < i ; a++) { for (int b = a + 1 ; b < i ; b++) { final AsciiCharacter charA = string.getCharacters()[a]; final AsciiCharacter charB = string.getCharacters()[b]; // Using == compares object references: Assert.assertFalse(charA == charB); } } } } @Test public void testConstructor_lengthConstructor_withNegativeLength() { final AsciiString string = new AsciiString(-1); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testConstructor_stringConstructor() { for (int i = 0 ; i < 10 ; i++) { final AsciiString string = new AsciiString(testString.substring(0, i)); // Ensure that the correct number of characters are initialized: Assert.assertEquals(i, string.getCharacters().length); // Ensure all characters are initialized properly: for (int a = 0 ; a < string.getCharacters().length ; a++) { final char expected = testString.charAt(a); final char actual = string.getCharacters()[a].getCharacter(); Assert.assertEquals(expected, actual); } // Ensure that no two characters are initialized as the same object: for (int a = 0 ; a < i ; a++) { for (int b = a + 1 ; b < i ; b++) { final AsciiCharacter charA = string.getCharacters()[a]; final AsciiCharacter charB = string.getCharacters()[b]; // Using == compares object references: Assert.assertFalse(charA == charB); } } } } @Test public void testConstructor_stringConstructor_withEmptyString() { final AsciiString string = new AsciiString(""); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testConstructor_stringConstructor_withNullString() { final AsciiString string = new AsciiString(null); Assert.assertEquals(0, string.getCharacters().length); } @Test public void testToString() { final String actual_toString = string.toString(); final String expected_toString = testString; Assert.assertEquals(expected_toString, actual_toString); } @Test public void testDetailedToString() { Assert.assertTrue(string.detailedToString().length() > 0); } @Test public void testEquals_withSelf() { Assert.assertEquals(string, string); } @Test public void testEquals_withEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); Assert.assertEquals(stringA, stringB); } @Test public void testEquals_withNonEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString("Xfgcgfytf"); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); Assert.assertNotEquals(stringA, stringB); } @Test public void testEquals_withNonAsciiStringObject() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final Integer integer = 666; Assert.assertNotEquals(stringA, integer); } @Test public void testEquals_withNonEqualBackgroundColors() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.RED); Assert.assertNotEquals(stringA, stringB); } @Test public void testEquals_withNonEqualForegroundColors() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.RED, Color.WHITE); Assert.assertNotEquals(stringA, stringB); } // todo Fix issue with the equals function. /* @Test public void testHashCode_withEqualStrings() { final AsciiString stringA = new AsciiString("A"); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString("A"); stringB.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); System.out.println(stringA.detailedToString()); System.out.println(stringB.detailedToString()); Assert.assertEquals(stringA.hashCode(), stringB.hashCode()); } */ @Test public void testHashCode_withNonEqualStrings() { final AsciiString stringA = new AsciiString(testString); stringA.setBackgroundAndForegroundColor(Color.BLACK, Color.WHITE); final AsciiString stringB = new AsciiString(testString); stringB.setBackgroundAndForegroundColor(Color.RED, Color.WHITE); Assert.assertNotEquals(stringA.hashCode(), stringB.hashCode()); } @Test public void testIsRangeValid() { final AsciiString string = new AsciiString(testString); for (int i = 0 ; i < string.getCharacters().length ; i++) { final IntRange range = new IntRange(0, i); Assert.assertTrue(string.isRangeValid(range)); } } @Test public void testIsRangeValid_withNegativeBegin() { final IntRange range = new IntRange(-1, 3); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withNegativeEnd() { final IntRange range = new IntRange(0, -3); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withBeginAndEndEqual() { final IntRange range = new IntRange(0, 0); Assert.assertTrue(string.isRangeValid(range)); } @Test public void testIsRangeValid_withEndLargerThanStringLength() { final IntRange range = new IntRange(0, string.getCharacters().length + 1); Assert.assertFalse(string.isRangeValid(range)); } @Test public void testIsRangeValid_withNullRange() { Assert.assertFalse(string.isRangeValid(null)); } @Test public void testSetCharacter_objectChar() { final AsciiCharacter newChar = new AsciiCharacter('Z'); string.setCharacter(0, newChar); // Using == compares object references: Assert.assertTrue(newChar == string.getCharacters()[0]); } @Test public void testSetCharacter_objectChar_withNegativeColumnIndex() { string.setCharacter(-1, new AsciiCharacter('Z')); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_objectChar_withColumnIndexLargerThanStringLength() { string.setCharacter(string.getCharacters().length + 1, new AsciiCharacter('Z')); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_objectChar_withNullCharacter() { string.setCharacter(0, null); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar() { string.setCharacter(0, 'Z'); Assert.assertEquals('Z', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar_withNegativeColumnIndex() { string.setCharacter(-1, 'Z'); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacter_primitiveChar_withColumnIndexLargerThanStringLength() { string.setCharacter(string.getCharacters().length + 1, 'Z'); Assert.assertEquals('A', string.getCharacters()[0].getCharacter()); } @Test public void testSetCharacters() { for (int i = 0 ; i < string.getCharacters().length ; i++) { string = new AsciiString(testString); final IntRange range = new IntRange(0, i); string.setCharacters('Z', range); // Ensure that all characters in the range are set to 'Z' and that // all other characters were unchanged. for (int j = 0 ; j < string.getCharacters().length ; j++) { if (j < i) { Assert.assertEquals('Z', string.getCharacters()[j].getCharacter()); } else { Assert.assertNotEquals('Z', string.getCharacters()[j].getCharacter()); } } } } @Test public void testSetCharacters_withNullRange() { string.setCharacters('Z', null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals('Z', character.getCharacter()); } } @Test public void testSetCharacters_withInvalidRange() { string.setCharacters('Z', new IntRange(-1, string.getCharacters().length)); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals('Z', character.getCharacter()); } } @Test public void testSetAllCharacters() { string.setAllCharacters('Z'); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals('Z', character.getCharacter()); } } @Test public void testApplyColorGradient_toBackgroundOfAllCharacters() { string.applyColorGradient(Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toForegroundOfAllCharacters() { string.applyColorGradient(Color.RED, Color.BLUE, false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertNotEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toBackgroundOfRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toForegroundOfRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertNotEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toRange_withNullRange() { string.applyColorGradient(null, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testApplyColorGradient_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.applyColorGradient(range, Color.RED, Color.BLUE, true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertNotEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test(expected=IllegalArgumentException.class) public void testApplyColorGradient_toRange_withNullColorFrom() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, null, Color.BLUE, true); } @Test(expected=IllegalArgumentException.class) public void testApplyColorGradient_toRange_withNullColorTo() { final IntRange range = new IntRange(0, string.getCharacters().length); string.applyColorGradient(range, Color.RED, null, true); } @Test public void testInvertColors_toAllCharacters() { string.invertColors(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testInvertColors_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.invertColors(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testInvertColors_toRange_withNullRange() { string.invertColors(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testInvertColors_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.invertColors(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.WHITE, character.getBackgroundColor()); Assert.assertEquals(Color.BLACK, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toAllCharacters() { string.setBackgroundColor(Color.RED); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toAllCharacters() { string.setForegroundColor(Color.RED); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toAllCharacters() { string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withNullColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withNullRange() { string.setBackgroundColor(Color.RED, null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.setBackgroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withNullColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetForegroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setForegroundColor(Color.RED, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.RED, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullBackgroundColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(null, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullForegroundColor() { final IntRange range = new IntRange(0, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, null, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withNullRange() { string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.BLACK, character.getBackgroundColor()); Assert.assertEquals(Color.WHITE, character.getForegroundColor()); } } @Test public void testSetBackgroundAndForegroundColor_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.setBackgroundAndForegroundColor(Color.RED, Color.BLUE, range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertEquals(Color.RED, character.getBackgroundColor()); Assert.assertEquals(Color.BLUE, character.getForegroundColor()); } } @Test public void testSetHidden_toAllCharacters_toHidden() { string.setHidden(true); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isHidden()); } } @Test public void testSetHidden_toAllCharacters_toNotHidden() { string.setHidden(false); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isHidden()); } } @Test public void testFlipCharactersHorizontally_toAllCharacters() { string.flipCharactersHorizontally(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toAllCharacters() { string.flipCharactersHorizontally(); string.unFlipCharactersHorizontally(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersVertically_toAllCharacters() { string.flipCharactersVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toAllCharacters() { string.flipCharactersVertically(); string.unFlipCharactersVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toAllCharacters() { string.flipCharactersHorizontallyAndVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toAllCharacters() { string.flipCharactersHorizontallyAndVertically(); string.unFlipCharactersHorizontallyAndVertically(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontally_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersHorizontally_toRange_withNullRange() { string.flipCharactersHorizontally(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersHorizontally_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); } } @Test public void testUnFlipCharactersHorizontally_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontally(range); string.unFlipCharactersHorizontally(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); } } @Test public void testFlipCharactersVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testFlipCharactersVertically_toRange_withNullRange() { string.flipCharactersVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersVertically(range); string.unFlipCharactersVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange_withNullRange() { string.flipCharactersHorizontallyAndVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testFlipCharactersHorizontallyAndVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isFlippedHorizontally()); Assert.assertTrue(character.isFlippedVertically()); } } @Test public void testUnFlipCharactersHorizontallyAndVertically_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.flipCharactersHorizontallyAndVertically(range); string.unFlipCharactersHorizontallyAndVertically(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isFlippedHorizontally()); Assert.assertFalse(character.isFlippedVertically()); } } @Test public void testUnderLineCharacters_toAllCharacters() { string.underlineCharacters(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toAllCharacters() { string.underlineCharacters(); string.unUnderlineCharacters(); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange_withNullRange() { string.underlineCharacters(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnderLineCharacters_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.underlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange_withNullRange() { final IntRange range = new IntRange(0, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(null); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertTrue(character.isUnderlined()); } } @Test public void testUnUnderLineCharacters_toRange_withInvalidRange() { final IntRange range = new IntRange(-1, string.getCharacters().length); string.underlineCharacters(range); string.unUnderlineCharacters(range); for (final AsciiCharacter character : string.getCharacters()) { Assert.assertFalse(character.isUnderlined()); } } }
Adds tests for the setAllCharactersToBeRedrawn and setCharacterRangeToBeRedrawn functions.
test/com/valkryst/VTerminal/AsciiStringTest.java
Adds tests for the setAllCharactersToBeRedrawn and setCharacterRangeToBeRedrawn functions.
<ide><path>est/com/valkryst/VTerminal/AsciiStringTest.java <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> <del>import java.awt.*; <add>import java.awt.Color; <add>import java.util.Arrays; <ide> <ide> public class AsciiStringTest { <ide> private final String testString = "ABCDEFGHJIKLMNOP"; <ide> @Test <ide> public void testIsRangeValid_withNullRange() { <ide> Assert.assertFalse(string.isRangeValid(null)); <add> } <add> <add> @Test <add> public void testSetAllCharactersToBeRedrawn() { <add> Arrays.fill(string.getCharactersToBeRedrawn(), false); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> <add> string.setAllCharactersToBeRedrawn(); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertTrue(val); <add> } <add> } <add> <add> @Test <add> public void testSetCharacterRangeToBeRedrawn_withNullRange() { <add> Arrays.fill(string.getCharactersToBeRedrawn(), false); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> <add> string.setCharacterRangeToBeRedrawn(null); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> } <add> <add> @Test <add> public void testSetCharacterRangeToBeRedrawn_withInvalidRange() { <add> Arrays.fill(string.getCharactersToBeRedrawn(), false); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> <add> final IntRange range = new IntRange(-1, string.getCharacters().length); <add> string.setCharacterRangeToBeRedrawn(range); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> } <add> <add> <add> @Test <add> public void testSetCharacterRangeToBeRedrawn_withValidRange() { <add> Arrays.fill(string.getCharactersToBeRedrawn(), false); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertFalse(val); <add> } <add> <add> final IntRange range = new IntRange(0, string.getCharacters().length); <add> string.setCharacterRangeToBeRedrawn(range); <add> <add> for (final boolean val : string.getCharactersToBeRedrawn()) { <add> Assert.assertTrue(val); <add> } <ide> } <ide> <ide> @Test
Java
apache-2.0
ae0a0c6da789b367abbeb5413ac394e600965abb
0
josephcsible/GravityBox
/* * Copyright (C) 2015 Peter Gregus for GravityBox Project (C3C076@xda) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ceco.lollipop.gravitybox; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; public class ModLowBatteryWarning { private static final String TAG = "GB:ModLowBatteryWarning"; public static final String PACKAGE_NAME = "com.android.systemui"; private static final String CLASS_POWER_UI = "com.android.systemui.power.PowerUI"; private static final String CLASS_POWER_WARNINGS = "com.android.systemui.power.PowerNotificationWarnings"; private static final String CLASS_BATTERY_SERVICE_LED = "com.android.server.BatteryService$Led"; public static final boolean DEBUG = false; public static enum ChargingLed { DEFAULT, EMULATED, DISABLED }; private static Object mBatteryLed; private static boolean mFlashingLedDisabled; private static ChargingLed mChargingLed; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } private static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(GravityBoxSettings.ACTION_BATTERY_LED_CHANGED)) { if (intent.hasExtra(GravityBoxSettings.EXTRA_BLED_FLASHING_DISABLED)) { mFlashingLedDisabled = intent.getBooleanExtra( GravityBoxSettings.EXTRA_BLED_FLASHING_DISABLED, false); } if (intent.hasExtra(GravityBoxSettings.EXTRA_BLED_CHARGING)) { mChargingLed = ChargingLed.valueOf(intent.getStringExtra( GravityBoxSettings.EXTRA_BLED_CHARGING)); } updateLightsLocked(); } } }; private static void updateLightsLocked() { if (mBatteryLed == null) return; try { XposedHelpers.callMethod(mBatteryLed, "updateLightsLocked"); } catch (Throwable t) { XposedBridge.log(t); } } public static void initAndroid(final XSharedPreferences prefs, final ClassLoader classLoader) { if (DEBUG) log("initAndroid"); try { final Class<?> batteryServiceClass = XposedHelpers.findClass(CLASS_BATTERY_SERVICE_LED, classLoader); mFlashingLedDisabled = prefs.getBoolean(GravityBoxSettings.PREF_KEY_FLASHING_LED_DISABLE, false); mChargingLed = ChargingLed.valueOf(prefs.getString(GravityBoxSettings.PREF_KEY_CHARGING_LED, "DEFAULT")); XposedBridge.hookAllConstructors(batteryServiceClass, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mBatteryLed = param.thisObject; Context context = (Context) XposedHelpers.getObjectField( XposedHelpers.getSurroundingThis(param.thisObject), "mContext"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(GravityBoxSettings.ACTION_BATTERY_LED_CHANGED); context.registerReceiver(mBroadcastReceiver, intentFilter); } }); XposedHelpers.findAndHookMethod(batteryServiceClass, "updateLightsLocked", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { Object batteryLight = XposedHelpers.getObjectField(param.thisObject, "mBatteryLight"); Object o = XposedHelpers.getSurroundingThis(param.thisObject); Object batteryProps = XposedHelpers.getObjectField(o, "mBatteryProps"); if (DEBUG) { log("BatteryService LED: updateLightsLocked ENTERED"); // for debugging purposes - simulate low battery XposedHelpers.setIntField(batteryProps, "batteryLevel", 10); } final int status = XposedHelpers.getIntField(batteryProps, "batteryStatus"); if (status == BatteryManager.BATTERY_STATUS_CHARGING) { if (mChargingLed == ChargingLed.DISABLED) { if (DEBUG) log("Disabling charging led"); XposedHelpers.callMethod(batteryLight, "turnOff"); param.setResult(null); return; } } else { if (mFlashingLedDisabled) { if (DEBUG) log("Disabling low battery flashing led"); XposedHelpers.callMethod(batteryLight, "turnOff"); param.setResult(null); return; } } } }); } catch (Throwable t) { XposedBridge.log(t); } } // SystemUI package public enum LowBatteryWarningMode { DEFAULT, NONINTRUSIVE, OFF }; static void init(final XSharedPreferences prefs, ClassLoader classLoader) { try { if (DEBUG) log("init"); // for debugging purposes - simulate low battery even if it's not if (DEBUG) { Class<?> classPowerUI = findClass(CLASS_POWER_UI, classLoader); findAndHookMethod(classPowerUI, "findBatteryLevelBucket", int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { param.setResult(-1); } }); } Class<?> classPowerWarnings = findClass(CLASS_POWER_WARNINGS, classLoader); findAndHookMethod(classPowerWarnings, "updateNotification", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { prefs.reload(); LowBatteryWarningMode mode = LowBatteryWarningMode.valueOf( prefs.getString(GravityBoxSettings.PREF_KEY_LOW_BATTERY_WARNING_POLICY, "DEFAULT")); if (DEBUG) log("showLowBatteryWarning called; mode = " + mode); switch (mode) { case DEFAULT: return; case NONINTRUSIVE: XposedHelpers.setBooleanField(param.thisObject, "mPlaySound", false); return; case OFF: XposedHelpers.setBooleanField(param.thisObject, "mWarning", false); return; } } }); } catch (Throwable t) { XposedBridge.log(t); } } }
src/com/ceco/lollipop/gravitybox/ModLowBatteryWarning.java
/* * Copyright (C) 2015 Peter Gregus for GravityBox Project (C3C076@xda) * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ceco.lollipop.gravitybox; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; public class ModLowBatteryWarning { private static final String TAG = "GB:ModLowBatteryWarning"; public static final String PACKAGE_NAME = "com.android.systemui"; private static final String CLASS_POWER_UI = "com.android.systemui.power.PowerUI"; private static final String CLASS_POWER_WARNINGS = "com.android.systemui.power.PowerNotificationWarnings"; private static final String CLASS_BATTERY_SERVICE_LED = "com.android.server.BatteryService$Led"; public static final boolean DEBUG = false; public static enum ChargingLed { DEFAULT, EMULATED, DISABLED }; private static Object mBatteryLed; private static boolean mFlashingLedDisabled; private static ChargingLed mChargingLed; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } private static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(GravityBoxSettings.ACTION_BATTERY_LED_CHANGED)) { if (intent.hasExtra(GravityBoxSettings.EXTRA_BLED_FLASHING_DISABLED)) { mFlashingLedDisabled = intent.getBooleanExtra( GravityBoxSettings.EXTRA_BLED_FLASHING_DISABLED, false); } if (intent.hasExtra(GravityBoxSettings.EXTRA_BLED_CHARGING)) { mChargingLed = ChargingLed.valueOf(intent.getStringExtra( GravityBoxSettings.EXTRA_BLED_CHARGING)); } updateLightsLocked(); } } }; private static void updateLightsLocked() { if (mBatteryLed == null) return; try { XposedHelpers.callMethod(mBatteryLed, "updateLightsLocked"); } catch (Throwable t) { XposedBridge.log(t); } } public static void initAndroid(final XSharedPreferences prefs, final ClassLoader classLoader) { if (DEBUG) log("initAndroid"); try { final Class<?> batteryServiceClass = XposedHelpers.findClass(CLASS_BATTERY_SERVICE_LED, classLoader); mFlashingLedDisabled = prefs.getBoolean(GravityBoxSettings.PREF_KEY_FLASHING_LED_DISABLE, false); mChargingLed = ChargingLed.valueOf(prefs.getString(GravityBoxSettings.PREF_KEY_CHARGING_LED, "DEFAULT")); XposedBridge.hookAllConstructors(batteryServiceClass, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mBatteryLed = param.thisObject; Context context = (Context) XposedHelpers.getObjectField( XposedHelpers.getSurroundingThis(param.thisObject), "mContext"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(GravityBoxSettings.ACTION_BATTERY_LED_CHANGED); context.registerReceiver(mBroadcastReceiver, intentFilter); } }); XposedHelpers.findAndHookMethod(batteryServiceClass, "updateLightsLocked", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { Object batteryLight = XposedHelpers.getObjectField(param.thisObject, "mBatteryLight"); Object o = XposedHelpers.getSurroundingThis(param.thisObject); Object batteryProps = XposedHelpers.getObjectField(o, "mBatteryProps"); if (DEBUG) { log("BatteryService LED: updateLightsLocked ENTERED"); // for debugging purposes - simulate low battery XposedHelpers.setIntField(batteryProps, "batteryLevel", 10); } final int status = XposedHelpers.getIntField(batteryProps, "batteryStatus"); if (status == BatteryManager.BATTERY_STATUS_CHARGING) { if (mChargingLed == ChargingLed.DISABLED) { if (DEBUG) log("Disabling charging led"); XposedHelpers.callMethod(batteryLight, "turnOff"); param.setResult(null); return; } } else { if (mFlashingLedDisabled) { if (DEBUG) log("Disabling low battery flashing led"); XposedHelpers.callMethod(batteryLight, "turnOff"); param.setResult(null); return; } } } }); } catch (Throwable t) { XposedBridge.log(t); } } // SystemUI package public enum LowBatteryWarningMode { DEFAULT, NONINTRUSIVE, OFF }; static void init(final XSharedPreferences prefs, ClassLoader classLoader) { try { if (DEBUG) log("init"); // for debugging purposes - simulate low battery even if it's not if (DEBUG) { Class<?> classPowerUI = findClass(CLASS_POWER_UI, classLoader); findAndHookMethod(classPowerUI, "findBatteryLevelBucket", int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { param.setResult(-1); } }); } Class<?> classPowerWarnings = findClass(CLASS_POWER_WARNINGS, classLoader); findAndHookMethod(classPowerWarnings, "showLowBatteryWarning", boolean.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { prefs.reload(); LowBatteryWarningMode mode = LowBatteryWarningMode.valueOf( prefs.getString(GravityBoxSettings.PREF_KEY_LOW_BATTERY_WARNING_POLICY, "DEFAULT")); if (DEBUG) log("showLowBatteryWarning called; mode = " + mode); switch (mode) { case DEFAULT: return; case NONINTRUSIVE: param.args[0] = false; break; case OFF: param.setResult(null); return; } } }); } catch (Throwable t) { XposedBridge.log(t); } } }
Power: improved low battery warning policy
src/com/ceco/lollipop/gravitybox/ModLowBatteryWarning.java
Power: improved low battery warning policy
<ide><path>rc/com/ceco/lollipop/gravitybox/ModLowBatteryWarning.java <ide> } <ide> <ide> Class<?> classPowerWarnings = findClass(CLASS_POWER_WARNINGS, classLoader); <del> findAndHookMethod(classPowerWarnings, "showLowBatteryWarning", boolean.class, new XC_MethodHook() { <add> findAndHookMethod(classPowerWarnings, "updateNotification", new XC_MethodHook() { <ide> @Override <ide> protected void beforeHookedMethod(MethodHookParam param) throws Throwable { <ide> prefs.reload(); <ide> case DEFAULT: <ide> return; <ide> case NONINTRUSIVE: <del> param.args[0] = false; <del> break; <add> XposedHelpers.setBooleanField(param.thisObject, "mPlaySound", false); <add> return; <ide> case OFF: <del> param.setResult(null); <add> XposedHelpers.setBooleanField(param.thisObject, "mWarning", false); <ide> return; <ide> } <ide> }
JavaScript
agpl-3.0
a5d28c27ab8a2512d429e981a3a797aff23c0588
0
schul-cloud/schulcloud-client,schul-cloud/schulcloud-client,schul-cloud/schulcloud-client
const moment = require('moment'); const express = require('express'); const shortId = require('shortid'); const router = express.Router({ mergeParams: true }); const Nexboard = require("nexboard-api-js"); const api = require('../api'); const authHelper = require('../helpers/authentication'); const etherpadBaseUrl = process.env.ETHERPAD_BASE_URL || 'https://tools.openhpi.de/etherpad/p/'; const editTopicHandler = (req, res, next) => { let lessonPromise, action, method; if(req.params.topicId) { action = '/courses/' + req.params.courseId + '/topics/' + req.params.topicId; method = 'patch'; lessonPromise = api(req).get('/lessons/' + req.params.topicId); } else { action = '/courses/' + req.params.courseId + '/topics/'; method = 'post'; lessonPromise = Promise.resolve({}); } Promise.all([ lessonPromise ]).then(([lesson]) => { if(lesson.contents) { // so we can share the content through data-value to the react component lesson.contents = JSON.stringify(lesson.contents); } res.render('topic/edit-topic', { action, method, title: req.params.topicId ? 'Thema bearbeiten' : 'Thema anlegen', submitLabel: req.params.topicId ? 'Änderungen speichern' : 'Thema anlegen', lesson, courseId: req.params.courseId, etherpadBaseUrl: etherpadBaseUrl }); }); }; // secure routes router.use(authHelper.authChecker); router.get('/', (req, res, next) => { res.redirect('/courses/' + req.params.courseId); }); router.get('/add', editTopicHandler); router.post('/', function (req, res, next) { const data = req.body; // Check for neXboard compontent data.contents = createNewNexBoards(req,res,data.contents); data.time = moment(data.time || 0, 'HH:mm').toString(); data.date = moment(data.date || 0, 'YYYY-MM-DD').toString(); api(req).post('/lessons/', { json: data // TODO: sanitize }).then(_ => { res.redirect('/courses/' + req.params.courseId + '/topics/'); }).catch(_ => { res.sendStatus(500); }); }); router.post('/:id/share', function (req, res, next) { // if lesson already has shareToken, do not generate a new one api(req).get('/lessons/' + req.params.id).then(topic => { topic.shareToken = topic.shareToken || shortId.generate(); api(req).patch("/lessons/" + req.params.id, {json: topic}) .then(result => res.json(result)) .catch(err => {res.err(err);}); }); }); router.get('/:topicId', function (req, res, next) { Promise.all([ api(req).get('/courses/' + req.params.courseId), api(req).get('/lessons/' + req.params.topicId, { qs: { $populate: ['materialIds'] } }), api(req).get('/homework/', { qs: { courseId: req.params.courseId, lessonId: req.params.topicId, $populate: ['courseId'], archived : {$ne: res.locals.currentUser._id } } }) ]).then(([course, lesson, homeworks]) => { // decorate contents lesson.contents = (lesson.contents || []).map(block => { block.component = 'topic/components/content-' + block.component; return block; }); homeworks = (homeworks.data || []).map(assignment => { assignment.url = '/homework/' + assignment._id; return assignment; }); homeworks.sort((a,b) => { if(a.dueDate > b.dueDate) { return 1; } else { return -1; } }); res.render('topic/topic', Object.assign({}, lesson, { title: lesson.name, homeworks: homeworks.filter(function(task){return !task.private;}), myhomeworks: homeworks.filter(function(task){return task.private;}), breadcrumb: [ { title: 'Meine Kurse', url: '/courses' }, { title: course.name, url: '/courses/' + course._id }, {} ] }), (error, html) => { if(error) { throw 'error in GET /:topicId - res.render: ' + error; } res.send(html); }); }); }); router.patch('/:topicId', function (req, res, next) { const data = req.body; data.time = moment(data.time || 0, 'HH:mm').toString(); data.date = moment(data.date || 0, 'YYYY-MM-DD').toString(); // if not a simple hidden or position patch, set contents to empty array if (!data.contents && !req.query.json){ data.contents = []; } // create new Nexboard when necessary data.contents = createNewNexBoards(req,res,data.contents); api(req).patch('/lessons/' + req.params.topicId, { json: data // TODO: sanitize }).then(_ => { if (req.query.json) { res.json(_); } else { //sends a GET request, not a PATCH res.redirect('/courses/' + req.params.courseId + '/topics/' + req.params.topicId); } }).catch(_ => { res.sendStatus(500); }); }); router.delete('/:topicId', function (req, res, next) { api(req).delete('/lessons/' + req.params.topicId).then(_ => { res.sendStatus(200); }).catch(err => { next(err); }); }); router.delete('/:topicId/materials/:materialId', function (req, res, next) { api(req).patch('/lessons/' + req.params.topicId, { json: { $pull: { materialIds: req.params.materialId } } }).then(_ => { api(req).delete('/materials/' + req.params.materialId).then(_ => { res.sendStatus(200); }); }); }); router.get('/:topicId/edit', editTopicHandler); const createNewNexBoards = (req,res,contents = []) => { contents.forEach(content => { if (content.component === "neXboard" && content.content.board === '0'){ const board = getNexBoardAPI().createBoard( content.content.title, content.content.description, getNexBoardProjectFromUser(req,res.locals.currentUser)); content.content.title = board.title; content.content.board = board.boardId; content.content.url = "https://" + board.public_link; content.content.description = board.description; } }); return contents; }; const getNexBoardAPI = () => { if (!process.env.NEXBOARD_USER_ID && !process.env.NEXBOARD_API_KEY) { //TODO handle error properly } return new Nexboard(process.env.NEXBOARD_API_KEY,process.env.NEXBOARD_USER_ID); }; const getNexBoardProjectFromUser = (req,user) => { const preferences = user.preferences || {}; if (typeof preferences.nexBoardProjectID === 'undefined') { const project = getNexBoardAPI().createProject(user._id,user._id); preferences.nexBoardProjectID = project.id; api(req).patch('/users/' + user._id, { json: { preferences } }); } return preferences.nexBoardProjectID; }; const getNexBoards = (req,res,next) => { api(req).get('/lessons/contents/neXboard' ,{ qs:{ type : 'neXboard', user : res.locals.currentUser._id } }) .then(boards => { res.json(boards); }); }; router.get('/:topicId/nexboard/boards', getNexBoards); router.get('/nexboard/boards',getNexBoards); module.exports = router;
controllers/topics.js
const moment = require('moment'); const express = require('express'); const shortId = require('shortid'); const router = express.Router({ mergeParams: true }); const Nexboard = require("nexboard-api-js"); const api = require('../api'); const authHelper = require('../helpers/authentication'); const etherpadBaseUrl = process.env.ETHERPAD_BASE_URL || 'https://tools.openhpi.de/etherpad/p/'; const editTopicHandler = (req, res, next) => { let lessonPromise, action, method; if(req.params.topicId) { action = '/courses/' + req.params.courseId + '/topics/' + req.params.topicId; method = 'patch'; lessonPromise = api(req).get('/lessons/' + req.params.topicId); } else { action = '/courses/' + req.params.courseId + '/topics/'; method = 'post'; lessonPromise = Promise.resolve({}); } Promise.all([ lessonPromise ]).then(([lesson]) => { if(lesson.contents) { // so we can share the content through data-value to the react component lesson.contents = JSON.stringify(lesson.contents); } res.render('topic/edit-topic', { action, method, title: req.params.topicId ? 'Thema bearbeiten' : 'Thema anlegen', submitLabel: req.params.topicId ? 'Änderungen speichern' : 'Thema anlegen', lesson, courseId: req.params.courseId, etherpadBaseUrl: etherpadBaseUrl }); }); }; // secure routes router.use(authHelper.authChecker); router.get('/', (req, res, next) => { res.redirect('/courses/' + req.params.courseId); }); router.get('/add', editTopicHandler); router.post('/', function (req, res, next) { const data = req.body; // Check for neXboard compontent data.contents = createNewNexBoards(req,res,data.contents); data.time = moment(data.time || 0, 'HH:mm').toString(); data.date = moment(data.date || 0, 'YYYY-MM-DD').toString(); api(req).post('/lessons/', { json: data // TODO: sanitize }).then(_ => { res.redirect('/courses/' + req.params.courseId + '/topics/'); }).catch(_ => { res.sendStatus(500); }); }); router.post('/:id/share', function (req, res, next) { // if lesson already has shareToken, do not generate a new one api(req).get('/lessons/' + req.params.id).then(topic => { topic.shareToken = topic.shareToken || shortId.generate(); api(req).patch("/lessons/" + req.params.id, {json: topic}) .then(result => res.json(result)) .catch(err => {res.err(err);}); }); }); router.get('/:topicId', function (req, res, next) { Promise.all([ api(req).get('/courses/' + req.params.courseId), api(req).get('/lessons/' + req.params.topicId, { qs: { $populate: ['materialIds'] } }), api(req).get('/homework/', { qs: { courseId: req.params.courseId, lessonId: req.params.topicId, $populate: ['courseId'], archived : {$ne: res.locals.currentUser._id } } }) ]).then(([course, lesson, homeworks]) => { // decorate contents lesson.contents = (lesson.contents || []).map(block => { block.component = 'topic/components/content-' + block.component; return block; }); homeworks = (homeworks.data || []).map(assignment => { assignment.url = '/homework/' + assignment._id; return assignment; }); homeworks.sort((a,b) => { if(a.dueDate > b.dueDate) { return 1; } else { return -1; } }); res.render('topic/topic', Object.assign({}, lesson, { title: lesson.name, homeworks: homeworks.filter(function(task){return !task.private;}), myhomeworks: homeworks.filter(function(task){return task.private;}), breadcrumb: [ { title: 'Meine Kurse', url: '/courses' }, { title: course.name, url: '/courses/' + course._id }, {} ] }), (error, html) => { if(error) { throw 'error in GET /:topicId - res.render: ' + error; } res.send(html); }); }); }); router.patch('/:topicId', function (req, res, next) { const data = req.body; data.time = moment(data.time || 0, 'HH:mm').toString(); data.date = moment(data.date || 0, 'YYYY-MM-DD').toString(); // if not a simple hidden or position patch, set contents to empty array if (!data.contents && !req.query.json){ data.contents = []; } // create new Nexboard when necessary data.contents = createNewNexBoards(req,res,data.contents); api(req).patch('/lessons/' + req.params.topicId, { json: data // TODO: sanitize }).then(_ => { if (req.query.json) { res.json(_); } else { //sends a GET request, not a PATCH res.redirect('/courses/' + req.params.courseId + '/topics/' + req.params.topicId); } }).catch(_ => { res.sendStatus(500); }); }); router.delete('/:topicId', function (req, res, next) { api(req).delete('/lessons/' + req.params.topicId).then(_ => { res.sendStatus(200); }).catch(err => { next(err); }); }); router.delete('/:topicId/materials/:materialId', function (req, res, next) { api(req).patch('/lessons/' + req.params.topicId, { json: { $pull: { materialIds: req.params.materialId } } }).then(_ => { api(req).delete('/materials/' + req.params.materialId).then(_ => { res.sendStatus(200); }); }); }); router.get('/:topicId/edit', editTopicHandler); const createNewNexBoards = (req,res,contents = []) => { contents.forEach(content => { if (content.component === "neXboard" && content.content.board === '0'){ const board = getNexBoardAPI().createBoard( content.content.title, content.content.description, getNexBoardProjectFromUser(req,res.locals.currentUser)); content.content.title = board.title; content.content.board = board.boardId; content.content.url = "https://" + board.public_link; content.content.description = board.description; } }); return contents; }; const getNexBoardAPI = () => { if (!process.env.NEXBOARD_USER_ID && !process.env.NEXBOARD_API_KEY) { //TODO handle error properly console.error("NEXBOARD_USER_ID and NEXBOARD_API_KEY environment variables are required"); } return new Nexboard(process.env.NEXBOARD_API_KEY,process.env.NEXBOARD_USER_ID); }; const getNexBoardProjectFromUser = (req,user) => { const preferences = user.preferences || {}; if (typeof preferences.nexBoardProjectID === 'undefined') { const project = getNexBoardAPI().createProject(user._id,user._id); preferences.nexBoardProjectID = project.id; api(req).patch('/users/' + user._id, { json: { preferences } }); } return preferences.nexBoardProjectID; }; const getNexBoards = (req,res,next) => { api(req).get('/lessons/contents/neXboard' ,{ qs:{ type : 'neXboard', user : res.locals.currentUser._id } }) .then(boards => { res.json(boards); }); }; router.get('/:topicId/nexboard/boards', getNexBoards); router.get('/nexboard/boards',getNexBoards); module.exports = router;
remove console command for Travis-tests
controllers/topics.js
remove console command for Travis-tests
<ide><path>ontrollers/topics.js <ide> const getNexBoardAPI = () => { <ide> if (!process.env.NEXBOARD_USER_ID && !process.env.NEXBOARD_API_KEY) { <ide> //TODO handle error properly <del> console.error("NEXBOARD_USER_ID and NEXBOARD_API_KEY environment variables are required"); <add> <ide> } <ide> return new Nexboard(process.env.NEXBOARD_API_KEY,process.env.NEXBOARD_USER_ID); <ide> };
Java
mit
error: pathspec 'test/idempotency/G003_MultipleFieldDeclarations.java' did not match any file(s) known to git
e6724afe7e5045ff71d213c99c66218280e5cd3d
1
rzwitserloot/lombok.ast,evant/android-retrolambda-lombok,evant/android-retrolambda-lombok,komalsukhani/deb-lombok.ast,rzwitserloot/lombok.ast,komalsukhani/deb-lombok.ast,evant/android-retrolambda-lombok,rzwitserloot/lombok.ast,komalsukhani/deb-lombok.ast
class G003_MultipleFieldDeclaration { private int x = 0, y; int z, k[] = {}; @SuppressWarnings("all") public final String[] name = null, names[] = {{}}; }
test/idempotency/G003_MultipleFieldDeclarations.java
Added test for multiple field declarations on one line
test/idempotency/G003_MultipleFieldDeclarations.java
Added test for multiple field declarations on one line
<ide><path>est/idempotency/G003_MultipleFieldDeclarations.java <add>class G003_MultipleFieldDeclaration { <add> private int x = 0, y; <add> <add> int z, k[] = {}; <add> <add> @SuppressWarnings("all") <add> public final String[] name = null, names[] = {{}}; <add>}
JavaScript
mit
17b9f148291414c376e2595ff3261567c2ef97a3
0
emlun/stegosaurus,emlun/stegosaurus
var multiparty = require('multiparty'); var fs = require('fs.extra'); var path = require('path'); var _ = require('underscore'); var steghide = require('./steghide'); /** * Build a request handler around steghide embed * * @param options the settings to use for the request handler. Expects an * object with zero or more of the following keys. The format for the below * is `name`: type (default). * * - `uploadDir`: String (`/tmp/stegosaurus`) the path under which to store * temporary files * - `imageFileParamName`: String (`coverImage`) the name of the HTTP query * parameter containing the cover image data * - `messageFileParamName`: String (`secretFile`) the name of the HTTP * query parameter containing the message file data * - `extractionPasswordParamName`: String (`extractionPassword`) the name of the * HTTP query parameter containing the extraction password * - `responseFileNamePrefix`: String (`steghidden-`) the prefix to prepend * to the uploaded image file name for the result file */ module.exports.embedHandler = function(options) { options = options || {}; _.defaults(options, { uploadDir: '/tmp/stegosaurus', imageFileParamName: 'coverImage', messageFileParamName: 'secretFile', extractionPasswordParamName: 'extractionPassword', responseFileNamePrefix: 'steghidden-', }); fs.mkdirp(options.uploadDir); return function(req, res) { var form = new multiparty.Form({ uploadDir: options.uploadDir, }); form.parse(req, function(err, fields, files) { if(err) { res.status(401).send('401 Bad request'); console.log('Bad request', err); return false; } var imageFile = files[options.imageFileParamName][0]; var secretFile = files[options.messageFileParamName][0]; var imagePath = imageFile.path; var secretPath = secretFile.path; var secretDir = secretPath + '.d'; var prettySecretPath = path.join(secretDir, path.basename(secretFile.originalFilename)); fs.mkdirSync(secretDir); fs.move(secretPath, prettySecretPath, function(err) { if(err) { res.status(503).send('503 Internal server error'); console.log(err); return false; } var steghiddenPath = steghide.embed( imagePath, prettySecretPath, fields[options.extractionPasswordParamName][0] ); function cleanup() { _([imagePath, secretPath, secretDir, steghiddenPath]).each(function(path) { fs.rmrfSync(path); }); } res.download(steghiddenPath, options.responseFileNamePrefix + imageFile.originalFilename, cleanup); }); }); } }; module.exports.extractHandler = function(options) { options = options || {}; _.defaults(options, { uploadDir: '/tmp/stegosaurus', imageFileParamName: 'stegoImage', extractionPasswordParamName: 'extractionPassword', }); fs.mkdirp(options.uploadDir); return function(req, res) { var form = new multiparty.Form({ uploadDir: options.uploadDir, }); form.parse(req, function(err, fields, files) { if(err) { res.status(401).send('401 Bad request'); console.log('Bad request', err); return false; } var imageFile = files[options.imageFileParamName][0]; var imagePath = imageFile.path; steghide.extract( imagePath, fields[options.extractionPasswordParamName][0], function(extractedPath, steghideCleanup) { function cleanup() { _([imagePath, extractedPath]).each(function(path) { fs.rmrfSync(path); }); steghideCleanup(); } res.download(extractedPath, path.basename(extractedPath), cleanup); } ); }); } };
index.js
var multiparty = require('multiparty'); var fs = require('fs.extra'); var path = require('path'); var _ = require('underscore'); var steghide = require('./steghide'); /** * Build a request handler around steghide embed * * @param options the settings to use for the request handler. Expects an * object with zero or more of the following keys. The format for the below * is `name`: type (default). * * - `uploadDir`: String (`/tmp/stegosaurus`) the path under which to store * temporary files * - `imageFileParamName`: String (`coverImage`) the name of the HTTP query * parameter containing the cover image data * - `messageFileParamName`: String (`secretFile`) the name of the HTTP * query parameter containing the message file data * - `extractionPasswordParamName`: String (`extractionPassword`) the name of the * HTTP query parameter containing the extraction password * - `responseFileNamePrefix`: String (`steghidden-`) the prefix to prepend * to the uploaded image file name for the result file */ module.exports.embedHandler = function(options) { options = options || {}; _.defaults(options, { uploadDir: '/tmp/stegosaurus', imageFileParamName: 'coverImage', messageFileParamName: 'secretFile', extractionPasswordParamName: 'extractionPassword', responseFileNamePrefix: 'steghidden-', }); return function(req, res) { var form = new multiparty.Form({ uploadDir: options.uploadDir, }); form.parse(req, function(err, fields, files) { if(err) { res.status(401).send('401 Bad request'); console.log('Bad request', err); return false; } var imageFile = files[options.imageFileParamName][0]; var secretFile = files[options.messageFileParamName][0]; var imagePath = imageFile.path; var secretPath = secretFile.path; var secretDir = secretPath + '.d'; var prettySecretPath = path.join(secretDir, path.basename(secretFile.originalFilename)); fs.mkdirSync(secretDir); fs.move(secretPath, prettySecretPath, function(err) { if(err) { res.status(503).send('503 Internal server error'); console.log(err); return false; } var steghiddenPath = steghide.embed( imagePath, prettySecretPath, fields[options.extractionPasswordParamName][0] ); function cleanup() { _([imagePath, secretPath, secretDir, steghiddenPath]).each(function(path) { fs.rmrfSync(path); }); } res.download(steghiddenPath, options.responseFileNamePrefix + imageFile.originalFilename, cleanup); }); }); } }; module.exports.extractHandler = function(options) { options = options || {}; _.defaults(options, { uploadDir: '/tmp/stegosaurus', imageFileParamName: 'stegoImage', extractionPasswordParamName: 'extractionPassword', }); return function(req, res) { var form = new multiparty.Form({ uploadDir: options.uploadDir, }); form.parse(req, function(err, fields, files) { if(err) { res.status(401).send('401 Bad request'); console.log('Bad request', err); return false; } var imageFile = files[options.imageFileParamName][0]; var imagePath = imageFile.path; steghide.extract( imagePath, fields[options.extractionPasswordParamName][0], function(extractedPath, steghideCleanup) { function cleanup() { _([imagePath, extractedPath]).each(function(path) { fs.rmrfSync(path); }); steghideCleanup(); } res.download(extractedPath, path.basename(extractedPath), cleanup); } ); }); } };
Create tmpdir(s) at startup
index.js
Create tmpdir(s) at startup
<ide><path>ndex.js <ide> extractionPasswordParamName: 'extractionPassword', <ide> responseFileNamePrefix: 'steghidden-', <ide> }); <add> <add> fs.mkdirp(options.uploadDir); <ide> <ide> return function(req, res) { <ide> var form = new multiparty.Form({ <ide> extractionPasswordParamName: 'extractionPassword', <ide> }); <ide> <add> fs.mkdirp(options.uploadDir); <add> <ide> return function(req, res) { <ide> var form = new multiparty.Form({ <ide> uploadDir: options.uploadDir,
Java
apache-2.0
8336557e638ac418988231567f038af35bd1b322
0
linas/relex,opencog/relex,rodsol/relex,opencog/relex,williampma/relex,ainishdave/relex,leungmanhin/relex,AmeBel/relex,virneo/relex,anitzkin/relex,williampma/relex,anitzkin/relex,anitzkin/relex,anitzkin/relex,AmeBel/relex,AmeBel/relex,rodsol/relex,linas/relex,leungmanhin/relex,anitzkin/relex,ainishdave/relex,williampma/relex,virneo/relex,leungmanhin/relex,rodsol/relex,virneo/relex,linas/relex,opencog/relex,ainishdave/relex,ainishdave/relex,williampma/relex,virneo/relex,rodsol/relex
/* * Copyright 2009 Linas Vepstas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); public TestRelEx() { re = new RelationExtractor(); pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); //add number of binary relations from parser-output, to total number of relationships got int sizeOfGotRelations= brgot.size(); //check expected binary and unary relations //the below for-loop checks whether all expected binary relations are //contained in the parser-binary-relation-output arrayList "brgot". //if any unary relations are expected in the output it checks the //parser-unary-relation-output arrayList "urgot" for unary relationships for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } //add the unary relation, count to totoal number of binary relations sizeOfGotRelations++; } } //The size checking of the expected relationships vs output relationships //is done here purposefully, to accommodate if there is any unary relationships present //in the expected output(see above for-loop also). //However it only checks whether parser-output resulted more relationships(binary+unary) than expected relations //If the parser-output resulted less relationships(binary+unary) than expected it would //catch that in the above for-loop if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK"); } else { System.err.println(subsys + ": Test failed\n\t" + fail + " sentences failed\n\t" + pass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_advmod(like, less)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_advmod(like, more)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); //Non-equal Gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "than(he, John)\n" + "more(intelligent,he)\n" + "degree(intelligent,comparative)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "than(he, John)\n" + "_more(intelligent,he)\n" + "degree(intelligent,comparative)\n"+ "_advmod(intelligent, less)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more than John.", "_obj(run, more)\n" + "_subj(run, he)\n" + "than(he,John)\n"+ "more(more,run)\n"+ "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less than John.", "_obj(run, less)\n" + "_subj(run, he)\n" + "than(he,John)\n"+ "_more(more,run)\n"+ "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs faster than John.", "than(He,John)\n" + "_more(fast,run)\n" + "_subj(run, He)\n"+ "_advmod(run, fast)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("He runs more slowly than John.", "than(He,John)\n" + "_subj(run, He)\n" + "more(slowly,run)\n"+ "_advmod(run,slowly)\n"+ "degree(slowly, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_Conjunction() { boolean rc = true; //conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); //conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); //conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); //conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); //adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); //verbs with modifiers rc &= test_sentence ( "We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go, movie)\n" + "_subj(go, we)\n"); //verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go_out, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); //conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); //conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); //conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, quickly)\n" + "_obj(handle, gracefully)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); //modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); //adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_and(car, truck)\n"); //Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "to(go, movie)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "who(woman, live)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_predadj(player, injured)\n" + "who(player, injured)\n" ); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "to(belong, aunt)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "which(restaurant, belong)\n" + "_predadj(restaurant, famous)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "by(write, Charles_Dickens)\n" + "_obj(read, book)\n" + "in(read, library)\n" + "_subj(read, I)\n" + "which(book, read)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "in(meet, library)\n" + "_subj(meet, I)\n" + "whose(book, author)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_iobj(lend, book)\n" + "_obj(lend, me)\n" + "_subj(lend, Jack)\n" + "that_adj(book, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "by(recommend, owner)\n" + "_poss(owner, restaurant)\n" + "which(curry, recommend)\n" + "_amod(curry, special)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "who(dog, chase)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_obj(near, window)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "that_adj(car, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "by(stop, sign)\n" + "_advmod(stop, just)\n" + "on(stand, street)\n" + "_subj(stand, sign)\n" + "that_adj(sign, stand)\n" + "_nn(sign, traffic)\n" + "before(just, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public static void main(String[] args) { TestRelEx ts = new TestRelEx(); boolean rc = true; rc &= ts.test_comparatives(); rc &= ts.test_extraposition(); rc &= ts.test_Conjunction(); if (rc) { System.err.println("Tested " + ts.pass + " sentences, test passed OK"); } else { System.err.println("Test failed\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if(sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
src/java_test/relex/test/TestRelEx.java
/* * Copyright 2009 Linas Vepstas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); public TestRelEx() { re = new RelationExtractor(); pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); //add number of binary relations from parser-output, to total number of relationships got int sizeOfGotRelations= brgot.size(); //check expected binary and unary relations //the below for-loop checks whether all expected binary relations are //contained in the parser-binary-relation-output arrayList "brgot". //if any unary relations are expected in the output it checks the //parser-unary-relation-output arrayList "urgot" for unary relationships for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } //add the unary relation, count to totoal number of binary relations sizeOfGotRelations++; } } //The size checking of the expected relationships vs output relationships //is done here purposefully, to accommodate if there is any unary relationships present //in the expected output(see above for-loop also). //However it only checks whether parser-output resulted more relationships(binary+unary) than expected relations //If the parser-output resulted less relationships(binary+unary) than expected it would //catch that in the above for-loop if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK"); } else { System.err.println(subsys + ": Test failed\n\t" + fail + " sentences failed\n\t" + pass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_advmod(like, less)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_advmod(like, more)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); //Non-equal Gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "than(he, John)\n" + "more(intelligent,he)\n" + "degree(intelligent,comparative)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "than(he, John)\n" + "_more(intelligent,he)\n" + "degree(intelligent,comparative)\n"+ "_advmod(intelligent, less)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more than John.", "_obj(run, more)\n" + "_subj(run, he)\n" + "than(he,John)\n"+ "more(more,run)\n"+ "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less than John.", "_obj(run, less)\n" + "_subj(run, he)\n" + "than(he,John)\n"+ "_more(more,run)\n"+ "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs faster than John.", "than(He,John)\n" + "_more(fast,run)\n" + "_subj(run, He)\n"+ "_advmod(run, fast)\n"+ "degree(fast, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_Conjunction() { boolean rc = true; //conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); //conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); //conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); //conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); //adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); //verbs with modifiers rc &= test_sentence ( "We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go, movie)\n" + "_subj(go, we)\n"); //verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go_out, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); //conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); //conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); //conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, quickly)\n" + "_obj(handle, gracefully)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); //modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); //adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_and(car, truck)\n"); //Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "to(go, movie)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "who(woman, live)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_predadj(player, injured)\n" + "who(player, injured)\n" ); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "to(belong, aunt)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "which(restaurant, belong)\n" + "_predadj(restaurant, famous)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "by(write, Charles_Dickens)\n" + "_obj(read, book)\n" + "in(read, library)\n" + "_subj(read, I)\n" + "which(book, read)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "in(meet, library)\n" + "_subj(meet, I)\n" + "whose(book, author)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_iobj(lend, book)\n" + "_obj(lend, me)\n" + "_subj(lend, Jack)\n" + "that_adj(book, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "by(recommend, owner)\n" + "_poss(owner, restaurant)\n" + "which(curry, recommend)\n" + "_amod(curry, special)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "who(dog, chase)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_obj(near, window)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "that_adj(car, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "by(stop, sign)\n" + "_advmod(stop, just)\n" + "on(stand, street)\n" + "_subj(stand, sign)\n" + "that_adj(sign, stand)\n" + "_nn(sign, traffic)\n" + "before(just, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public static void main(String[] args) { TestRelEx ts = new TestRelEx(); boolean rc = true; rc &= ts.test_comparatives(); rc &= ts.test_extraposition(); rc &= ts.test_Conjunction(); if (rc) { System.err.println("Tested " + ts.pass + " sentences, test passed OK"); } else { System.err.println("Test failed\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if(sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
Adding test sentence "He runs more slowly than John."
src/java_test/relex/test/TestRelEx.java
Adding test sentence "He runs more slowly than John."
<ide><path>rc/java_test/relex/test/TestRelEx.java <ide> "_subj(run, He)\n"+ <ide> "_advmod(run, fast)\n"+ <ide> "degree(fast, comparative)\n"); <add> <add> rc &= test_sentence ("He runs more slowly than John.", <add> "than(He,John)\n" + <add> "_subj(run, He)\n" + <add> "more(slowly,run)\n"+ <add> "_advmod(run,slowly)\n"+ <add> "degree(slowly, comparative)\n"); <ide> report(rc, "Comparatives"); <ide> return rc; <ide> }
Java
apache-2.0
1a63969415773d8302f813167f587d356ce77538
0
libris/librisxl,libris/librisxl,libris/librisxl
package transform; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Assert; import org.junit.Test; import whelk.util.TransformScript; import java.util.Map; public class ScriptTest { static ObjectMapper mapper = new ObjectMapper(); @Test public void testBasicSet() throws Exception { String data = "{}"; String script = "mode normal " + "set value0 -> key0"; String transformed = "" + "{" + " \"key0\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicLet() throws Exception { String data = "{}"; String script = "mode normal " + "set value0 -> key0 " + "let x = 1"; String transformed = "" + "{" + " \"key0\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testLetSetMove() throws Exception { String data = "{\"key0\":\"value0\"}"; String script = "mode normal " + "let var = * key0 " + "set var -> key1 " + "set literal -> key2 "; String transformed = "" + "{" + " \"key0\":\"value0\"," + " \"key1\":\"value0\"," + " \"key2\":\"literal\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicParenthesis() throws Exception { String data = "{\"key0\":\"value0\"}"; String script = "mode normal " + "let var = ( * key0 ) " + "set ( var ) -> key1 "; String transformed = "" + "{" + " \"key0\":\"value0\"," + " \"key1\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicArithmetic() throws Exception { String data = "{}"; String script = "mode normal " + "let x = 1 + 1 " + "set x -> key0 " + "let y = 1 + 1 + 2 " + "set y -> key1 " + "let z = ( 1 + 1 ) * 3 " + "set z -> key2 "; String transformed = "" + "{" + " \"key0\":2," + " \"key1\":4," + " \"key2\":6" + "}"; testScript(data, transformed, script); } @Test public void testSizeOf() throws Exception { String data = "" + "{" + " \"somelist\":" + " [" + " {\"somekey\":\"somevalue\"}," + " {\"somekey\":\"somevalue\"}," + " {\"somekey\":\"somevalue\"}" + " ]" + "}"; String script = "mode normal " + "let x = sizeof somelist * 2 " + "delete somelist " + "set x -> result "; String transformed = "" + "{" + " \"result\":6" + "}"; testScript(data, transformed, script); } @Test public void testLocalScope() throws Exception { String data = "{}"; String script = "mode normal " + "let x = 2 " + "{ " + " let x = 3 " + " set x -> result0 " + "} " + "set x -> result1 "; String transformed = "" + "{" + " \"result0\":3," + " \"result1\":2" + "}"; testScript(data, transformed, script); } private void testScript(String beforeTransformText, String expectedResultText, String transformScript) throws Exception { Map oldData = mapper.readValue(beforeTransformText, Map.class); Map expectedResultData = mapper.readValue(expectedResultText, Map.class); TransformScript executableScript = new TransformScript(transformScript); Map transformed = executableScript.executeOn(oldData); if ( ! Utils.rdfEquals( expectedResultData, transformed ) ) { System.out.println("expected transformation result:\n"+expectedResultData); System.out.println("\nactual transformation result:\n"+transformed); Assert.assertTrue( false ); } } }
transform/src/test/java/transform/ScriptTest.java
package transform; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Assert; import org.junit.Test; import whelk.util.TransformScript; import java.util.Map; public class ScriptTest { static ObjectMapper mapper = new ObjectMapper(); @Test public void testBasicSet() throws Exception { String data = "{}"; String script = "mode normal " + "set value0 -> key0"; String transformed = "" + "{" + " \"key0\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicLet() throws Exception { String data = "{}"; String script = "mode normal " + "set value0 -> key0 " + "let x = 1"; String transformed = "" + "{" + " \"key0\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testLetSetMove() throws Exception { String data = "{\"key0\":\"value0\"}"; String script = "mode normal " + "let var = * key0 " + "set var -> key1 " + "set literal -> key2 "; String transformed = "" + "{" + " \"key0\":\"value0\"," + " \"key1\":\"value0\"," + " \"key2\":\"literal\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicParenthesis() throws Exception { String data = "{\"key0\":\"value0\"}"; String script = "mode normal " + "let var = ( * key0 ) " + "set ( var ) -> key1 "; String transformed = "" + "{" + " \"key0\":\"value0\"," + " \"key1\":\"value0\"" + "}"; testScript(data, transformed, script); } @Test public void testBasicArithmetic() throws Exception { String data = "{}"; String script = "mode normal " + "let x = 1 + 1 " + "set x -> key0 " + "let y = 1 + 1 + 2 " + "set y -> key1 " + "let z = ( 1 + 1 ) * 3 " + "set z -> key2 "; String transformed = "" + "{" + " \"key0\":2," + " \"key1\":4," + " \"key2\":6" + "}"; testScript(data, transformed, script); } @Test public void testSizeOf() throws Exception { String data = "" + "{" + " \"somelist\":" + " [" + " {\"somekey\":\"somevalue\"}," + " {\"somekey\":\"somevalue\"}," + " {\"somekey\":\"somevalue\"}" + " ]" + "}"; String script = "mode normal " + "let x = sizeof somelist * 2 " + "delete somelist " + "set x -> result "; String transformed = "" + "{" + " \"result\":6" + "}"; testScript(data, transformed, script); } private void testScript(String beforeTransformText, String expectedResultText, String transformScript) throws Exception { Map oldData = mapper.readValue(beforeTransformText, Map.class); Map expectedResultData = mapper.readValue(expectedResultText, Map.class); TransformScript executableScript = new TransformScript(transformScript); Map transformed = executableScript.executeOn(oldData); if ( ! Utils.rdfEquals( expectedResultData, transformed ) ) { System.out.println("expected transformation result:\n"+expectedResultData); System.out.println("\nactual transformation result:\n"+transformed); Assert.assertTrue( false ); } } }
Add transform script test case.
transform/src/test/java/transform/ScriptTest.java
Add transform script test case.
<ide><path>ransform/src/test/java/transform/ScriptTest.java <ide> testScript(data, transformed, script); <ide> } <ide> <add> @Test <add> public void testLocalScope() throws Exception <add> { <add> String data = "{}"; <add> <add> String script = "mode normal " + <add> "let x = 2 " + <add> "{ " + <add> " let x = 3 " + <add> " set x -> result0 " + <add> "} " + <add> "set x -> result1 "; <add> <add> String transformed = "" + <add> "{" + <add> " \"result0\":3," + <add> " \"result1\":2" + <add> "}"; <add> <add> testScript(data, transformed, script); <add> } <add> <ide> private void testScript(String beforeTransformText, String expectedResultText, String transformScript) throws Exception <ide> { <ide> Map oldData = mapper.readValue(beforeTransformText, Map.class);
Java
bsd-3-clause
d3c51873fe6dd56187e97f56bbeb0a9f57504fcb
0
mushroomhostage/FreeTrade,mushroomhostage/FreeTrade,mushroomhostage/FreeTrade
package me.exphc.FreeTrade; import java.util.logging.Logger; import java.util.regex.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.SortedSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.Date; import java.sql.Timestamp; import java.io.*; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.command.*; import org.bukkit.entity.*; import org.bukkit.inventory.*; import org.bukkit.enchantments.*; import org.bukkit.configuration.*; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.player.*; import org.bukkit.event.*; import org.bukkit.block.*; import org.bukkit.*; import info.somethingodd.bukkit.OddItem.OddItem; import org.bukkit.craftbukkit.CraftServer; import net.minecraft.server.MinecraftServer; import net.minecraft.server.EntityPlayer; import net.minecraft.server.ItemInWorldManager; enum Obtainability { NORMAL, SILKTOUCH, CREATIVE, HACKING, NEVER }; class ItemQuery { ItemStack itemStack; static Logger log = Logger.getLogger("Minecraft"); // Map between item names/aliases and id;dmg string // TODO: switch to more appropriate data structures, ItemStacks? static ConcurrentHashMap<String,String> name2CodeName; static ConcurrentHashMap<String,String> codeName2Name; // TODO: switch to sets static ConcurrentHashMap<String,Boolean> isTradableMap; static ConcurrentHashMap<Material,Boolean> isDurableMap; static ConcurrentHashMap<Material,Boolean> isEnchantableMap; static ConcurrentHashMap<Material,Boolean> isCountableMap; public ItemQuery(String s) { //Pattern onp = Pattern.compile( "^(\\d+)" Pattern p = Pattern.compile( "^(\\d*)" + // quantity "([# :;-]?)" + // separator / stack flag "([^/\\\\]+)" + // name "([/\\\\]?)" + // separator / damage flag "([\\d%]*)" + // use / damage "/?([^/]*)$"); // enchant Matcher m = p.matcher(s); int quantity; if (!m.find()) { throw new UsageException("Unrecognized item specification: " + s); } String quantityString = m.group(1); String isStackString = m.group(2); String nameString = m.group(3); String dmgOrUsesString = m.group(4); String usesString = m.group(5); String enchString = m.group(6); if (quantityString.equals("")) { quantity = 1; } else { quantity = Integer.parseInt(quantityString); if (quantity < 1) { throw new UsageException("Invalid quantity: " + quantity); } } // Name // Allowed to be any case, with or without any word separators nameString = nameString.replaceAll("[ _-]", "").toLowerCase(); if (nameString.contains("*")) { // Wildcard expressions SortedSet<String> results = wildcardLookupName(nameString); if (results.size() == 0) { throw new UsageException("No items match pattern " + nameString); } if (results.size() > 1) { StringBuffer nameMatches = new StringBuffer(); for (String resultName: results) { nameMatches.append(resultName + ", "); } throw new UsageException("Found " + results.size() + " matching items: " + nameMatches); } // Exactly one hit, use it nameString = results.first().toLowerCase(); } // First try built-in name lookup itemStack = directLookupName(nameString); if (itemStack == null) { // If available, try OddItem for better names or clever suggestions if (Bukkit.getServer().getPluginManager().getPlugin("OddItem") != null) { try { itemStack = OddItem.getItemStack(nameString).clone(); } catch (IllegalArgumentException suggestion) { throw new UsageException("No such item '" + nameString + "', did you mean '" + suggestion.getMessage() + "'?"); } } else { // Worst case, lookup name from Bukkit itself // Not very good because doesn't include damage value subtypes Material material = Material.matchMaterial(nameString); if (material == null) { throw new UsageException("Unrecognized item name: " + nameString + " (no suggestions available)"); } itemStack = new ItemStack(material); } } if (itemStack == null) { throw new UsageException("Unrecognized item name: " + nameString); } // Quantity, shorthand 10# = 10 stacks if (isStackString.equals("#")) { quantity *= Math.abs(itemStack.getType().getMaxStackSize()); } itemStack.setAmount(quantity); // Damage value aka durability // User specifies how much they want left, 100% = unused tool short maxDamage = itemStack.getType().getMaxDurability(); if (usesString != null && !usesString.equals("")) { short damage; short value; if (isCountable(itemStack.getType()) || !isDurable(itemStack.getType())) { // Countable items specify damage directly // -or- non-durable items // TODO: restrict setting durability on non-durable items?? admin function if (!isDurable(itemStack.getType())) { log.info("Warning: setting durability on non-durable item "+nameStack(itemStack)); } damage = Short.parseShort(usesString); // TODO: clamp? for maps at least, if request beyond last + 2, will give last + 1 // but, if request last + 1, then will create a new map in that slot } else { // Tools - uses, percentages if (usesString.endsWith("%")) { String percentageString = usesString.substring(0, usesString.length() - 1); double percentage = Double.parseDouble(percentageString); value = (short)(percentage / 100.0 * maxDamage); } else { value = Short.parseShort(usesString); } // Normally, convenient for user to specify percent or times left (inverse of damage), / // Allow \ separator to specify damage itself if (dmgOrUsesString.equals("\\")) { damage = value; } else { damage = (short)(maxDamage - value); } if (damage > maxDamage) { damage = maxDamage; // Breaks right after one use } if (damage < 0) { damage = 0; // Completely unused } } itemStack.setDurability(damage); } else { // If they didn't specify a durability, but they want a durable item, assume no damage (0) // TODO: only assume 0 for wants. For gives, need to use value from inventory! Underspecified } // Enchantments if (enchString != null && !enchString.equals("")) { // TODO: rethink enchantable and other item subtype permissions // Should always be expressible as new ItemQuery(), but may want to restrict // based on player permissions what they can trade /* if (!isEnchantable(itemStack.getType())) { throw new UsageException("Not enchantable"); // TODO: allow permission to override, if want e.g. enchanted shears for testing }*/ EnchantQuery enchs = new EnchantQuery(enchString); itemStack.addUnsafeEnchantments(enchs.all); } } public ItemQuery(String s, OfflinePlayer p) { if (s.equals("this")) { if (p.getPlayer() == null) { throw new UsageException("Cannot specify 'this' on offline player"); } itemStack = p.getPlayer().getItemInHand().clone(); if (itemStack == null) { throw new UsageException("No item in hand"); } } else { itemStack = (new ItemQuery(s)).itemStack; } } // Return whether an item degrades when used public static boolean isDurable(Material m) { if (m == null) return false; // TODO: non-standard items return isDurableMap.containsKey(m); } // Return whether an item can be legitimately enchanted public static boolean isEnchantable(Material m) { if (m == null) return false; // TODO: non-standard items return isEnchantableMap.containsKey(m); } // Return whether an item is numbered, like maps in vanilla (map0, map1..) public static boolean isCountable(Material m) { if (m == null) return false; // TODO: non-standard items return isCountableMap.containsKey(m); } public static String nameStack(ItemStack itemStack) { if (isNothing(itemStack)) { return "nothing"; } String name, usesString, enchString; Material m = itemStack.getType(); if (isDurable(m)) { // Percentage remaining // Round down so '100%' always means completely unused? (1 dmg = 99%) //int percentage = Math.round(Math.floor((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability())) // but then lower percentages are always one lower.. // So just special-case 100% to avoid misleading int percentage; if (itemStack.getDurability() == 0) { percentage = 100; } else { percentage = (int)((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability()); if (percentage == 100) { percentage = 99; } } usesString = "/" + percentage + "%"; } else { usesString = ""; } // Find canonical name of item String codeName; codeName = itemStack.getTypeId() + ""; name = codeName2Name.get(codeName); if (name == null) { // durability here actually is overloaded to mean a different item codeName = itemStack.getTypeId() + ";" + itemStack.getDurability(); name = codeName2Name.get(codeName); } if (name == null) { name = "unknown="+codeName; } // Countable items are numbered (map/0, map/1...) if (isCountable(itemStack.getType())) { name += "/" + itemStack.getDurability(); } // Enchantments if (EnchantQuery.hasEnchantments(itemStack)) { Map<Enchantment,Integer> enchs = itemStack.getEnchantments(); enchString = "/" + EnchantQuery.nameEnchs(enchs); } else { enchString = ""; } return itemStack.getAmount() + ":" + name + usesString + enchString; } // Return whether two item stacks have the same item, taking into account 'subtypes' // stored in the damage value (ex: blue wool, only same as blue wool) - but will // ignore damage for durable items (ex: diamond sword, 50% = diamond sword, 100%) public static boolean isSameType(ItemStack a, ItemStack b) { if (a.getType() != b.getType()) { return false; } Material m = a.getType(); if (isDurable(m)) { return true; } return a.getDurability() == b.getDurability(); } // Return whether two item stacks are identical - except for amount! // Compares type, durability, enchantments public static boolean isIdenticalItem(ItemStack a, ItemStack b) { if (a == null || b == null) { return false; } if (a == null && b == null) { return true; } if (a.getType() != b.getType()) { return false; } // Same subtype -or- durability for tools if (a.getDurability() != b.getDurability()) { return false; } // Same enchantments // Compare by name to avoid complex duplicate enchantment traversing code String enchNameA = EnchantQuery.nameEnchs(a.getEnchantments()); String enchNameB = EnchantQuery.nameEnchs(b.getEnchantments()); if (!enchNameA.equals(enchNameB)) { return false; } return true; } // Identical and same amounts too public static boolean isIdenticalStack(ItemStack a, ItemStack b) { return isIdenticalItem(a, b) && a.getAmount() == b.getAmount(); } // Return whether item is configured to be allowed to be traded public static boolean isTradable(ItemStack items) { // Durability always stored, but 0 for durable items return isTradableMap.containsKey(items.getTypeId() + ";" + (isDurable(items.getType()) ? 0 : items.getDurability())); } // Configuration public static void loadConfig(YamlConfiguration config) { Map<String,Object> configValues = config.getValues(true); MemorySection itemsSection = (MemorySection)configValues.get("items"); int i = 0; name2CodeName = new ConcurrentHashMap<String, String>(); codeName2Name = new ConcurrentHashMap<String, String>(); isDurableMap = new ConcurrentHashMap<Material, Boolean>(); isEnchantableMap = new ConcurrentHashMap<Material, Boolean>(); isCountableMap = new ConcurrentHashMap<Material, Boolean>(); ConcurrentHashMap<String,Boolean> isTradableMapUnfiltered = new ConcurrentHashMap<String, Boolean>(); HashSet<Obtainability> tradableCategories = new HashSet<Obtainability>(); for (String obtainString: config.getStringList("tradableCategories")) { tradableCategories.add(Obtainability.valueOf(obtainString.toUpperCase())); } for (String codeName: itemsSection.getKeys(false)) { String properName = config.getString("items." + codeName + ".name"); // How this item can be obtained String obtainString = config.getString("items." + codeName + ".obtain"); Obtainability obtain = (obtainString == null) ? Obtainability. NORMAL : Obtainability.valueOf(obtainString.toUpperCase()); boolean tradable = tradableCategories.contains(obtain); // TODO: whitelist, blacklist (with wildcards! search) if (tradable) { isTradableMapUnfiltered.put(codeName.contains(";") ? codeName : codeName + ";0", tradable); } // Add aliases from config List<String> aliases = config.getStringList("items." + codeName + ".aliases"); if (aliases != null) { for (String alias: aliases) { name2CodeName.put(alias, codeName); i += 1; } } // Generate 'proper name' alias, preprocessed for lookup String smushedProperName = properName.replaceAll(" ",""); String aliasProperName = smushedProperName.toLowerCase(); name2CodeName.put(aliasProperName, codeName); i += 1; codeName2Name.put(codeName, smushedProperName); // Generate numeric alias name2CodeName.put(codeName, codeName); i += 1; // Whether loses durability when used or not (include in trades) String purpose = config.getString("items." + codeName + ".purpose"); Material material = codeName2ItemStack(codeName).getType(); boolean durable = purpose != null && (purpose.equals("armor") || purpose.equals("tool") || purpose.equals("weapon")); if (durable) { isDurableMap.put(material, new Boolean(true)); } // Items are enchantable if durable, unless overridden (for shears, etc.) boolean enchantable = config.getBoolean("items." + codeName + ".enchant", durable); if (enchantable) { isEnchantableMap.put(material, new Boolean(true)); } if (config.getBoolean("items." + codeName + ".count", false)) { isCountableMap.put(material, new Boolean(true)); } } log.info("Loaded " + i + " item aliases"); // Whitelist tradable items for (String whiteString: config.getStringList("tradableWhitelist")) { ItemStack itemStack = directLookupName(whiteString); isTradableMapUnfiltered.put(itemStack.getTypeId() + ";" + itemStack.getDurability(), true); } // Filter through blacklist isTradableMap = new ConcurrentHashMap<String, Boolean>(); SKIP: for (String tradableCodeName: isTradableMapUnfiltered.keySet()) { // Is this blacklisted? for (String blackString: config.getStringList("tradableBlacklist")) { ItemStack itemStack = directLookupName(blackString); if (tradableCodeName.equals(itemStack.getTypeId() + ";" + itemStack.getDurability())) { continue SKIP; } } // No, add to real list isTradableMap.put(tradableCodeName, true); } } // Parse a material code string with optional damage value (ex: 35;11) public static ItemStack codeName2ItemStack(String codeName) { Pattern p = Pattern.compile("^(\\d+)[;:/]?(\\d*)([+]?.*)$"); Matcher m = p.matcher(codeName); int typeCode; short dmgCode; if (!m.find()) { // This is an error in the config file (TODO: preparse or detect earlier) throw new UsageException("Invalid item code format: " + codeName); } // typeid typeCode = Integer.parseInt(m.group(1)); // ;damagevalue if (m.group(2) != null && !m.group(2).equals("")) { dmgCode = Short.parseShort(m.group(2)); } else { dmgCode = 0; } ItemStack item = new ItemStack(typeCode, 1, dmgCode); // +enchantcode@enchantlevel... if (m.group(3) != null && !m.group(3).equals("")) { String[] parts = m.group(3).split("[+]"); for (String part: parts) { if (part.length() == 0) { continue; } String[] idAndLevel = part.split("@"); if (idAndLevel.length != 2) { throw new UsageException("Invalid item code: " + codeName + ", enchantment spec: " + part); } int id, level; try { id = Integer.parseInt(idAndLevel[0]); level = Integer.parseInt(idAndLevel[1]); } catch (Exception e) { throw new UsageException("Invalid item code: " + codeName + ", enchantment id/level: " + part); } Enchantment ench = Enchantment.getById(id); // Add unsafe, since plugins might want to (ab)use enchantment for other purposes item.addUnsafeEnchantment(ench, level); } } return item; } // Get an ItemStack directly from one of its names or aliases, or null private static ItemStack directLookupName(String nameString) { String materialCode = name2CodeName.get(nameString); if (materialCode == null) { return null; } return codeName2ItemStack(materialCode); } // Get proper names of all aliases matching a wildcard pattern private static SortedSet<String> wildcardLookupName(String pattern) { SortedSet<String> results = new TreeSet<String>(); Iterator it = name2CodeName.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); String name = (String)pair.getKey(); String codeName = (String)pair.getValue(); if (matchesWildcard(pattern, name) && isTradableMap.containsKey(codeName)) { results.add(codeName2Name.get(codeName).replace(" ","")); } } return results; } // Return whether a wildcard pattern (with asterisks = anything) matches private static boolean matchesWildcard(String needle, String haystack) { String[] cards = needle.split("\\*"); for (String card : cards) { int i = haystack.indexOf(card); if (i == -1) { return false; } haystack = haystack.substring(i + card.length()); } return true; } public static boolean isNothing(ItemStack itemStack) { return itemStack == null || itemStack.getType() == Material.AIR; } } class EnchantQuery { static Logger log = Logger.getLogger("Minecraft"); Map<Enchantment,Integer> all; static ConcurrentHashMap<String, Enchantment> name2Code; static ConcurrentHashMap<Enchantment, String> code2Name; public EnchantQuery(String allString) { all = new HashMap<Enchantment,Integer>(); String[] enchStrings = allString.split("[, /-]+"); for (String enchString: enchStrings) { Pattern p = Pattern.compile("^([A-Za-z-]*[a-z])([IV0-9]*)$"); Matcher m = p.matcher(enchString); if (!m.find()) { throw new UsageException("Unrecognizable enchantment: '" + enchString + "'"); } String baseName = m.group(1); String levelString = m.group(2); Enchantment ench = enchFromBaseName(baseName); int level = levelFromString(levelString); // Odd, what's the point of having a separate 'wrapper' class? // Either way, it has useful methods for us //EnchantmentWrapper enchWrapper = new EnchantmentWrapper(ench.getId()); EnchantmentWrapper enchWrapper = wrapEnch(ench); // TODO: restrict max level? need to figure out permissions here // sometimes (often), exceeding the "max" is useful if (level > enchWrapper.getMaxLevel()) { log.info("Warning: exceeding max level enchantment "+ench+" "+level+" > " + enchWrapper.getMaxLevel()); //level = ench.getMaxLevel(); } log.info("Enchantment: " + ench + ", level="+level); all.put(enchWrapper, new Integer(level)); } } // Return whether all the enchantments can apply to an item public boolean canEnchantItem(ItemStack item) { Iterator it = all.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); EnchantmentWrapper ench = wrapEnch(pair.getKey()); Integer level = (Integer)pair.getValue(); if (!ench.canEnchantItem(item)) { log.info("Cannot apply enchantment " + ench + " to " + item); return false; } } return true; } public static boolean hasEnchantments(ItemStack item) { Map<Enchantment,Integer> enchs = item.getEnchantments(); return enchs.size() != 0; } public String toString() { return nameEnchs(all); } public static String nameEnchs(Map<Enchantment,Integer> all) { StringBuffer names = new StringBuffer(); Iterator it = all.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); Object obj = pair.getKey(); EnchantmentWrapper ench = wrapEnch(pair.getKey()); Integer level = (Integer)pair.getValue(); names.append(nameEnch(ench)); names.append(levelToString(level)); names.append(","); } // Remove the trailing comma // Would have liked to just build an array then join it, but not easier in Java either if (names.length() > 1) { names.deleteCharAt(names.length() - 1); } return names.toString(); } // Get an EnchantmentWrapper from either an EnchantmentWrapper or Enchantment // Not sure why Bukkit chose to have two classes, but EnchantmentWrapper is more functional public static EnchantmentWrapper wrapEnch(Object obj) { if (obj instanceof EnchantmentWrapper) { return (EnchantmentWrapper)obj; } Enchantment ench = (Enchantment)obj; return new EnchantmentWrapper(ench.getId()); } static Enchantment enchFromBaseName(String name) { // Built-in config file database.. name = name.toLowerCase(); Enchantment ench = name2Code.get(name); if (ench != null) { return ench; } // Bukkit itself? ench = Enchantment.getByName(name); if (ench != null) { return ench; } throw new UsageException("Unrecognized enchantment: " + name); } static String nameEnch(EnchantmentWrapper ench) { String name = code2Name.get(ench); if (name != null) { return name; } return "Unknown(" + ench.getId() + ")"; // There is ench.getName(), but the names don't match in-game } static int levelFromString(String s) { if (s.equals("") || s.equals("I")) { return 1; } else if (s.equals("II")) { return 2; } else if (s.equals("III")) { return 3; } else if (s.equals("IV")) { return 4; } else if (s.equals("V")) { return 5; } else { return Integer.parseInt(s); } } static String levelToString(int n) { switch (n) { case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; default: return Integer.toString(n); } } // Return wheather itemA has >= enchantments than itemB public static boolean equalOrBetter(ItemStack itemA, ItemStack itemB) { Map<Enchantment,Integer> enchsB = itemB.getEnchantments(); Iterator it = enchsB.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); EnchantmentWrapper enchB = (EnchantmentWrapper)pair.getKey(); int levelB = ((Integer)pair.getValue()).intValue(); if (!itemA.containsEnchantment(Enchantment.getById(enchB.getId()))) { log.info("Missing enchantment " + nameEnch(enchB) + " not on " + itemA + " (doesn't match " + itemB + ")"); return false; } int levelA = itemA.getEnchantmentLevel(Enchantment.getById(enchB.getId())); log.info("Level " + levelB + " vs " + levelA); if (levelA < levelB) { log.info("Lower enchantment level " + levelA + " < " + levelB); return false; } } return true; } public static void loadConfig(YamlConfiguration config) { Map<String,Object> configValues = config.getValues(true); MemorySection enchantsSection = (MemorySection)configValues.get("enchants"); int i = 0; name2Code = new ConcurrentHashMap<String, Enchantment>(); code2Name = new ConcurrentHashMap<Enchantment, String>(); for (String codeString: enchantsSection.getKeys(false)) { Enchantment ench = Enchantment.getById(Integer.parseInt(codeString)); String properName = config.getString("enchants." + codeString + ".name"); List<String> aliases = config.getStringList("enchants." + codeString + ".aliases"); if (aliases != null) { for (String alias: aliases) { name2Code.put(alias, ench); i += 1; } } // Generate 'proper name' alias, preprocessed for lookup String smushedProperName = properName.replaceAll(" ",""); String aliasProperName = smushedProperName.toLowerCase(); name2Code.put(aliasProperName, ench); i += 1; code2Name.put(ench, smushedProperName); } log.info("Loaded " + i + " enchantment aliases"); } } class Order implements Comparable { OfflinePlayer player; ItemStack want, give; boolean free; public Order(OfflinePlayer p, String wantString, String giveString) { player = p; if (wantString.startsWith("!")) { if (player.getPlayer() == null || !player.getPlayer().hasPermission("freetrade.rawitems")) { throw new UsageException("You do not have permission to request raw items"); } // TODO: merge into ItemQuery! and better permissions (allow raw if is item they can trade, already exists) want = ItemQuery.codeName2ItemStack(wantString.replace("!", "")); // TODO: allow !-less raw items, but need quantity separator (.?) } else { want = (new ItemQuery(wantString, p)).itemStack; } if (giveString.startsWith("!")) { if (player.getPlayer() == null || !player.getPlayer().hasPermission("freetrade.rawitems")) { throw new UsageException("You do not have permission to request raw items"); } give = ItemQuery.codeName2ItemStack(giveString.replace("!", "")); } else { give = (new ItemQuery(giveString, p)).itemStack; } if (ItemQuery.isIdenticalItem(want, give)) { throw new UsageException("You can't trade items for themselves"); } } public Order(OfflinePlayer p, ItemStack w, ItemStack g) { player = p; want = w; give = g; } public String toString() { // TODO: pregenerate in initialization as description, no need to relookup return player.getName() + " wants " + ItemQuery.nameStack(want) + " for " + ItemQuery.nameStack(give); } // Convert to a command that can be executed to recreate the order public String serialize() { // TODO: would be nice to return a String[] instead String cmd = "want " + player.getName() + " " + ItemQuery.nameStack(want) + " " + ItemQuery.nameStack(give); return cmd; } public static Order deserialize(String s) { String[] parts = s.split(" "); if (parts.length != 4) { throw new UsageException("Invalid serialized order parts: " + s); } if (!parts[0].equals("want")) { throw new UsageException("Invalid serialized order command: " + s); } String playerString = parts[1]; String wantString = parts[2]; String giveString = parts[3]; OfflinePlayer player = Bukkit.getOfflinePlayer(playerString); if (player == null) { throw new UsageException("Sorry, player "+playerString+" not found, cannot resurrect order"); } return new Order(player, wantString, giveString); } // Required for ConcurrentSkipListSet - Comparable interface public int compareTo(Object obj) { if (!(obj instanceof Order)) { return -1; } Order rhs = (Order)obj; return toString().compareTo(rhs.toString()); //return player.getName().compareTo(rhs.player.getName()) || ItemQuery.isIdenticalStack(want, rhs.want) || ItemQuery.isIdenticalStack(give, rhs.give); } } // Exception to be reported back to player as invalid usage class UsageException extends RuntimeException { String message; public UsageException(String msg) { message = msg; } public String toString() { return "UsageException: " + message; } public String getMessage() { return message; } } // Completed order record class Transaction { OfflinePlayer playerA, playerB; ItemStack itemsA, itemsB; // received by corresponding player Timestamp whenExecuted; FreeTrade plugin; public Transaction(FreeTrade pl, OfflinePlayer pa, ItemStack a, OfflinePlayer pb, ItemStack b) { plugin = pl; playerA = pa; playerB = pb; itemsA = a; itemsB = b; // Timestamp whenExecuted = new Timestamp((new Date()).getTime()); } public String toString() { // CSV // TODO: items more easily parseable? for 3rd parties return whenExecuted + "," + playerA.getName() + "," + ItemQuery.nameStack(itemsA) + "," + playerB.getName() + "," + ItemQuery.nameStack(itemsB); } // Log to file public void log() { String filename = plugin.getDataFolder() + System.getProperty("file.separator") + "transactions.csv"; try { BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true)); writer.write(toString()); writer.newLine(); writer.close(); } catch (IOException e) { plugin.log.info("Failed to save transaction! " + e.getMessage()); } } } // TODO: ought to be a built-in class for this (or in WorldGuard?) class Zone { int minX, minZ, maxX, maxZ; public Zone(int mx, int mz, int xx, int xz) { minX = mx; minZ = mz; maxX = xx; maxZ = xz; } public Zone(List objs) { minX = ((Integer)objs.get(0)).intValue(); minZ = ((Integer)objs.get(1)).intValue(); maxX = ((Integer)objs.get(2)).intValue(); maxZ = ((Integer)objs.get(3)).intValue(); } public String toString() { return minX + "<x<" + maxX + ", " + minZ + "<z<" + maxZ; } public boolean within(Location loc) { return loc.getX() > minX && loc.getX() < maxX && loc.getZ() > minZ && loc.getZ() < maxZ; } } class Market { ConcurrentSkipListSet<Order> orders; static Logger log = Logger.getLogger("Minecraft"); Zone tradeZone = null; int tradeTerminalRadius = 0; Material tradeTerminalMaterial; ItemStack tradeTerminalBlock; FreeTrade plugin; public Market(FreeTrade pl) { orders = new ConcurrentSkipListSet<Order>(); plugin = pl; // Note: will also want to load() } public void loadConfig(YamlConfiguration config) { // TODO: figure out how to fix 'unchecked conversion' warning. getList() returns a List<Object>, so... List tradeZoneObj = config.getList("tradeZone"); if (tradeZoneObj != null) { tradeZone = new Zone(tradeZoneObj); log.info("Enforcing trade zone: " + tradeZone); } tradeTerminalRadius = config.getInt("tradeTerminalRadius"); tradeTerminalBlock = (new ItemQuery(config.getString("tradeTerminalBlock"))).itemStack; tradeTerminalMaterial = tradeTerminalBlock.getType(); // limitation: type only if (config.getBoolean("tradeTerminalCraftable")) { // Two ways to create trade terminal: // 2 enderpearls (for teleporting items, sending and receiving end) // 4 lapis lazuli ore (watery-looking material, travels through the aether) // into a sponge, sucks the items through to their destination // TODO: configurable recipes ShapelessRecipe recipe = new ShapelessRecipe(tradeTerminalBlock); recipe.addIngredient(2, Material.ENDER_PEARL); Bukkit.getServer().addRecipe(recipe); recipe = new ShapelessRecipe(tradeTerminalBlock); recipe.addIngredient(4, Material.LAPIS_ORE); Bukkit.getServer().addRecipe(recipe); } } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("Open orders:"); int i = 0; for (Order order: orders) { i += 1; sender.sendMessage(i + ". " + order); } sender.sendMessage("To add or fulfill an order:"); return false; } // Save open orders to disk public void save() { String filename = getOutstandingSaveFilename(); try { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (Order order: orders) { writer.write(order.serialize()); writer.newLine(); } writer.close(); } catch (IOException e) { log.info("Failed to save orders! " + e.getMessage()); } } // Load open orders from disk public void load() { String filename = getOutstandingSaveFilename(); try { BufferedReader reader = new BufferedReader(new FileReader(filename)); orders.clear(); String line; do { line = reader.readLine(); if (line != null) { try { Order order = Order.deserialize(line); orders.add(order); } catch (Exception e) { log.info("Bad order: " + line + " (" + e.getMessage() + "), ignored"); } } } while (line != null); reader.close(); } catch (IOException e) { log.info("Failed to load orders! " + e.getMessage()); } } private String getOutstandingSaveFilename() { return plugin.getDataFolder() + System.getProperty("file.separator") + "outstanding.txt"; } public void cancelOrder(OfflinePlayer player, String s) { if (s == null || s.equals("-")) { cancelOrders(player); return; } ItemStack wanted = (new ItemQuery(s, player)).itemStack; int i = 0; for (Order order: orders) { if (order.player.equals(player) && ItemQuery.isIdenticalItem(order.want, wanted)) { cancelOrder(order); i += 1; } } if (player.getPlayer() != null) { player.getPlayer().sendMessage("Canceled " + i + " orders"); } } // Cancel all orders for a player public void cancelOrders(OfflinePlayer player) { int i = 0; for (Order order: orders) { if (order.player.equals(player)) { cancelOrder(order); i += 1; } } if (player.getPlayer() != null) { player.getPlayer().sendMessage("Canceled all your " + i + " orders"); } } public void cancelOrder(Order order) { if (!orders.remove(order)) { for (Order o: orders) { log.info("Compare " + o + " = " + o.compareTo(order)); } throw new UsageException("Failed to find order to cancel: " + order); } Bukkit.getServer().broadcastMessage("Closed order " + order); save(); } public void placeOrder(Order order) { Player onlinePlayer = order.player.getPlayer(); if (onlinePlayer == null) { throw new UsageException("Offline player tried to place order"); } // Admin conjuring permission if (ItemQuery.isNothing(order.give)) { if (!onlinePlayer.hasPermission("freetrade.conjure")) { throw new UsageException("You must specify or select what you want to trade for"); } recvItems(order.player, order.want); return; } // Item obliteration destruction permission if (ItemQuery.isNothing(order.want)) { if (!onlinePlayer.hasPermission("freetrade.obliterate")) { throw new UsageException("You do not have permission to trade items for nothing"); // tip: throw in lava or cacti instead } takeItems(order.player, order.give); return; } // Trade restrictions if (!onlinePlayer.hasPermission("freetrade.trade")) { throw new UsageException("You are not allowed to trade"); } if (tradeZone != null && !tradeZone.within(onlinePlayer.getLocation())) { throw new UsageException("You must be within the trade zone " + tradeZone + " to trade"); } // TODO: Trade machine nearby? (if enabled) if (tradeTerminalRadius != 0) { Location location = onlinePlayer.getLocation(); World world = onlinePlayer.getWorld(); int r = tradeTerminalRadius; int ox = location.getBlockX(), oy = location.getBlockY(), oz = location.getBlockZ(); log.info("original= "+ox+","+oy+","+oz); boolean found = false; DONE: for (int x = -r; x < r; x += 1) { for (int y = -r; y < r; y += 1) { for (int z = -r; z < r; z += 1) { Block block = world.getBlockAt(x+ox, y+oy, z+oz); //log.info("blockat("+x+","+y+","+z+") = " + block); if (block.getType().equals(tradeTerminalMaterial)) { found = true; } } } } log.info("Found = " + found); if (!found) { throw new UsageException("You are not within " + tradeTerminalRadius + " blocks of a " + ItemQuery.codeName2Name.get(tradeTerminalMaterial.getId() + "") + " trading terminal"); } } // TODO: if asking for identical want, different give, then update give? (Updating orders) // Not sure, might want to try asking for all different things for same item if really want it.. // Restricted by admin? // TODO: show reason (unobtainable, blacklisted) if (!ItemQuery.isTradable(order.want)) { throw new UsageException("Trading " + ItemQuery.nameStack(order.want) + " is prohibited"); } if (!ItemQuery.isTradable(order.give)) { throw new UsageException("Trading " + ItemQuery.nameStack(order.give) + " is prohibited"); } // You can only give what you have if (!hasItems(order.player, order.give)) { throw new UsageException("You don't have " + ItemQuery.nameStack(order.give) + " to give"); } if (matchOrder(order)) { // Executed return; } // Not fulfilled; add to outstanding to match with future order // Broadcast to all players so they know someone wants something, then add Bukkit.getServer().broadcastMessage("Wanted: " + order); orders.add(order); // Save to disk on every order save(); } // Transfer items from one player to another public static void transferItems(OfflinePlayer fromPlayer, OfflinePlayer toPlayer, ItemStack items) { /* // XXX: This is very important to prevent offline failures until have exception rollback Player fromPlayer = fromPlayerOffline.getPlayer(); Player toPlayer = toPlayerOffline.getPlayer(); if (fromPlayer == null) { // TODO: open up player's .dat, edit. Offline transfers! throw new UsageException("Sorry, from player "+fromPlayer.getDisplayName()+" is offline, cannot transfer items"); } if (toPlayer == null) { // TODO: offline player support throw new UsageException("Sorry, to player "+fromPlayer.getDisplayName()+" is offline, cannot transfer items"); }*/ // Online player transfer if (!hasItems(fromPlayer, items)) { throw new UsageException("Player " + fromPlayer.getName() + " doesn't have " + ItemQuery.nameStack(items)); } int missing = -1; Exception takeException = null; try { missing = takeItems(fromPlayer, items); } catch (Exception e) { missing = -1; takeException = e; } if (missing == -1 || missing > 0) { // Rollback order // TODO: verify items.setAmount(items.getAmount() - missing); recvItems(fromPlayer, items); // TODO: try to prevent this from happening, by watching inventory changes, player death, etc if (missing > 0) { throw new UsageException("Player " + fromPlayer.getName() + " doesn't have enough " + ItemQuery.nameStack(items) + ", missing " + missing + ", reverted"); } else { throw new UsageException("Player " + fromPlayer.getName() + " could not have items taken ("+takeException.getMessage()+"), reverted"); } } try { recvItems(toPlayer, items); } catch (Exception recvException) { // Give back // TODO: this needs to be BULLETPROOF to avoid item duping recvItems(fromPlayer, items); throw new UsageException("Player " + toPlayer.getName() + " could not receive items ("+recvException.getMessage()+"), reverted"); } Bukkit.getServer().broadcastMessage(toPlayer.getName() + " received " + ItemQuery.nameStack(items) + " from " + fromPlayer.getName()); } // Remove items from player's inventory, return # of items player had < amount (insufficient items) // Based on OddItem public static int takeItems(OfflinePlayer offlinePlayer, ItemStack goners) { Player player = offlinePlayer.getPlayer(); boolean offline = player == null; if (offline) { player = loadOfflinePlayer(offlinePlayer); } int remaining = takeItemsOnline(player, goners); if (offline) { saveOfflinePlayer(player); } return remaining; } private static int takeItemsOnline(Player player, ItemStack goners) { player.saveData(); ItemStack[] inventory = player.getInventory().getContents(); int remaining = goners.getAmount(); int i = 0; for (ItemStack slot: inventory) { if (ItemQuery.isIdenticalItem(slot, goners)) { if (remaining > slot.getAmount()) { remaining -= slot.getAmount(); slot.setAmount(0); } else if (remaining > 0) { slot.setAmount(slot.getAmount() - remaining); remaining = 0; } else { slot.setAmount(0); } // If removed whole slot, need to explicitly clear it // ItemStacks with amounts of 0 are interpreted as 1 (possible Bukkit bug?) if (slot.getAmount() == 0) { player.getInventory().clear(i); } } i += 1; if (remaining == 0) { break; } } return remaining; } // Return whether player has at least the items in the stack public static boolean hasItems(OfflinePlayer offlinePlayer, ItemStack items) { Player player = offlinePlayer.getPlayer(); if (player == null) { player = loadOfflinePlayer(offlinePlayer); } return hasItemsOnline(player, items); // not saved - no changes } private static boolean hasItemsOnline(Player player, ItemStack items) { ItemStack[] inventory = player.getInventory().getContents(); int remaining = items.getAmount(); for (ItemStack slot: inventory) { if (ItemQuery.isIdenticalItem(slot, items)) { remaining -= slot.getAmount(); } } return remaining <= 0; } // Have a player receive items in their inventory public static void recvItems(OfflinePlayer offlinePlayer, ItemStack items) { Player player = offlinePlayer.getPlayer(); boolean offline = player == null; if (offline) { player = loadOfflinePlayer(offlinePlayer); } recvItemsOnline(player, items); if (offline) { saveOfflinePlayer(player); } } // Save a temporary online player object created by loadOfflinePlayer() private static void saveOfflinePlayer(Player player) { player.saveData(); // TODO: need to destroy entity? } // Load an offline player into a temporary online Player private static Player loadOfflinePlayer(OfflinePlayer player) { List<File> files = getOfflinePlayerDataFiles(player); for (File file: files) { // Load offline player .dat // see also https://github.com/lishd/OpenInv/blob/master/src/lishid/openinv/commands/OpenInvPluginCommand.java#L81 net.minecraft.server.MinecraftServer console = ((CraftServer)Bukkit.getServer()).getServer(); net.minecraft.server.ItemInWorldManager manager = new net.minecraft.server.ItemInWorldManager(console.getWorldServer(0)); net.minecraft.server.EntityPlayer entity = new net.minecraft.server.EntityPlayer( console, console.getWorldServer(0), player.getName(), manager); if (entity == null) { throw new UsageException("Failed to load offline player entity " + player.getName()); } Player onlinePlayer = (Player)entity.getBukkitEntity(); if (onlinePlayer == null) { throw new UsageException("Failed to load offline player " + player.getName()); } log.info("Found! " + onlinePlayer); // read .dat onlinePlayer.loadData(); return onlinePlayer; /* PlayerInventory inv = onlinePlayer.getInventory(); for (ItemStack slot: inv.getContents()) { log.info("slot "+slot); }*/ // TODO: multiple players? destroy other entities? //break; } throw new UsageException("Could not find offline player "+player.getName()); } // Get all player .dat files for an offline player // Searches through all worlds, so could conceivably find >1 // (with multiworld plugin? but I haven't seen any in world_nether or world_the_end) private static List<File> getOfflinePlayerDataFiles(OfflinePlayer player) { List<File> playerFiles = new ArrayList<File>(1); String thisPlayerName = player.getName(); List<World> worlds = Bukkit.getWorlds(); for (World world: worlds) { File players = new File(world.getWorldFolder(), "players"); for (File playerFile: players.listFiles()) { String playerName = playerFile.getName().replaceFirst("\\.dat$", ""); if (playerName.trim().equalsIgnoreCase(thisPlayerName)) { playerFiles.add(playerFile); } } } return playerFiles; } private static void recvItemsOnline(Player player, ItemStack items) { int remaining = items.getAmount(); // Get maximum size per stack, then add individually // Prevents non-stackable items (potions, signs, boats, etc.) and semi-stackable // (enderpearls, eggs, snowballs, etc.) from being stacked to 64 int stackSize; if (player.hasPermission("freetrade.bigstacks")) { stackSize = remaining; } else { stackSize = Math.abs(items.getType().getMaxStackSize()); // Surprisingly, this always returns -1, see http://forums.bukkit.org/threads/getmaxstacksize-always-return-1.1154/#post-13147 //int stackSize = Math.abs(items.getMaxStackSize()); } // TODO: optional "huge stacks", beyond 64. setAmount(200) in inventory slot. Seems to work. do { int amount; if (remaining > stackSize) { amount = stackSize; remaining -= stackSize; } else { amount = remaining; remaining = 0; } // https://bukkit.atlassian.net/browse/BUKKIT-621 // ItemStack cannot clone all items, uses addEnchantment instead of addUnsafeEnchantment //ItemStack oneStack = items.clone(); // Workaround: clone ourselves ItemStack oneStack = new ItemStack(items.getTypeId(), amount, items.getDurability()); oneStack.addUnsafeEnchantments(items.getEnchantments()); // This fails with NPE on invalid items (/w !123) (TODO: bug report, null check) // public void setData(int i) { // this.damage = (this.id > 0) && (this.id < 256) ? Item.byId[this.id].filterData(i) : i; // CraftBukkit // } // Item.byId isn't defined for invalid items.. // -but- it does work for new items (CB modded with IC2, try /w !233 HashMap<Integer,ItemStack> excess = player.getInventory().addItem(oneStack); // If player's inventory if full, drop excess items on the floor Iterator it = excess.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); int unknown = ((Integer)pair.getKey()).intValue(); // hmm? always 0 ItemStack excessItems = (ItemStack)pair.getValue(); player.getWorld().dropItemNaturally(player.getLocation(), excessItems); } } while (remaining > 0); // How did the items transport themselves between the players? Magic, as indicated by smoke. // (Note only smoke on receiving end, and only if receiving player is online) player.playEffect(player.getLocation(), Effect.SMOKE, 0); } public boolean matchOrder(Order newOrder) { int i = 0; for (Order oldOrder: orders) { i += 1; //log.info("oldOrder: " + oldOrder); //log.info("newOrder: " + newOrder); // Are they giving what anyone else wants? if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) || !ItemQuery.isSameType(newOrder.want, oldOrder.give)) { log.info("Not matched, different types"); continue; } double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount(); double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount(); // Offering a better or equal deal? (Quantity = relative value) log.info("ratio " + newRatio + " >= " + oldRatio); if (!(newRatio >= oldRatio)) { log.info("Not matched, worse relative value"); continue; } // TODO: refactor into ItemStackX compareTo(), so can check if item is 'better than' other item // Generalized to 'betterness' // Is item less damaged or equally damaged than wanted? (Durability) if (ItemQuery.isDurable(newOrder.give.getType())) { if (newOrder.give.getDurability() > oldOrder.want.getDurability()) { log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability()); continue; } } if (ItemQuery.isDurable(oldOrder.give.getType())) { if (oldOrder.give.getDurability() > newOrder.want.getDurability()) { log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability()); continue; } } // Does the item have at least the enchantments and levels that are wanted? (Enchantments) if (ItemQuery.isEnchantable(newOrder.give.getType())) { if (!EnchantQuery.equalOrBetter(newOrder.give, oldOrder.want)) { log.info("Not matched, insufficient magic new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) + " < " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments())); continue; } } else { // Not legitimately enchantmentable, means enchant is used as a 'subtype', just like // damage is if !isDurable, so match exactly. if (!EnchantQuery.nameEnchs(newOrder.give.getEnchantments()).equals( EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()))) { log.info("Not matched, non-identical enchantments new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) + " != " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments())); continue; } } if (ItemQuery.isEnchantable(oldOrder.give.getType())) { if (!EnchantQuery.equalOrBetter(oldOrder.give, newOrder.want)) { log.info("Not matched, insufficient magic old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) + " < " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments())); continue; } } else { if (!EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()).equals( EnchantQuery.nameEnchs(newOrder.want.getEnchantments()))) { log.info("Not matched, non-identical enchantments old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) + " != " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments())); continue; } } // Determine how much of the order can be fulfilled int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount(); int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount(); log.info("remaining want="+remainingWant+", give="+remainingGive); // They get what they want! // Calculate amount that can be exchanged ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability()); ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability()); exchWant.addUnsafeEnchantments(newOrder.give.getEnchantments()); exchGive.addUnsafeEnchantments(oldOrder.give.getEnchantments()); log.info("exchWant="+ItemQuery.nameStack(exchWant)); log.info("exchGive="+ItemQuery.nameStack(exchGive)); transferItems(newOrder.player, oldOrder.player, exchWant); transferItems(oldOrder.player, newOrder.player, exchGive); Transaction t = new Transaction(plugin, oldOrder.player, exchWant, newOrder.player, exchGive); t.log(); /* oldOrder.player.getInventory().addItem(exchWant); newOrder.player.getInventory().remove(exchWant); Bukkit.getServer().broadcastMessage(oldOrder.player.getDisplayName() + " received " + ItemQuery.nameStack(exchWant) + " from " + newOrder.player.getDisplayName()); newOrder.player.getInventory().addItem(exchGive); oldOrder.player.getInventory().remove(exchGive); Bukkit.getServer().broadcastMessage(newOrder.player.getDisplayName() + " received " + ItemQuery.nameStack(exchGive) + " from " + oldOrder.player.getDisplayName()); */ // Remove oldOrder from orders, if complete, or add partial if incomplete if (remainingWant == 0) { // This order is finished, old player got everything they wanted // Note: remainingWant can be negative if they got more than they bargained for // (other player offered a better deal than expected). Either way, done deal. cancelOrder(oldOrder); return true; } else if (remainingWant > 0) { oldOrder.want.setAmount(remainingWant); oldOrder.give.setAmount(remainingGive); Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder); return true; } else if (remainingWant < 0) { // TODO: test better cancelOrder(oldOrder); newOrder.want.setAmount(-remainingGive); newOrder.give.setAmount(-remainingWant); log.info("Adding new partial order"); return false; } } return false; } } // Watch trader for things they might to do invalidate their orders class TraderListener implements Listener { Logger log = Logger.getLogger("Minecraft"); Market market; FreeTrade plugin; public TraderListener(FreeTrade pl, Market m) { plugin = pl; market = m; Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerDropItem(PlayerDropItemEvent event) { // Re-validate order, see if they dropped an item they were going to give for (Order order: market.orders) { // TODO: hash lookup of player? Performance if (order.player.equals(event.getPlayer())) { if (!Market.hasItems(order.player, order.give)) { if (order.player.getPlayer() != null) { order.player.getPlayer().sendMessage("Order invalidated by item drop"); } market.cancelOrder(order); } } } } // TODO: player death, drop events // TODO: player an item, changes damage, or uses up (either way invalidates order) } public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); Market market; YamlConfiguration config; TraderListener listener; public void onEnable() { market = new Market(this); loadConfig(); market.load(); listener = new TraderListener(this, market); log.info(getDescription().getName() + " enabled"); } public void onDisable() { market.save(); log.info(getDescription().getName() + " disabled"); } public void loadConfig() { String filename = getDataFolder() + System.getProperty("file.separator") + "FreeTrade.yml"; File file = new File(filename); if (!file.exists()) { if (!newConfig(file)) { throw new UsageException("Could not create new configuration file"); } } config = YamlConfiguration.loadConfiguration(new File(filename)); if (config == null) { throw new UsageException("Failed to load configuration file " + filename); } if (config.getInt("version") < 1) { throw new UsageException("Configuration file version is outdated"); } EnchantQuery.loadConfig(config); ItemQuery.loadConfig(config); market.loadConfig(config); } // Copy default configuration public boolean newConfig(File file) { FileWriter fileWriter; if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } try { fileWriter = new FileWriter(file); } catch (IOException e) { log.severe("Couldn't write config file: " + e.getMessage()); Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade")); return false; } BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(getResource("FreeTrade.yml")))); BufferedWriter writer = new BufferedWriter(fileWriter); try { String line = reader.readLine(); while (line != null) { writer.write(line + System.getProperty("line.separator")); line = reader.readLine(); } log.info("Wrote default config"); } catch (IOException e) { log.severe("Error writing config: " + e.getMessage()); } finally { try { writer.close(); reader.close(); } catch (IOException e) { log.severe("Error saving config: " + e.getMessage()); Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade")); } } return true; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; int n = 0; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return market.showOutstanding(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // Get player name from first argument player = Bukkit.getServer().getPlayer(args[0]); if (player == null) { sender.sendMessage("no such player"); return false; } n++; } if (args.length < 1+n) { return false; } String wantString, giveString; wantString = args[n]; if (args.length < 2+n) { // Omitted last arg, use item in hand giveString = "this"; } else if (args.length > 2+n) { // Too many args, don't try to interpret return false; } else { if (args[n+1].equalsIgnoreCase("for")) { giveString = args[n+2]; } else { giveString = args[n+1]; } } Order order; try { if (wantString.equals("-")) { log.info("cancelall"); market.cancelOrder(player, null); } else if (giveString.equals("-")) { market.cancelOrder(player, wantString); } else { order = new Order(player, wantString, giveString); sender.sendMessage(order.toString()); market.placeOrder(order); } } catch (UsageException e) { log.info("Sending usage exception: " + player.getDisplayName() + " - " + e ); player.sendMessage(e.getMessage()); return false; } return true; } }
FreeTrade.java
package me.exphc.FreeTrade; import java.util.logging.Logger; import java.util.regex.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.SortedSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.Date; import java.sql.Timestamp; import java.io.*; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.command.*; import org.bukkit.entity.*; import org.bukkit.inventory.*; import org.bukkit.enchantments.*; import org.bukkit.configuration.*; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.player.*; import org.bukkit.event.*; import org.bukkit.block.*; import org.bukkit.*; import info.somethingodd.bukkit.OddItem.OddItem; import org.bukkit.craftbukkit.CraftServer; import net.minecraft.server.MinecraftServer; import net.minecraft.server.EntityPlayer; import net.minecraft.server.ItemInWorldManager; enum Obtainability { NORMAL, SILKTOUCH, CREATIVE, HACKING, NEVER }; class ItemQuery { ItemStack itemStack; static Logger log = Logger.getLogger("Minecraft"); // Map between item names/aliases and id;dmg string // TODO: switch to more appropriate data structures, ItemStacks? static ConcurrentHashMap<String,String> name2CodeName; static ConcurrentHashMap<String,String> codeName2Name; // TODO: switch to sets static ConcurrentHashMap<String,Boolean> isTradableMap; static ConcurrentHashMap<Material,Boolean> isDurableMap; static ConcurrentHashMap<Material,Boolean> isEnchantableMap; static ConcurrentHashMap<Material,Boolean> isCountableMap; public ItemQuery(String s) { //Pattern onp = Pattern.compile( "^(\\d+)" Pattern p = Pattern.compile( "^(\\d*)" + // quantity "([# :;-]?)" + // separator / stack flag "([^/\\\\]+)" + // name "([/\\\\]?)" + // separator / damage flag "([\\d%]*)" + // use / damage "/?([^/]*)$"); // enchant Matcher m = p.matcher(s); int quantity; if (!m.find()) { throw new UsageException("Unrecognized item specification: " + s); } String quantityString = m.group(1); String isStackString = m.group(2); String nameString = m.group(3); String dmgOrUsesString = m.group(4); String usesString = m.group(5); String enchString = m.group(6); if (quantityString.equals("")) { quantity = 1; } else { quantity = Integer.parseInt(quantityString); if (quantity < 1) { throw new UsageException("Invalid quantity: " + quantity); } } // Name // Allowed to be any case, with or without any word separators nameString = nameString.replaceAll("[ _-]", "").toLowerCase(); if (nameString.contains("*")) { // Wildcard expressions SortedSet<String> results = wildcardLookupName(nameString); if (results.size() == 0) { throw new UsageException("No items match pattern " + nameString); } if (results.size() > 1) { StringBuffer nameMatches = new StringBuffer(); for (String resultName: results) { nameMatches.append(resultName + ", "); } throw new UsageException("Found " + results.size() + " matching items: " + nameMatches); } // Exactly one hit, use it nameString = results.first().toLowerCase(); } // First try built-in name lookup itemStack = directLookupName(nameString); if (itemStack == null) { // If available, try OddItem for better names or clever suggestions if (Bukkit.getServer().getPluginManager().getPlugin("OddItem") != null) { try { itemStack = OddItem.getItemStack(nameString).clone(); } catch (IllegalArgumentException suggestion) { throw new UsageException("No such item '" + nameString + "', did you mean '" + suggestion.getMessage() + "'?"); } } else { // Worst case, lookup name from Bukkit itself // Not very good because doesn't include damage value subtypes Material material = Material.matchMaterial(nameString); if (material == null) { throw new UsageException("Unrecognized item name: " + nameString + " (no suggestions available)"); } itemStack = new ItemStack(material); } } if (itemStack == null) { throw new UsageException("Unrecognized item name: " + nameString); } // Quantity, shorthand 10# = 10 stacks if (isStackString.equals("#")) { quantity *= Math.abs(itemStack.getType().getMaxStackSize()); } itemStack.setAmount(quantity); // Damage value aka durability // User specifies how much they want left, 100% = unused tool short maxDamage = itemStack.getType().getMaxDurability(); if (usesString != null && !usesString.equals("")) { short damage; short value; if (isCountable(itemStack.getType()) || !isDurable(itemStack.getType())) { // Countable items specify damage directly // -or- non-durable items // TODO: restrict setting durability on non-durable items?? admin function if (!isDurable(itemStack.getType())) { log.info("Warning: setting durability on non-durable item "+nameStack(itemStack)); } damage = Short.parseShort(usesString); // TODO: clamp? for maps at least, if request beyond last + 2, will give last + 1 // but, if request last + 1, then will create a new map in that slot } else { // Tools - uses, percentages if (usesString.endsWith("%")) { String percentageString = usesString.substring(0, usesString.length() - 1); double percentage = Double.parseDouble(percentageString); value = (short)(percentage / 100.0 * maxDamage); } else { value = Short.parseShort(usesString); } // Normally, convenient for user to specify percent or times left (inverse of damage), / // Allow \ separator to specify damage itself if (dmgOrUsesString.equals("\\")) { damage = value; } else { damage = (short)(maxDamage - value); } if (damage > maxDamage) { damage = maxDamage; // Breaks right after one use } if (damage < 0) { damage = 0; // Completely unused } } itemStack.setDurability(damage); } else { // If they didn't specify a durability, but they want a durable item, assume no damage (0) // TODO: only assume 0 for wants. For gives, need to use value from inventory! Underspecified } // Enchantments if (enchString != null && !enchString.equals("")) { // TODO: rethink enchantable and other item subtype permissions // Should always be expressible as new ItemQuery(), but may want to restrict // based on player permissions what they can trade /* if (!isEnchantable(itemStack.getType())) { throw new UsageException("Not enchantable"); // TODO: allow permission to override, if want e.g. enchanted shears for testing }*/ EnchantQuery enchs = new EnchantQuery(enchString); itemStack.addUnsafeEnchantments(enchs.all); } } public ItemQuery(String s, OfflinePlayer p) { if (s.equals("this")) { if (p.getPlayer() == null) { throw new UsageException("Cannot specify 'this' on offline player"); } itemStack = p.getPlayer().getItemInHand().clone(); if (itemStack == null) { throw new UsageException("No item in hand"); } } else { itemStack = (new ItemQuery(s)).itemStack; } } // Return whether an item degrades when used public static boolean isDurable(Material m) { if (m == null) return false; // TODO: non-standard items return isDurableMap.containsKey(m); } // Return whether an item can be legitimately enchanted public static boolean isEnchantable(Material m) { if (m == null) return false; // TODO: non-standard items return isEnchantableMap.containsKey(m); } // Return whether an item is numbered, like maps in vanilla (map0, map1..) public static boolean isCountable(Material m) { if (m == null) return false; // TODO: non-standard items return isCountableMap.containsKey(m); } public static String nameStack(ItemStack itemStack) { if (isNothing(itemStack)) { return "nothing"; } String name, usesString, enchString; Material m = itemStack.getType(); if (isDurable(m)) { // Percentage remaining // Round down so '100%' always means completely unused? (1 dmg = 99%) //int percentage = Math.round(Math.floor((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability())) // but then lower percentages are always one lower.. // So just special-case 100% to avoid misleading int percentage; if (itemStack.getDurability() == 0) { percentage = 100; } else { percentage = (int)((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability()); if (percentage == 100) { percentage = 99; } } usesString = "/" + percentage + "%"; } else { usesString = ""; } // Find canonical name of item String codeName; codeName = itemStack.getTypeId() + ""; name = codeName2Name.get(codeName); if (name == null) { // durability here actually is overloaded to mean a different item codeName = itemStack.getTypeId() + ";" + itemStack.getDurability(); name = codeName2Name.get(codeName); } if (name == null) { name = "unknown="+codeName; } // Countable items are numbered (map/0, map/1...) if (isCountable(itemStack.getType())) { name += "/" + itemStack.getDurability(); } // Enchantments if (EnchantQuery.hasEnchantments(itemStack)) { Map<Enchantment,Integer> enchs = itemStack.getEnchantments(); enchString = "/" + EnchantQuery.nameEnchs(enchs); } else { enchString = ""; } return itemStack.getAmount() + ":" + name + usesString + enchString; } // Return whether two item stacks have the same item, taking into account 'subtypes' // stored in the damage value (ex: blue wool, only same as blue wool) - but will // ignore damage for durable items (ex: diamond sword, 50% = diamond sword, 100%) public static boolean isSameType(ItemStack a, ItemStack b) { if (a.getType() != b.getType()) { return false; } Material m = a.getType(); if (isDurable(m)) { return true; } return a.getDurability() == b.getDurability(); } // Return whether two item stacks are identical - except for amount! // Compares type, durability, enchantments public static boolean isIdenticalItem(ItemStack a, ItemStack b) { if (a == null || b == null) { return false; } if (a == null && b == null) { return true; } if (a.getType() != b.getType()) { return false; } // Same subtype -or- durability for tools if (a.getDurability() != b.getDurability()) { return false; } // Same enchantments // Compare by name to avoid complex duplicate enchantment traversing code String enchNameA = EnchantQuery.nameEnchs(a.getEnchantments()); String enchNameB = EnchantQuery.nameEnchs(b.getEnchantments()); if (!enchNameA.equals(enchNameB)) { return false; } return true; } // Identical and same amounts too public static boolean isIdenticalStack(ItemStack a, ItemStack b) { return isIdenticalItem(a, b) && a.getAmount() == b.getAmount(); } // Return whether item is configured to be allowed to be traded public static boolean isTradable(ItemStack items) { // Durability always stored, but 0 for durable items return isTradableMap.containsKey(items.getTypeId() + ";" + (isDurable(items.getType()) ? 0 : items.getDurability())); } // Configuration public static void loadConfig(YamlConfiguration config) { Map<String,Object> configValues = config.getValues(true); MemorySection itemsSection = (MemorySection)configValues.get("items"); int i = 0; name2CodeName = new ConcurrentHashMap<String, String>(); codeName2Name = new ConcurrentHashMap<String, String>(); isDurableMap = new ConcurrentHashMap<Material, Boolean>(); isEnchantableMap = new ConcurrentHashMap<Material, Boolean>(); isCountableMap = new ConcurrentHashMap<Material, Boolean>(); ConcurrentHashMap<String,Boolean> isTradableMapUnfiltered = new ConcurrentHashMap<String, Boolean>(); HashSet<Obtainability> tradableCategories = new HashSet<Obtainability>(); for (String obtainString: config.getStringList("tradableCategories")) { tradableCategories.add(Obtainability.valueOf(obtainString.toUpperCase())); } for (String codeName: itemsSection.getKeys(false)) { String properName = config.getString("items." + codeName + ".name"); // How this item can be obtained String obtainString = config.getString("items." + codeName + ".obtain"); Obtainability obtain = (obtainString == null) ? Obtainability. NORMAL : Obtainability.valueOf(obtainString.toUpperCase()); boolean tradable = tradableCategories.contains(obtain); // TODO: whitelist, blacklist (with wildcards! search) if (tradable) { isTradableMapUnfiltered.put(codeName.contains(";") ? codeName : codeName + ";0", tradable); } // Add aliases from config List<String> aliases = config.getStringList("items." + codeName + ".aliases"); if (aliases != null) { for (String alias: aliases) { name2CodeName.put(alias, codeName); i += 1; } } // Generate 'proper name' alias, preprocessed for lookup String smushedProperName = properName.replaceAll(" ",""); String aliasProperName = smushedProperName.toLowerCase(); name2CodeName.put(aliasProperName, codeName); i += 1; codeName2Name.put(codeName, smushedProperName); // Generate numeric alias name2CodeName.put(codeName, codeName); i += 1; // Whether loses durability when used or not (include in trades) String purpose = config.getString("items." + codeName + ".purpose"); Material material = codeName2ItemStack(codeName).getType(); boolean durable = purpose != null && (purpose.equals("armor") || purpose.equals("tool") || purpose.equals("weapon")); if (durable) { isDurableMap.put(material, new Boolean(true)); } // Items are enchantable if durable, unless overridden (for shears, etc.) boolean enchantable = config.getBoolean("items." + codeName + ".enchant", durable); if (enchantable) { isEnchantableMap.put(material, new Boolean(true)); } if (config.getBoolean("items." + codeName + ".count", false)) { isCountableMap.put(material, new Boolean(true)); } } log.info("Loaded " + i + " item aliases"); // Whitelist tradable items for (String whiteString: config.getStringList("tradableWhitelist")) { ItemStack itemStack = directLookupName(whiteString); isTradableMapUnfiltered.put(itemStack.getTypeId() + ";" + itemStack.getDurability(), true); } // Filter through blacklist isTradableMap = new ConcurrentHashMap<String, Boolean>(); SKIP: for (String tradableCodeName: isTradableMapUnfiltered.keySet()) { // Is this blacklisted? for (String blackString: config.getStringList("tradableBlacklist")) { ItemStack itemStack = directLookupName(blackString); if (tradableCodeName.equals(itemStack.getTypeId() + ";" + itemStack.getDurability())) { continue SKIP; } } // No, add to real list isTradableMap.put(tradableCodeName, true); } } // Parse a material code string with optional damage value (ex: 35;11) public static ItemStack codeName2ItemStack(String codeName) { Pattern p = Pattern.compile("^(\\d+)[;:/]?(\\d*)([+]?.*)$"); Matcher m = p.matcher(codeName); int typeCode; short dmgCode; if (!m.find()) { // This is an error in the config file (TODO: preparse or detect earlier) throw new UsageException("Invalid item code format: " + codeName); } // typeid typeCode = Integer.parseInt(m.group(1)); // ;damagevalue if (m.group(2) != null && !m.group(2).equals("")) { dmgCode = Short.parseShort(m.group(2)); } else { dmgCode = 0; } ItemStack item = new ItemStack(typeCode, 1, dmgCode); // +enchantcode@enchantlevel... if (m.group(3) != null && !m.group(3).equals("")) { String[] parts = m.group(3).split("[+]"); for (String part: parts) { if (part.length() == 0) { continue; } String[] idAndLevel = part.split("@"); if (idAndLevel.length != 2) { throw new UsageException("Invalid item code: " + codeName + ", enchantment spec: " + part); } int id, level; try { id = Integer.parseInt(idAndLevel[0]); level = Integer.parseInt(idAndLevel[1]); } catch (Exception e) { throw new UsageException("Invalid item code: " + codeName + ", enchantment id/level: " + part); } Enchantment ench = Enchantment.getById(id); // Add unsafe, since plugins might want to (ab)use enchantment for other purposes item.addUnsafeEnchantment(ench, level); } } return item; } // Get an ItemStack directly from one of its names or aliases, or null private static ItemStack directLookupName(String nameString) { String materialCode = name2CodeName.get(nameString); if (materialCode == null) { return null; } return codeName2ItemStack(materialCode); } // Get proper names of all aliases matching a wildcard pattern private static SortedSet<String> wildcardLookupName(String pattern) { SortedSet<String> results = new TreeSet<String>(); Iterator it = name2CodeName.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); String name = (String)pair.getKey(); String codeName = (String)pair.getValue(); if (matchesWildcard(pattern, name) && isTradableMap.containsKey(codeName)) { results.add(codeName2Name.get(codeName).replace(" ","")); } } return results; } // Return whether a wildcard pattern (with asterisks = anything) matches private static boolean matchesWildcard(String needle, String haystack) { String[] cards = needle.split("\\*"); for (String card : cards) { int i = haystack.indexOf(card); if (i == -1) { return false; } haystack = haystack.substring(i + card.length()); } return true; } public static boolean isNothing(ItemStack itemStack) { return itemStack == null || itemStack.getType() == Material.AIR; } } class EnchantQuery { static Logger log = Logger.getLogger("Minecraft"); Map<Enchantment,Integer> all; static ConcurrentHashMap<String, Enchantment> name2Code; static ConcurrentHashMap<Enchantment, String> code2Name; public EnchantQuery(String allString) { all = new HashMap<Enchantment,Integer>(); String[] enchStrings = allString.split("[, /-]+"); for (String enchString: enchStrings) { Pattern p = Pattern.compile("^([A-Za-z-]*[a-z])([IV0-9]*)$"); Matcher m = p.matcher(enchString); if (!m.find()) { throw new UsageException("Unrecognizable enchantment: '" + enchString + "'"); } String baseName = m.group(1); String levelString = m.group(2); Enchantment ench = enchFromBaseName(baseName); int level = levelFromString(levelString); // Odd, what's the point of having a separate 'wrapper' class? // Either way, it has useful methods for us //EnchantmentWrapper enchWrapper = new EnchantmentWrapper(ench.getId()); EnchantmentWrapper enchWrapper = wrapEnch(ench); // TODO: restrict max level? need to figure out permissions here // sometimes (often), exceeding the "max" is useful if (level > enchWrapper.getMaxLevel()) { log.info("Warning: exceeding max level enchantment "+ench+" "+level+" > " + enchWrapper.getMaxLevel()); //level = ench.getMaxLevel(); } log.info("Enchantment: " + ench + ", level="+level); all.put(enchWrapper, new Integer(level)); } } // Return whether all the enchantments can apply to an item public boolean canEnchantItem(ItemStack item) { Iterator it = all.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); EnchantmentWrapper ench = wrapEnch(pair.getKey()); Integer level = (Integer)pair.getValue(); if (!ench.canEnchantItem(item)) { log.info("Cannot apply enchantment " + ench + " to " + item); return false; } } return true; } public static boolean hasEnchantments(ItemStack item) { Map<Enchantment,Integer> enchs = item.getEnchantments(); return enchs.size() != 0; } public String toString() { return nameEnchs(all); } public static String nameEnchs(Map<Enchantment,Integer> all) { StringBuffer names = new StringBuffer(); Iterator it = all.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); Object obj = pair.getKey(); EnchantmentWrapper ench = wrapEnch(pair.getKey()); Integer level = (Integer)pair.getValue(); names.append(nameEnch(ench)); names.append(levelToString(level)); names.append(","); } // Remove the trailing comma // Would have liked to just build an array then join it, but not easier in Java either if (names.length() > 1) { names.deleteCharAt(names.length() - 1); } return names.toString(); } // Get an EnchantmentWrapper from either an EnchantmentWrapper or Enchantment // Not sure why Bukkit chose to have two classes, but EnchantmentWrapper is more functional public static EnchantmentWrapper wrapEnch(Object obj) { if (obj instanceof EnchantmentWrapper) { return (EnchantmentWrapper)obj; } Enchantment ench = (Enchantment)obj; return new EnchantmentWrapper(ench.getId()); } static Enchantment enchFromBaseName(String name) { // Built-in config file database.. name = name.toLowerCase(); Enchantment ench = name2Code.get(name); if (ench != null) { return ench; } // Bukkit itself? ench = Enchantment.getByName(name); if (ench != null) { return ench; } throw new UsageException("Unrecognized enchantment: " + name); } static String nameEnch(EnchantmentWrapper ench) { String name = code2Name.get(ench); if (name != null) { return name; } return "Unknown(" + ench.getId() + ")"; // There is ench.getName(), but the names don't match in-game } static int levelFromString(String s) { if (s.equals("") || s.equals("I")) { return 1; } else if (s.equals("II")) { return 2; } else if (s.equals("III")) { return 3; } else if (s.equals("IV")) { return 4; } else if (s.equals("V")) { return 5; } else { return Integer.parseInt(s); } } static String levelToString(int n) { switch (n) { case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; default: return Integer.toString(n); } } // Return wheather itemA has >= enchantments than itemB public static boolean equalOrBetter(ItemStack itemA, ItemStack itemB) { Map<Enchantment,Integer> enchsB = itemB.getEnchantments(); Iterator it = enchsB.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); EnchantmentWrapper enchB = (EnchantmentWrapper)pair.getKey(); int levelB = ((Integer)pair.getValue()).intValue(); if (!itemA.containsEnchantment(Enchantment.getById(enchB.getId()))) { log.info("Missing enchantment " + nameEnch(enchB) + " not on " + itemA + " (doesn't match " + itemB + ")"); return false; } int levelA = itemA.getEnchantmentLevel(Enchantment.getById(enchB.getId())); log.info("Level " + levelB + " vs " + levelA); if (levelA < levelB) { log.info("Lower enchantment level " + levelA + " < " + levelB); return false; } } return true; } public static void loadConfig(YamlConfiguration config) { Map<String,Object> configValues = config.getValues(true); MemorySection enchantsSection = (MemorySection)configValues.get("enchants"); int i = 0; name2Code = new ConcurrentHashMap<String, Enchantment>(); code2Name = new ConcurrentHashMap<Enchantment, String>(); for (String codeString: enchantsSection.getKeys(false)) { Enchantment ench = Enchantment.getById(Integer.parseInt(codeString)); String properName = config.getString("enchants." + codeString + ".name"); List<String> aliases = config.getStringList("enchants." + codeString + ".aliases"); if (aliases != null) { for (String alias: aliases) { name2Code.put(alias, ench); i += 1; } } // Generate 'proper name' alias, preprocessed for lookup String smushedProperName = properName.replaceAll(" ",""); String aliasProperName = smushedProperName.toLowerCase(); name2Code.put(aliasProperName, ench); i += 1; code2Name.put(ench, smushedProperName); } log.info("Loaded " + i + " enchantment aliases"); } } class Order implements Comparable { OfflinePlayer player; ItemStack want, give; boolean free; public Order(OfflinePlayer p, String wantString, String giveString) { player = p; if (wantString.startsWith("!")) { if (player.getPlayer() == null || !player.getPlayer().hasPermission("freetrade.rawitems")) { throw new UsageException("You do not have permission to request raw items"); } // TODO: merge into ItemQuery! and better permissions (allow raw if is item they can trade, already exists) want = ItemQuery.codeName2ItemStack(wantString.replace("!", "")); // TODO: allow !-less raw items, but need quantity separator (.?) } else { want = (new ItemQuery(wantString, p)).itemStack; } if (giveString.startsWith("!")) { if (player.getPlayer() == null || !player.getPlayer().hasPermission("freetrade.rawitems")) { throw new UsageException("You do not have permission to request raw items"); } give = ItemQuery.codeName2ItemStack(giveString.replace("!", "")); } else { give = (new ItemQuery(giveString, p)).itemStack; } if (ItemQuery.isIdenticalItem(want, give)) { throw new UsageException("You can't trade items for themselves"); } } public Order(OfflinePlayer p, ItemStack w, ItemStack g) { player = p; want = w; give = g; } public String toString() { // TODO: pregenerate in initialization as description, no need to relookup return player.getName() + " wants " + ItemQuery.nameStack(want) + " for " + ItemQuery.nameStack(give); } // Convert to a command that can be executed to recreate the order public String serialize() { // TODO: would be nice to return a String[] instead String cmd = "want " + player.getName() + " " + ItemQuery.nameStack(want) + " " + ItemQuery.nameStack(give); return cmd; } public static Order deserialize(String s) { String[] parts = s.split(" "); if (parts.length != 4) { throw new UsageException("Invalid serialized order parts: " + s); } if (!parts[0].equals("want")) { throw new UsageException("Invalid serialized order command: " + s); } String playerString = parts[1]; String wantString = parts[2]; String giveString = parts[3]; OfflinePlayer player = Bukkit.getOfflinePlayer(playerString); if (player == null) { throw new UsageException("Sorry, player "+playerString+" not found, cannot resurrect order"); } return new Order(player, wantString, giveString); } // Required for ConcurrentSkipListSet - Comparable interface public int compareTo(Object obj) { if (!(obj instanceof Order)) { return -1; } Order rhs = (Order)obj; return toString().compareTo(rhs.toString()); //return player.getName().compareTo(rhs.player.getName()) || ItemQuery.isIdenticalStack(want, rhs.want) || ItemQuery.isIdenticalStack(give, rhs.give); } } // Exception to be reported back to player as invalid usage class UsageException extends RuntimeException { String message; public UsageException(String msg) { message = msg; } public String toString() { return "UsageException: " + message; } public String getMessage() { return message; } } // Completed order record class Transaction { OfflinePlayer playerA, playerB; ItemStack itemsA, itemsB; // received by corresponding player Timestamp whenExecuted; FreeTrade plugin; public Transaction(FreeTrade pl, OfflinePlayer pa, ItemStack a, OfflinePlayer pb, ItemStack b) { plugin = pl; playerA = pa; playerB = pb; itemsA = a; itemsB = b; // Timestamp whenExecuted = new Timestamp((new Date()).getTime()); } public String toString() { // CSV // TODO: items more easily parseable? for 3rd parties return whenExecuted + "," + playerA.getName() + "," + ItemQuery.nameStack(itemsA) + "," + playerB.getName() + "," + ItemQuery.nameStack(itemsB); } // Log to file public void log() { String filename = plugin.getDataFolder() + System.getProperty("file.separator") + "transactions.csv"; try { BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true)); writer.write(toString()); writer.newLine(); writer.close(); } catch (IOException e) { plugin.log.info("Failed to save transaction! " + e.getMessage()); } } } // TODO: ought to be a built-in class for this (or in WorldGuard?) class Zone { int minX, minZ, maxX, maxZ; public Zone(int mx, int mz, int xx, int xz) { minX = mx; minZ = mz; maxX = xx; maxZ = xz; } public Zone(List objs) { minX = ((Integer)objs.get(0)).intValue(); minZ = ((Integer)objs.get(1)).intValue(); maxX = ((Integer)objs.get(2)).intValue(); maxZ = ((Integer)objs.get(3)).intValue(); } public String toString() { return minX + "<x<" + maxX + ", " + minZ + "<z<" + maxZ; } public boolean within(Location loc) { return loc.getX() > minX && loc.getX() < maxX && loc.getZ() > minZ && loc.getZ() < maxZ; } } class Market { ConcurrentSkipListSet<Order> orders; static Logger log = Logger.getLogger("Minecraft"); Zone tradeZone = null; int tradeTerminalRadius = 0; Material tradeTerminalMaterial; ItemStack tradeTerminalBlock; FreeTrade plugin; public Market(FreeTrade pl) { orders = new ConcurrentSkipListSet<Order>(); plugin = pl; // Note: will also want to load() } public void loadConfig(YamlConfiguration config) { // TODO: figure out how to fix 'unchecked conversion' warning. getList() returns a List<Object>, so... List tradeZoneObj = config.getList("tradeZone"); if (tradeZoneObj != null) { tradeZone = new Zone(tradeZoneObj); log.info("Enforcing trade zone: " + tradeZone); } tradeTerminalRadius = config.getInt("tradeTerminalRadius"); tradeTerminalBlock = (new ItemQuery(config.getString("tradeTerminalBlock"))).itemStack; tradeTerminalMaterial = tradeTerminalBlock.getType(); // limitation: type only if (config.getBoolean("tradeTerminalCraftable")) { // Two ways to create trade terminal: // 2 enderpearls (for teleporting items, sending and receiving end) // 4 lapis lazuli ore (watery-looking material, travels through the aether) // into a sponge, sucks the items through to their destination // TODO: configurable recipes ShapelessRecipe recipe = new ShapelessRecipe(tradeTerminalBlock); recipe.addIngredient(2, Material.ENDER_PEARL); Bukkit.getServer().addRecipe(recipe); recipe = new ShapelessRecipe(tradeTerminalBlock); recipe.addIngredient(4, Material.LAPIS_ORE); Bukkit.getServer().addRecipe(recipe); } } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("Open orders:"); int i = 0; for (Order order: orders) { i += 1; sender.sendMessage(i + ". " + order); } sender.sendMessage("To add or fulfill an order:"); return false; } // Save open orders to disk public void save() { String filename = getOutstandingSaveFilename(); try { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (Order order: orders) { writer.write(order.serialize()); writer.newLine(); } writer.close(); } catch (IOException e) { log.info("Failed to save orders! " + e.getMessage()); } } // Load open orders from disk public void load() { String filename = getOutstandingSaveFilename(); try { BufferedReader reader = new BufferedReader(new FileReader(filename)); orders.clear(); String line; do { line = reader.readLine(); if (line != null) { try { Order order = Order.deserialize(line); orders.add(order); } catch (Exception e) { log.info("Bad order: " + line + " (" + e.getMessage() + "), ignored"); } } } while (line != null); reader.close(); } catch (IOException e) { log.info("Failed to load orders! " + e.getMessage()); } } private String getOutstandingSaveFilename() { return plugin.getDataFolder() + System.getProperty("file.separator") + "outstanding.txt"; } public void cancelOrder(OfflinePlayer player, String s) { if (s == null || s.equals("-")) { cancelOrders(player); return; } ItemStack wanted = (new ItemQuery(s, player)).itemStack; int i = 0; for (Order order: orders) { if (order.player.equals(player) && ItemQuery.isIdenticalItem(order.want, wanted)) { cancelOrder(order); i += 1; } } if (player.getPlayer() != null) { player.getPlayer().sendMessage("Canceled " + i + " orders"); } } // Cancel all orders for a player public void cancelOrders(OfflinePlayer player) { int i = 0; for (Order order: orders) { if (order.player.equals(player)) { cancelOrder(order); i += 1; } } if (player.getPlayer() != null) { player.getPlayer().sendMessage("Canceled all your " + i + " orders"); } } public void cancelOrder(Order order) { if (!orders.remove(order)) { for (Order o: orders) { log.info("Compare " + o + " = " + o.compareTo(order)); } throw new UsageException("Failed to find order to cancel: " + order); } Bukkit.getServer().broadcastMessage("Closed order " + order); save(); } public void placeOrder(Order order) { Player onlinePlayer = order.player.getPlayer(); if (onlinePlayer == null) { throw new UsageException("Offline player tried to place order"); } // Admin conjuring permission if (ItemQuery.isNothing(order.give)) { if (!onlinePlayer.hasPermission("freetrade.conjure")) { throw new UsageException("You must specify or select what you want to trade for"); } recvItems(order.player, order.want); return; } // Item obliteration destruction permission if (ItemQuery.isNothing(order.want)) { if (!onlinePlayer.hasPermission("freetrade.obliterate")) { throw new UsageException("You do not have permission to trade items for nothing"); // tip: throw in lava or cacti instead } takeItems(order.player, order.give); return; } // Trade restrictions if (!onlinePlayer.hasPermission("freetrade.trade")) { throw new UsageException("You are not allowed to trade"); } if (tradeZone != null && !tradeZone.within(onlinePlayer.getLocation())) { throw new UsageException("You must be within the trade zone " + tradeZone + " to trade"); } // TODO: Trade machine nearby? (if enabled) if (tradeTerminalRadius != 0) { Location location = onlinePlayer.getLocation(); World world = onlinePlayer.getWorld(); int r = tradeTerminalRadius; int ox = location.getBlockX(), oy = location.getBlockY(), oz = location.getBlockZ(); log.info("original= "+ox+","+oy+","+oz); boolean found = false; DONE: for (int x = -r; x < r; x += 1) { for (int y = -r; y < r; y += 1) { for (int z = -r; z < r; z += 1) { Block block = world.getBlockAt(x+ox, y+oy, z+oz); //log.info("blockat("+x+","+y+","+z+") = " + block); if (block.getType().equals(tradeTerminalMaterial)) { found = true; } } } } log.info("Found = " + found); if (!found) { throw new UsageException("You are not within " + tradeTerminalRadius + " blocks of a " + ItemQuery.codeName2Name.get(tradeTerminalMaterial.getId() + "") + " trading terminal"); } } // TODO: if asking for identical want, different give, then update give? (Updating orders) // Not sure, might want to try asking for all different things for same item if really want it.. // Restricted by admin? // TODO: show reason (unobtainable, blacklisted) if (!ItemQuery.isTradable(order.want)) { throw new UsageException("Trading " + ItemQuery.nameStack(order.want) + " is prohibited"); } if (!ItemQuery.isTradable(order.give)) { throw new UsageException("Trading " + ItemQuery.nameStack(order.give) + " is prohibited"); } // You can only give what you have if (!hasItems(order.player, order.give)) { throw new UsageException("You don't have " + ItemQuery.nameStack(order.give) + " to give"); } if (matchOrder(order)) { // Executed return; } // Not fulfilled; add to outstanding to match with future order // Broadcast to all players so they know someone wants something, then add Bukkit.getServer().broadcastMessage("Wanted: " + order); orders.add(order); // Save to disk on every order save(); } // Transfer items from one player to another public static void transferItems(OfflinePlayer fromPlayer, OfflinePlayer toPlayer, ItemStack items) { /* // XXX: This is very important to prevent offline failures until have exception rollback Player fromPlayer = fromPlayerOffline.getPlayer(); Player toPlayer = toPlayerOffline.getPlayer(); if (fromPlayer == null) { // TODO: open up player's .dat, edit. Offline transfers! throw new UsageException("Sorry, from player "+fromPlayer.getDisplayName()+" is offline, cannot transfer items"); } if (toPlayer == null) { // TODO: offline player support throw new UsageException("Sorry, to player "+fromPlayer.getDisplayName()+" is offline, cannot transfer items"); }*/ // Online player transfer if (!hasItems(fromPlayer, items)) { throw new UsageException("Player " + fromPlayer.getName() + " doesn't have " + ItemQuery.nameStack(items)); } int missing = -1; Exception takeException = null; try { missing = takeItems(fromPlayer, items); } catch (Exception e) { missing = -1; takeException = e; } if (missing == -1 || missing > 0) { // Rollback order // TODO: verify items.setAmount(items.getAmount() - missing); recvItems(fromPlayer, items); // TODO: try to prevent this from happening, by watching inventory changes, player death, etc if (missing > 0) { throw new UsageException("Player " + fromPlayer.getName() + " doesn't have enough " + ItemQuery.nameStack(items) + ", missing " + missing + ", reverted"); } else { throw new UsageException("Player " + fromPlayer.getName() + " could not have items taken ("+takeException.getMessage()+"), reverted"); } } try { recvItems(toPlayer, items); } catch (Exception recvException) { // Give back // TODO: this needs to be BULLETPROOF to avoid item duping recvItems(fromPlayer, items); throw new UsageException("Player " + toPlayer.getName() + " could not receive items ("+recvException.getMessage()+"), reverted"); } Bukkit.getServer().broadcastMessage(toPlayer.getName() + " received " + ItemQuery.nameStack(items) + " from " + fromPlayer.getName()); } // Remove items from player's inventory, return # of items player had < amount (insufficient items) // Based on OddItem public static int takeItems(OfflinePlayer offlinePlayer, ItemStack goners) { Player player = offlinePlayer.getPlayer(); boolean offline = player == null; if (offline) { player = loadOfflinePlayer(offlinePlayer); } int remaining = takeItemsOnline(player, goners); if (offline) { saveOfflinePlayer(player); } return remaining; } private static int takeItemsOnline(Player player, ItemStack goners) { player.saveData(); ItemStack[] inventory = player.getInventory().getContents(); int remaining = goners.getAmount(); int i = 0; for (ItemStack slot: inventory) { if (ItemQuery.isIdenticalItem(slot, goners)) { if (remaining > slot.getAmount()) { remaining -= slot.getAmount(); slot.setAmount(0); } else if (remaining > 0) { slot.setAmount(slot.getAmount() - remaining); remaining = 0; } else { slot.setAmount(0); } // If removed whole slot, need to explicitly clear it // ItemStacks with amounts of 0 are interpreted as 1 (possible Bukkit bug?) if (slot.getAmount() == 0) { player.getInventory().clear(i); } } i += 1; if (remaining == 0) { break; } } return remaining; } // Return whether player has at least the items in the stack public static boolean hasItems(OfflinePlayer offlinePlayer, ItemStack items) { Player player = offlinePlayer.getPlayer(); if (player == null) { player = loadOfflinePlayer(player); } return hasItemsOnline(player, items); // not saved - no changes } private static boolean hasItemsOnline(Player player, ItemStack items) { ItemStack[] inventory = player.getInventory().getContents(); int remaining = items.getAmount(); for (ItemStack slot: inventory) { if (ItemQuery.isIdenticalItem(slot, items)) { remaining -= slot.getAmount(); } } return remaining <= 0; } // Have a player receive items in their inventory public static void recvItems(OfflinePlayer offlinePlayer, ItemStack items) { Player player = offlinePlayer.getPlayer(); boolean offline = player == null; if (offline) { player = loadOfflinePlayer(offlinePlayer); } recvItemsOnline(player, items); if (offline) { saveOfflinePlayer(player); } } // Save a temporary online player object created by loadOfflinePlayer() private static void saveOfflinePlayer(Player player) { player.saveData(); // TODO: need to destroy entity? } // Load an offline player into a temporary online Player private static Player loadOfflinePlayer(OfflinePlayer player) { List<File> files = getOfflinePlayerDataFiles(player); for (File file: files) { // Load offline player .dat // see also https://github.com/lishd/OpenInv/blob/master/src/lishid/openinv/commands/OpenInvPluginCommand.java#L81 net.minecraft.server.MinecraftServer console = ((CraftServer)Bukkit.getServer()).getServer(); net.minecraft.server.ItemInWorldManager manager = new net.minecraft.server.ItemInWorldManager(console.getWorldServer(0)); net.minecraft.server.EntityPlayer entity = new net.minecraft.server.EntityPlayer( console, console.getWorldServer(0), player.getName(), manager); if (entity == null) { throw new UsageException("Failed to load offline player entity " + player.getName()); } Player onlinePlayer = (Player)entity.getBukkitEntity(); if (onlinePlayer == null) { throw new UsageException("Failed to load offline player " + player.getName()); } log.info("Found! " + onlinePlayer); // read .dat onlinePlayer.loadData(); return onlinePlayer; /* PlayerInventory inv = onlinePlayer.getInventory(); for (ItemStack slot: inv.getContents()) { log.info("slot "+slot); }*/ // TODO: multiple players? destroy other entities? //break; } throw new UsageException("Could not find offline player "+player.getName()); } // Get all player .dat files for an offline player // Searches through all worlds, so could conceivably find >1 // (with multiworld plugin? but I haven't seen any in world_nether or world_the_end) private static List<File> getOfflinePlayerDataFiles(OfflinePlayer player) { List<File> playerFiles = new ArrayList<File>(1); String thisPlayerName = player.getName(); List<World> worlds = Bukkit.getWorlds(); for (World world: worlds) { File players = new File(world.getWorldFolder(), "players"); for (File playerFile: players.listFiles()) { String playerName = playerFile.getName().replaceFirst("\\.dat$", ""); if (playerName.trim().equalsIgnoreCase(thisPlayerName)) { playerFiles.add(playerFile); } } } return playerFiles; } private static void recvItemsOnline(Player player, ItemStack items) { int remaining = items.getAmount(); // Get maximum size per stack, then add individually // Prevents non-stackable items (potions, signs, boats, etc.) and semi-stackable // (enderpearls, eggs, snowballs, etc.) from being stacked to 64 int stackSize; if (player.hasPermission("freetrade.bigstacks")) { stackSize = remaining; } else { stackSize = Math.abs(items.getType().getMaxStackSize()); // Surprisingly, this always returns -1, see http://forums.bukkit.org/threads/getmaxstacksize-always-return-1.1154/#post-13147 //int stackSize = Math.abs(items.getMaxStackSize()); } // TODO: optional "huge stacks", beyond 64. setAmount(200) in inventory slot. Seems to work. do { int amount; if (remaining > stackSize) { amount = stackSize; remaining -= stackSize; } else { amount = remaining; remaining = 0; } // https://bukkit.atlassian.net/browse/BUKKIT-621 // ItemStack cannot clone all items, uses addEnchantment instead of addUnsafeEnchantment //ItemStack oneStack = items.clone(); // Workaround: clone ourselves ItemStack oneStack = new ItemStack(items.getTypeId(), amount, items.getDurability()); oneStack.addUnsafeEnchantments(items.getEnchantments()); // This fails with NPE on invalid items (/w !123) (TODO: bug report, null check) // public void setData(int i) { // this.damage = (this.id > 0) && (this.id < 256) ? Item.byId[this.id].filterData(i) : i; // CraftBukkit // } // Item.byId isn't defined for invalid items.. // -but- it does work for new items (CB modded with IC2, try /w !233 HashMap<Integer,ItemStack> excess = player.getInventory().addItem(oneStack); // If player's inventory if full, drop excess items on the floor Iterator it = excess.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); int unknown = ((Integer)pair.getKey()).intValue(); // hmm? always 0 ItemStack excessItems = (ItemStack)pair.getValue(); player.getWorld().dropItemNaturally(player.getLocation(), excessItems); } } while (remaining > 0); // How did the items transport themselves between the players? Magic, as indicated by smoke. // (Note only smoke on receiving end, and only if receiving player is online) player.playEffect(player.getLocation(), Effect.SMOKE, 0); } public boolean matchOrder(Order newOrder) { int i = 0; for (Order oldOrder: orders) { i += 1; //log.info("oldOrder: " + oldOrder); //log.info("newOrder: " + newOrder); // Are they giving what anyone else wants? if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) || !ItemQuery.isSameType(newOrder.want, oldOrder.give)) { log.info("Not matched, different types"); continue; } double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount(); double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount(); // Offering a better or equal deal? (Quantity = relative value) log.info("ratio " + newRatio + " >= " + oldRatio); if (!(newRatio >= oldRatio)) { log.info("Not matched, worse relative value"); continue; } // TODO: refactor into ItemStackX compareTo(), so can check if item is 'better than' other item // Generalized to 'betterness' // Is item less damaged or equally damaged than wanted? (Durability) if (ItemQuery.isDurable(newOrder.give.getType())) { if (newOrder.give.getDurability() > oldOrder.want.getDurability()) { log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability()); continue; } } if (ItemQuery.isDurable(oldOrder.give.getType())) { if (oldOrder.give.getDurability() > newOrder.want.getDurability()) { log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability()); continue; } } // Does the item have at least the enchantments and levels that are wanted? (Enchantments) if (ItemQuery.isEnchantable(newOrder.give.getType())) { if (!EnchantQuery.equalOrBetter(newOrder.give, oldOrder.want)) { log.info("Not matched, insufficient magic new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) + " < " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments())); continue; } } else { // Not legitimately enchantmentable, means enchant is used as a 'subtype', just like // damage is if !isDurable, so match exactly. if (!EnchantQuery.nameEnchs(newOrder.give.getEnchantments()).equals( EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()))) { log.info("Not matched, non-identical enchantments new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) + " != " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments())); continue; } } if (ItemQuery.isEnchantable(oldOrder.give.getType())) { if (!EnchantQuery.equalOrBetter(oldOrder.give, newOrder.want)) { log.info("Not matched, insufficient magic old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) + " < " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments())); continue; } } else { if (!EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()).equals( EnchantQuery.nameEnchs(newOrder.want.getEnchantments()))) { log.info("Not matched, non-identical enchantments old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) + " != " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments())); continue; } } // Determine how much of the order can be fulfilled int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount(); int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount(); log.info("remaining want="+remainingWant+", give="+remainingGive); // They get what they want! // Calculate amount that can be exchanged ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability()); ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability()); exchWant.addUnsafeEnchantments(newOrder.give.getEnchantments()); exchGive.addUnsafeEnchantments(oldOrder.give.getEnchantments()); log.info("exchWant="+ItemQuery.nameStack(exchWant)); log.info("exchGive="+ItemQuery.nameStack(exchGive)); transferItems(newOrder.player, oldOrder.player, exchWant); transferItems(oldOrder.player, newOrder.player, exchGive); Transaction t = new Transaction(plugin, oldOrder.player, exchWant, newOrder.player, exchGive); t.log(); /* oldOrder.player.getInventory().addItem(exchWant); newOrder.player.getInventory().remove(exchWant); Bukkit.getServer().broadcastMessage(oldOrder.player.getDisplayName() + " received " + ItemQuery.nameStack(exchWant) + " from " + newOrder.player.getDisplayName()); newOrder.player.getInventory().addItem(exchGive); oldOrder.player.getInventory().remove(exchGive); Bukkit.getServer().broadcastMessage(newOrder.player.getDisplayName() + " received " + ItemQuery.nameStack(exchGive) + " from " + oldOrder.player.getDisplayName()); */ // Remove oldOrder from orders, if complete, or add partial if incomplete if (remainingWant == 0) { // This order is finished, old player got everything they wanted // Note: remainingWant can be negative if they got more than they bargained for // (other player offered a better deal than expected). Either way, done deal. cancelOrder(oldOrder); return true; } else if (remainingWant > 0) { oldOrder.want.setAmount(remainingWant); oldOrder.give.setAmount(remainingGive); Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder); return true; } else if (remainingWant < 0) { // TODO: test better cancelOrder(oldOrder); newOrder.want.setAmount(-remainingGive); newOrder.give.setAmount(-remainingWant); log.info("Adding new partial order"); return false; } } return false; } } // Watch trader for things they might to do invalidate their orders class TraderListener implements Listener { Logger log = Logger.getLogger("Minecraft"); Market market; FreeTrade plugin; public TraderListener(FreeTrade pl, Market m) { plugin = pl; market = m; Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerDropItem(PlayerDropItemEvent event) { // Re-validate order, see if they dropped an item they were going to give for (Order order: market.orders) { // TODO: hash lookup of player? Performance if (order.player.equals(event.getPlayer())) { if (!Market.hasItems(order.player, order.give)) { if (order.player.getPlayer() != null) { order.player.getPlayer().sendMessage("Order invalidated by item drop"); } market.cancelOrder(order); } } } } // TODO: player death, drop events // TODO: player an item, changes damage, or uses up (either way invalidates order) } public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); Market market; YamlConfiguration config; TraderListener listener; public void onEnable() { market = new Market(this); loadConfig(); market.load(); listener = new TraderListener(this, market); log.info(getDescription().getName() + " enabled"); } public void onDisable() { market.save(); log.info(getDescription().getName() + " disabled"); } public void loadConfig() { String filename = getDataFolder() + System.getProperty("file.separator") + "FreeTrade.yml"; File file = new File(filename); if (!file.exists()) { if (!newConfig(file)) { throw new UsageException("Could not create new configuration file"); } } config = YamlConfiguration.loadConfiguration(new File(filename)); if (config == null) { throw new UsageException("Failed to load configuration file " + filename); } if (config.getInt("version") < 1) { throw new UsageException("Configuration file version is outdated"); } EnchantQuery.loadConfig(config); ItemQuery.loadConfig(config); market.loadConfig(config); } // Copy default configuration public boolean newConfig(File file) { FileWriter fileWriter; if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } try { fileWriter = new FileWriter(file); } catch (IOException e) { log.severe("Couldn't write config file: " + e.getMessage()); Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade")); return false; } BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(getResource("FreeTrade.yml")))); BufferedWriter writer = new BufferedWriter(fileWriter); try { String line = reader.readLine(); while (line != null) { writer.write(line + System.getProperty("line.separator")); line = reader.readLine(); } log.info("Wrote default config"); } catch (IOException e) { log.severe("Error writing config: " + e.getMessage()); } finally { try { writer.close(); reader.close(); } catch (IOException e) { log.severe("Error saving config: " + e.getMessage()); Bukkit.getServer().getPluginManager().disablePlugin(Bukkit.getServer().getPluginManager().getPlugin("FreeTrade")); } } return true; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; int n = 0; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return market.showOutstanding(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // Get player name from first argument player = Bukkit.getServer().getPlayer(args[0]); if (player == null) { sender.sendMessage("no such player"); return false; } n++; } if (args.length < 1+n) { return false; } String wantString, giveString; wantString = args[n]; if (args.length < 2+n) { // Omitted last arg, use item in hand giveString = "this"; } else if (args.length > 2+n) { // Too many args, don't try to interpret return false; } else { if (args[n+1].equalsIgnoreCase("for")) { giveString = args[n+2]; } else { giveString = args[n+1]; } } Order order; try { if (wantString.equals("-")) { log.info("cancelall"); market.cancelOrder(player, null); } else if (giveString.equals("-")) { market.cancelOrder(player, wantString); } else { order = new Order(player, wantString, giveString); sender.sendMessage(order.toString()); market.placeOrder(order); } } catch (UsageException e) { log.info("Sending usage exception: " + player.getDisplayName() + " - " + e ); player.sendMessage(e.getMessage()); return false; } return true; } }
Fix typo -- offline trading now works!
FreeTrade.java
Fix typo -- offline trading now works!
<ide><path>reeTrade.java <ide> Player player = offlinePlayer.getPlayer(); <ide> <ide> if (player == null) { <del> player = loadOfflinePlayer(player); <add> player = loadOfflinePlayer(offlinePlayer); <ide> } <ide> <ide> return hasItemsOnline(player, items);
Java
apache-2.0
30e7aba1e62179236c9c91b91c04a0c4f980f28f
0
mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service,mapcode-foundation/mapcode-rest-service
/* * Copyright (C) 2016-2017, Stichting Mapcode Foundation (http://www.mapcode.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mapcode.services.standalone; import com.google.inject.Guice; import com.google.inject.Injector; import com.mapcode.services.ResourcesModule; import com.tomtom.speedtools.guice.GuiceConfigurationModule; import com.tomtom.speedtools.rest.ServicesModule; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "ConstantConditions"}) public class MainCommandLine { private static final String CMD_HELP = "--help"; private static final String CMD_SILENT = "--silent"; private static final String CMD_DEBUG = "--debug"; private static final String CMD_PORT = "--port"; private static final int DEFAULT_PORT = 8080; private static final Server server; private static final Logger rootLogger; private static final ConsoleAppender consoleAppender; // Static init. static { final Injector guice = createGuice(); server = guice.getInstance(Server.class); // Configure log4j. rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.INFO); consoleAppender = new ConsoleAppender(new SimpleLayout()); consoleAppender.setThreshold(Level.INFO); rootLogger.addAppender(consoleAppender); } private MainCommandLine() { // Prevent instantiation. } public static void execute(final String[] args) { int port = DEFAULT_PORT; String command = null; boolean debug = false; // Parse command-line arguments. int index = 0; while (index < args.length) { switch (args[index]) { case CMD_SILENT: rootLogger.setLevel(Level.WARN); consoleAppender.setThreshold(Level.WARN); break; case CMD_DEBUG: debug = true; break; case CMD_PORT: if (index >= (args.length - 1)) { System.out.println("Missing port number"); printUsage(); return; } port = Integer.parseInt(args[index + 1]); ++index; break; default: if (args[index].startsWith("-")) { System.out.println("Unknown option: " + args[index]); printUsage(); return; } if (command != null) { System.out.println("Unknown argument: " + args[index]); printUsage(); return; } command = args[index]; break; } ++index; } if (debug) { consoleAppender.setThreshold(Level.DEBUG); } if ((command != null) && command.equals(CMD_HELP)) { printUsage(); } else { server.startServer(port); } } public static void stop() { server.stopServer(); } /** * Create the guice injector. * * @return Guice injector. */ private static Injector createGuice() { return Guice.createInjector( new GuiceConfigurationModule( "classpath:speedtools.default.properties", // Default set required by SpeedTools. "classpath:mapcode.properties"), // Mapcode properties. new ServicesModule(), new ResourcesModule(), new StandaloneModule()); } private static void printUsage() { System.out.println("Usage: java -jar <warfile>" + " [" + CMD_PORT + " <port>] [" + CMD_SILENT + "] [" + CMD_DEBUG + ']'); System.out.println(" java -jar <warfile> " + CMD_HELP); } }
service/src/main/java/com/mapcode/services/standalone/MainCommandLine.java
/* * Copyright (C) 2016-2017, Stichting Mapcode Foundation (http://www.mapcode.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mapcode.services.standalone; import com.google.inject.Guice; import com.google.inject.Injector; import com.mapcode.services.ResourcesModule; import com.tomtom.speedtools.guice.GuiceConfigurationModule; import com.tomtom.speedtools.rest.ServicesModule; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "ConstantConditions"}) public class MainCommandLine { private static final String CMD_HELP = "--help"; private static final String CMD_SILENT = "--silent"; private static final String CMD_DEBUG = "--debug"; private static final String CMD_PORT = "--port"; private static final int DEFAULT_PORT = 8080; private static Server server; private MainCommandLine() { // Prevent instantiation. } public static void execute(final String[] args) { int port = DEFAULT_PORT; String command = null; boolean debug = false; // Configure log4j. final Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.INFO); final ConsoleAppender consoleAppender = new ConsoleAppender(new SimpleLayout()); consoleAppender.setThreshold(Level.INFO); rootLogger.addAppender(consoleAppender); // Parse command-line arguments. int index = 0; while (index < args.length) { switch (args[index]) { case CMD_SILENT: rootLogger.setLevel(Level.WARN); consoleAppender.setThreshold(Level.WARN); break; case CMD_DEBUG: debug = true; break; case CMD_PORT: if (index >= (args.length - 1)) { System.out.println("Missing port number"); printUsage(); return; } port = Integer.parseInt(args[index + 1]); ++index; break; default: if (args[index].startsWith("-")) { System.out.println("Unknown option: " + args[index]); printUsage(); return; } if (command != null) { System.out.println("Unknown argument: " + args[index]); printUsage(); return; } command = args[index]; break; } ++index; } if (debug) { consoleAppender.setThreshold(Level.DEBUG); } if ((command != null) && command.equals(CMD_HELP)) { printUsage(); } else { final Injector guice = createGuice(); server = guice.getInstance(Server.class); server.startServer(port); } } public static void stop() { server.stopServer(); } /** * Create the guice injector. * * @return Guice injector. */ private static Injector createGuice() { return Guice.createInjector( new GuiceConfigurationModule( "classpath:speedtools.default.properties", // Default set required by SpeedTools. "classpath:mapcode.properties"), // Mapcode properties. new ServicesModule(), new ResourcesModule(), new StandaloneModule()); } private static void printUsage() { System.out.println("Usage: java -jar <warfile>" + " [" + CMD_PORT + " <port>] [" + CMD_SILENT + "] [" + CMD_DEBUG + ']'); System.out.println(" java -jar <warfile> " + CMD_HELP); } }
Improved test server handling
service/src/main/java/com/mapcode/services/standalone/MainCommandLine.java
Improved test server handling
<ide><path>ervice/src/main/java/com/mapcode/services/standalone/MainCommandLine.java <ide> <ide> private static final int DEFAULT_PORT = 8080; <ide> <del> private static Server server; <add> private static final Server server; <add> private static final Logger rootLogger; <add> private static final ConsoleAppender consoleAppender; <add> <add> // Static init. <add> static { <add> final Injector guice = createGuice(); <add> server = guice.getInstance(Server.class); <add> <add> // Configure log4j. <add> rootLogger = Logger.getRootLogger(); <add> rootLogger.setLevel(Level.INFO); <add> <add> consoleAppender = new ConsoleAppender(new SimpleLayout()); <add> consoleAppender.setThreshold(Level.INFO); <add> rootLogger.addAppender(consoleAppender); <add> } <ide> <ide> private MainCommandLine() { <ide> // Prevent instantiation. <ide> int port = DEFAULT_PORT; <ide> String command = null; <ide> boolean debug = false; <del> <del> // Configure log4j. <del> final Logger rootLogger = Logger.getRootLogger(); <del> rootLogger.setLevel(Level.INFO); <del> <del> final ConsoleAppender consoleAppender = new ConsoleAppender(new SimpleLayout()); <del> consoleAppender.setThreshold(Level.INFO); <del> rootLogger.addAppender(consoleAppender); <ide> <ide> // Parse command-line arguments. <ide> int index = 0; <ide> if ((command != null) && command.equals(CMD_HELP)) { <ide> printUsage(); <ide> } else { <del> final Injector guice = createGuice(); <del> server = guice.getInstance(Server.class); <ide> server.startServer(port); <ide> } <ide> }
JavaScript
mit
d47f93c499570ea4490f53be54e5414299b83288
0
mafintosh/hyperdb
var sodium = require('sodium-universal') var protocol = require('hypercore-protocol') var allocUnsafe = require('buffer-alloc-unsafe') var toBuffer = require('to-buffer') var thunky = require('thunky') var mutexify = require('mutexify') var peer = require('./lib/peer') var KEY = allocUnsafe(sodium.crypto_shorthash_KEYBYTES).fill(0) module.exports = DB function DB (feeds, opts) { if (!(this instanceof DB)) return new DB(feeds, opts) if (!opts) opts = {} var self = this this.feeds = feeds this.ready = thunky(open) this.writable = false this.readable = !!feeds.length this.key = null this.discoveryKey = null this._peers = [] this._peersByKey = {} this._writer = null this._lock = mutexify() this._map = opts.map this._reduce = opts.reduce feeds[0].on('peer-add', onpeer) feeds[0].ready(function (err) { if (err) throw err // yolo self.key = feeds[0].key self.discoveryKey = feeds[0].discoveryKey }) function onpeer () { var peer = feeds[0].peers[feeds[0].peers.length - 1] // hack self._onpeer(peer) } function open (cb) { self._open(cb) } } DB.prototype._onpeer = function (peer) { var self = this peer.stream.on('extension', function (type, message) { if (type !== 'hyperdb') return message = JSON.parse(message) if (message.type === 'get') { self.nodes(message.key, function (err, nodes) { if (err) return peer.stream.extension('hyperdb', toBuffer(JSON.stringify({type: 'nodes', nodes: nodes}))) }) return } if (message.type === 'nodes') { var nodes = message.nodes for (var i = 0; i < nodes.length; i++) { var feed = self._peersByKey[nodes[i].feed].feed if (!feed.has(nodes[i].seq)) feed.get(nodes[i].seq, noop) } // return } }) } DB.prototype.replicate = function (opts) { if (!opts) opts = {} var self = this var stream = protocol({ id: this.feeds[0].id, extensions: ['hyperdb'], expectedFeeds: this.feeds.length }) self.feeds[0].ready(function () { for (var i = 0; i < self.feeds.length; i++) { self.feeds[i].replicate({stream: stream}) } }) return stream } DB.prototype._open = function (cb) { var missing = this.feeds.length var error = null var self = this for (var i = 0; i < this.feeds.length; i++) { this.feeds[i].ready(onready) } function onready (err) { if (err) error = err if (--missing) return if (error) return cb(error) for (var i = 0; i < self.feeds.length; i++) { self._peersByKey[self.feeds[i].key.toString('hex')] = self._peers[i] = peer(self.feeds[i]) if (self.feeds[i].writable) { self._writer = self.feeds[i] self.writable = true } } cb(null) } } DB.prototype.nodes = function (key, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) var i = 0 var nodes = [] var record = heads .map(function (head) { return head && {feed: head.feed, seq: head.seq} }) .filter(x => x) loop(null) function loop (err) { if (err) return cb(err) if (i >= heads.length) return done() var head = heads[i++] self._get(head, key, nodes, record, loop) } function done () { cb(null, record) } }) }) } DB.prototype.get = function (key, cb) { var self = this this.ready(function (err) { if (err) return cb(err) for (var i = 0; i < self.feeds[0].peers.length; i++) { self.feeds[0].peers[i].stream.extension('hyperdb', toBuffer(JSON.stringify({type: 'get', key: key}))) } self._heads(function (err, heads) { if (err) return cb(err) var i = 0 var nodes = [] loop(null) function loop (err) { if (err) return cb(err) if (i >= heads.length) return done() var head = heads[i++] self._get(head, key, nodes, null, loop) } function done () { nodes = dedup(nodes, heads) if (!nodes.length) return cb(new Error('Not found')) if (self._reduce) { var node = nodes.reduce(self._reduce) if (!node) return cb(new Error('Not found')) return cb(null, self._map ? self._map(node) : node) } if (self._map) { nodes = nodes.map(self._map) } cb(null, nodes) } }) }) } DB.prototype._get = function (head, key, result, record, cb) { if (!head) return cb(null) if (head.key === key) { result.push(head) return cb(null) } var path = toPath(key) var cmp = compare(head.path, path) var ptrs = head.pointers[cmp] if (!ptrs.length) return cb(null) var target = path[cmp] var self = this ptrs = ptrs.filter(function (p) { if (p.v === undefined) return true return p.v === target }) if (record) { for (var i = 0; i < ptrs.length; i++) { record.push({feed: ptrs[i].feed, seq: ptrs[i].seq}) } } this._getAll(ptrs, function (err, nodes) { if (err) return cb(err) var i = 0 loop(null) function loop (err) { if (err) return cb(err) if (i === nodes.length) return cb(null) var node = nodes[i++] if (node.path[cmp] === target) { return self._get(node, key, result, record, loop) } process.nextTick(loop) } }) } DB.prototype._append = function (node, cb) { if (!this._writer) return cb(new Error('No writable feed. Cannot append')) if (this._writer.length === 0) { this._writer.append([{type: 'hyperdb', version: 0}, node], cb) } else { this._writer.append(node, cb) } } DB.prototype._heads = function (cb) { var error = null var heads = [] var missing = this._peers.length this._peers.forEach(function (peer, i) { peer.head(function (err, head) { if (err) error = err else heads[i] = head if (--missing) return cb(error, heads) }) }) } DB.prototype.put = function (key, val, cb) { if (!cb) cb = noop var self = this this._lock(function (release) { self._put(key, val, function (err) { if (err) return release(cb, err) release(cb, null) }) }) } DB.prototype._put = function (key, val, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) if (heads.every(isNull)) return self._init(key, val, cb) var path = toPath(key) var i = 0 var pointers = [] var seq = Math.max(self._writer.length, 1) var me = self._writer.key.toString('hex') heads = heads.filter(x => x) loop() function onlyNumber (val) { return typeof val === 'number' ? val : undefined } function filter (result, val, i) { result = result.filter(function (r) { if (r.key === key) return false if (r.feed === me && r.path[i] === val) { return false } return true }) result = result.map(function (r) { return {feed: r.feed, seq: r.seq, v: onlyNumber(r.path[i])} }) result.push({ feed: me, seq: seq, v: onlyNumber(val) }) return result } function done () { var node = { feed: me, seq: seq, key: key, pointers: pointers, path: path, value: val, heads: self.feeds .map(function (f) { return f !== self._writer && { feed: f.key.toString('hex'), length: f.length } }) .filter(function (f) { return f }) } self._append(node, cb) } function loop (err, nodes) { if (err) return cb(err) if (nodes) { pointers.push(filter(nodes, path[i], i)) i++ } if (i === path.length) return done() self._listHeads(heads, path.slice(0, i), loop) } }) }) } DB.prototype.list = function (path, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) self._listHeads(heads, path, cb) }) }) } DB.prototype.close = function (cb) { if (!cb) cb = noop var self = this this.ready(function (err) { if (err) return cb(err) self.readable = false self.writable = false var missing = self.feeds.length var error = null self.feeds.forEach(function (feed) { feed.close(function (err) { if (err) error = err if (--missing) return cb(error) }) }) }) } DB.prototype._listHeads = function (heads, path, cb) { var self = this var i = 0 var result = [] loop(null, null) function loop (err, nodes) { if (err) return cb(err) if (nodes) { for (var j = 0; j < nodes.length; j++) { result.push(nodes[j]) } } if (i === heads.length) { return cb(null, dedupKeys(result, heads)) } self._list(heads[i++], path, loop) } } DB.prototype._list = function (head, path, cb) { var self = this if (!head) return cb(null, []) var cmp = compare(head.path, path) var ptrs = head.pointers[cmp] if (cmp === path.length) { self._getAll(ptrs, cb) return } self._closer(path, cmp, ptrs, cb) } DB.prototype._init = function (key, val, cb) { var self = this var seq = Math.max(this._writer.length, 1) var node = { feed: this._writer.key.toString('hex'), seq: seq, key: key, pointers: toPath(key).map(function (v) { return [{feed: self._writer.key.toString('hex'), seq: seq}] }), path: toPath(key), value: val, heads: this.feeds .map(function (f) { return f !== self._writer && { feed: f.key.toString('hex'), length: f.length } }) .filter(function (f) { return f }) } this._append(node, cb) } DB.prototype._closer = function (path, cmp, ptrs, cb) { var target = path[cmp] var self = this this._getAll(ptrs, function (err, nodes) { if (err) return cb(err) for (var i = 0; i < nodes.length; i++) { var node = nodes[i] if (node.path[cmp] === target) { self._list(node, path, cb) return } } cb(null, []) }) } DB.prototype._getAll = function (pointers, cb) { if (!pointers || !pointers.length) return cb(null, []) var all = new Array(pointers.length) var missing = all.length var error = null var self = this pointers.forEach(function (ptr, i) { self._peersByKey[ptr.feed].get(ptr.seq, function (err, node) { if (err) error = err if (node) all[i] = node if (--missing) return if (error) cb(error) else cb(null, all) }) }) } function dedupKeys (nodes, heads) { nodes.sort(function (a, b) { return a.key.localeCompare(b.key) }) var batch = nodes.slice(0, 1) var all = [] for (var i = 1; i < nodes.length; i++) { if (nodes[i - 1].key === nodes[i].key) { batch.push(nodes[i]) } else { all = all.concat(dedup(batch, heads)) batch = [nodes[i]] } } return all.concat(dedup(batch, heads)) } function dedup (nodes, heads) { nodes = nodes.filter(function (n, i) { return indexOf(n) === i }) nodes = nodes.filter(function (n) { return !nodes.some(function (o) { if (o.feed === n.feed && o.seq > n.seq) return true return o.heads.some(function (head) { return head.feed === n.feed && head.length > n.seq }) }) }) return nodes function indexOf (n) { for (var i = 0; i < nodes.length; i++) { if (nodes[i].feed === n.feed && nodes[i].seq === n.seq) return i } return -1 } } function toPath (key) { var arr = splitHash(hash(toBuffer(key))) arr.push(key) return arr } function isNull (v) { return v === null } function compare (a, b) { var idx = 0 while (idx < a.length && a[idx] === b[idx]) idx++ return idx } function hash (key) { var out = allocUnsafe(8) sodium.crypto_shorthash(out, key, KEY) return out } function splitHash (hash) { var list = [] for (var i = 0; i < hash.length; i++) { factor(hash[i], 4, 4, list) } return list } function factor (n, b, cnt, list) { while (cnt--) { var r = n & (b - 1) list.push(r) n -= r n /= b } } function noop () {}
index.js
var sodium = require('sodium-universal') var protocol = require('hypercore-protocol') var allocUnsafe = require('buffer-alloc-unsafe') var toBuffer = require('to-buffer') var thunky = require('thunky') var mutexify = require('mutexify') var peer = require('./lib/peer') var KEY = allocUnsafe(sodium.crypto_shorthash_KEYBYTES).fill(0) module.exports = DB function DB (feeds, opts) { if (!(this instanceof DB)) return new DB(feeds, opts) if (!opts) opts = {} var self = this this.feeds = feeds this.ready = thunky(open) this.writable = false this.readable = !!feeds.length this._peers = [] this._peersByKey = {} this._writer = null this._lock = mutexify() this._map = opts.map this._reduce = opts.reduce feeds[0].on('peer-add', onpeer) function onpeer () { var peer = feeds[0].peers[feeds[0].peers.length - 1] // hack self._onpeer(peer) } function open (cb) { self._open(cb) } } DB.prototype._onpeer = function (peer) { var self = this peer.stream.on('extension', function (type, message) { if (type !== 'hyperdb') return message = JSON.parse(message) if (message.type === 'get') { self.nodes(message.key, function (err, nodes) { if (err) return peer.stream.extension('hyperdb', new Buffer(JSON.stringify({type: 'nodes', nodes: nodes}))) }) return } if (message.type === 'nodes') { var nodes = message.nodes for (var i = 0; i < nodes.length; i++) { var feed = self._peersByKey[nodes[i].feed].feed if (!feed.has(nodes[i].seq)) feed.get(nodes[i].seq, noop) } return } }) } DB.prototype.replicate = function (opts) { if (!opts) opts = {} var self = this var stream = protocol({ id: this.feeds[0].id, extensions: ['hyperdb'], expectedFeeds: this.feeds.length }) self.feeds[0].ready(function () { for (var i = 0; i < self.feeds.length; i++) { self.feeds[i].replicate({stream: stream}) } }) return stream } DB.prototype._open = function (cb) { var missing = this.feeds.length var error = null var self = this for (var i = 0; i < this.feeds.length; i++) { this.feeds[i].ready(onready) } function onready (err) { if (err) error = err if (--missing) return if (error) return cb(error) for (var i = 0; i < self.feeds.length; i++) { self._peersByKey[self.feeds[i].key.toString('hex')] = self._peers[i] = peer(self.feeds[i]) if (self.feeds[i].writable) { self._writer = self.feeds[i] self.writable = true } } cb(null) } } DB.prototype.nodes = function (key, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) var i = 0 var nodes = [] var record = heads .map(function (head) { return head && {feed: head.feed, seq: head.seq} }) .filter(x => x) loop(null) function loop (err) { if (err) return cb(err) if (i >= heads.length) return done() var head = heads[i++] self._get(head, key, nodes, record, loop) } function done () { cb(null, record) } }) }) } DB.prototype.get = function (key, cb) { var self = this this.ready(function (err) { if (err) return cb(err) for (var i = 0; i < self.feeds[0].peers.length; i++) { self.feeds[0].peers[i].stream.extension('hyperdb', new Buffer(JSON.stringify({type: 'get', key: key}))) } self._heads(function (err, heads) { if (err) return cb(err) var i = 0 var nodes = [] loop(null) function loop (err) { if (err) return cb(err) if (i >= heads.length) return done() var head = heads[i++] self._get(head, key, nodes, null, loop) } function done () { nodes = dedup(nodes, heads) if (!nodes.length) return cb(new Error('Not found')) if (self._reduce) { var node = nodes.reduce(self._reduce) if (!node) return cb(new Error('Not found')) return cb(null, self._map ? self._map(node) : node) } if (self._map) { nodes = nodes.map(self._map) } cb(null, nodes) } }) }) } DB.prototype._get = function (head, key, result, record, cb) { if (!head) return cb(null) if (head.key === key) { result.push(head) return cb(null) } var path = toPath(key) var cmp = compare(head.path, path) var ptrs = head.pointers[cmp] if (!ptrs.length) return cb(null) var target = path[cmp] var self = this ptrs = ptrs.filter(function (p) { if (p.v === undefined) return true return p.v === target }) if (record) { for (var i = 0; i < ptrs.length; i++) { record.push({feed: ptrs[i].feed, seq: ptrs[i].seq}) } } this._getAll(ptrs, function (err, nodes) { if (err) return cb(err) var i = 0 loop(null) function loop (err) { if (err) return cb(err) if (i === nodes.length) return cb(null) var node = nodes[i++] if (node.path[cmp] === target) { return self._get(node, key, result, record, loop) } process.nextTick(loop) } }) } DB.prototype._append = function (node, cb) { if (!this._writer) return cb(new Error('No writable feed. Cannot append')) if (this._writer.length === 0) { this._writer.append([{type: 'hyperdb', version: 0}, node], cb) } else { this._writer.append(node, cb) } } DB.prototype._heads = function (cb) { var error = null var heads = [] var missing = this._peers.length this._peers.forEach(function (peer, i) { peer.head(function (err, head) { if (err) error = err else heads[i] = head if (--missing) return cb(error, heads) }) }) } DB.prototype.put = function (key, val, cb) { if (!cb) cb = noop var self = this this._lock(function (release) { self._put(key, val, function (err) { if (err) return release(cb, err) release(cb, null) }) }) } DB.prototype._put = function (key, val, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) if (heads.every(isNull)) return self._init(key, val, cb) var path = toPath(key) var i = 0 var pointers = [] var seq = Math.max(self._writer.length, 1) var me = self._writer.key.toString('hex') heads = heads.filter(x => x) loop() function onlyNumber (val) { return typeof val === 'number' ? val : undefined } function filter (result, val, i) { result = result.filter(function (r) { if (r.key === key) return false if (r.feed === me && r.path[i] === val) { return false } return true }) result = result.map(function (r) { return {feed: r.feed, seq: r.seq, v: onlyNumber(r.path[i])} }) result.push({ feed: me, seq: seq, v: onlyNumber(val) }) return result } function done () { var node = { feed: me, seq: seq, key: key, pointers: pointers, path: path, value: val, heads: self.feeds .map(function (f) { return f !== self._writer && { feed: f.key.toString('hex'), length: f.length } }) .filter(function (f) { return f }) } self._append(node, cb) } function loop (err, nodes) { if (err) return cb(err) if (nodes) { pointers.push(filter(nodes, path[i], i)) i++ } if (i === path.length) return done() self._listHeads(heads, path.slice(0, i), loop) } }) }) } DB.prototype.list = function (path, cb) { var self = this this.ready(function (err) { if (err) return cb(err) self._heads(function (err, heads) { if (err) return cb(err) self._listHeads(heads, path, cb) }) }) } DB.prototype.close = function (cb) { if (!cb) cb = noop var self = this this.ready(function (err) { if (err) return cb(err) self.readable = false self.writable = false var missing = self.feeds.length var error = null self.feeds.forEach(function (feed) { feed.close(function (err) { if (err) error = err if (--missing) return cb(error) }) }) }) } DB.prototype._listHeads = function (heads, path, cb) { var self = this var i = 0 var result = [] loop(null, null) function loop (err, nodes) { if (err) return cb(err) if (nodes) { for (var j = 0; j < nodes.length; j++) { result.push(nodes[j]) } } if (i === heads.length) { return cb(null, dedupKeys(result, heads)) } self._list(heads[i++], path, loop) } } DB.prototype._list = function (head, path, cb) { var self = this if (!head) return cb(null, []) var cmp = compare(head.path, path) var ptrs = head.pointers[cmp] if (cmp === path.length) { self._getAll(ptrs, cb) return } self._closer(path, cmp, ptrs, cb) } DB.prototype._init = function (key, val, cb) { var self = this var seq = Math.max(this._writer.length, 1) var node = { feed: this._writer.key.toString('hex'), seq: seq, key: key, pointers: toPath(key).map(function (v) { return [{feed: self._writer.key.toString('hex'), seq: seq}] }), path: toPath(key), value: val, heads: this.feeds .map(function (f) { return f !== self._writer && { feed: f.key.toString('hex'), length: f.length } }) .filter(function (f) { return f }) } this._append(node, cb) } DB.prototype._closer = function (path, cmp, ptrs, cb) { var target = path[cmp] var self = this this._getAll(ptrs, function (err, nodes) { if (err) return cb(err) for (var i = 0; i < nodes.length; i++) { var node = nodes[i] if (node.path[cmp] === target) { self._list(node, path, cb) return } } cb(null, []) }) } DB.prototype._getAll = function (pointers, cb) { if (!pointers || !pointers.length) return cb(null, []) var all = new Array(pointers.length) var missing = all.length var error = null var self = this pointers.forEach(function (ptr, i) { self._peersByKey[ptr.feed].get(ptr.seq, function (err, node) { if (err) error = err if (node) all[i] = node if (--missing) return if (error) cb(error) else cb(null, all) }) }) } function dedupKeys (nodes, heads) { nodes.sort(function (a, b) { return a.key.localeCompare(b.key) }) var batch = nodes.slice(0, 1) var all = [] for (var i = 1; i < nodes.length; i++) { if (nodes[i - 1].key === nodes[i].key) { batch.push(nodes[i]) } else { all = all.concat(dedup(batch, heads)) batch = [nodes[i]] } } return all.concat(dedup(batch, heads)) } function dedup (nodes, heads) { nodes = nodes.filter(function (n, i) { return indexOf(n) === i }) nodes = nodes.filter(function (n) { return !nodes.some(function (o) { if (o.feed === n.feed && o.seq > n.seq) return true return o.heads.some(function (head) { return head.feed === n.feed && head.length > n.seq }) }) }) return nodes function indexOf (n) { for (var i = 0; i < nodes.length; i++) { if (nodes[i].feed === n.feed && nodes[i].seq === n.seq) return i } return -1 } } function toPath (key) { var arr = splitHash(hash(toBuffer(key))) arr.push(key) return arr } function isNull (v) { return v === null } function compare (a, b) { var idx = 0 while (idx < a.length && a[idx] === b[idx]) idx++ return idx } function hash (key) { var out = allocUnsafe(8) sodium.crypto_shorthash(out, key, KEY) return out } function splitHash (hash) { var list = [] for (var i = 0; i < hash.length; i++) { factor(hash[i], 4, 4, list) } return list } function factor (n, b, cnt, list) { while (cnt--) { var r = n & (b - 1) list.push(r) n -= r n /= b } } function noop () {}
be standard
index.js
be standard
<ide><path>ndex.js <ide> this.ready = thunky(open) <ide> this.writable = false <ide> this.readable = !!feeds.length <add> this.key = null <add> this.discoveryKey = null <ide> <ide> this._peers = [] <ide> this._peersByKey = {} <ide> this._reduce = opts.reduce <ide> <ide> feeds[0].on('peer-add', onpeer) <add> feeds[0].ready(function (err) { <add> if (err) throw err // yolo <add> self.key = feeds[0].key <add> self.discoveryKey = feeds[0].discoveryKey <add> }) <ide> <ide> function onpeer () { <ide> var peer = feeds[0].peers[feeds[0].peers.length - 1] // hack <ide> if (message.type === 'get') { <ide> self.nodes(message.key, function (err, nodes) { <ide> if (err) return <del> peer.stream.extension('hyperdb', new Buffer(JSON.stringify({type: 'nodes', nodes: nodes}))) <add> peer.stream.extension('hyperdb', toBuffer(JSON.stringify({type: 'nodes', nodes: nodes}))) <ide> }) <ide> return <ide> } <ide> var feed = self._peersByKey[nodes[i].feed].feed <ide> if (!feed.has(nodes[i].seq)) feed.get(nodes[i].seq, noop) <ide> } <del> return <add> // return <ide> } <ide> }) <ide> } <ide> if (err) return cb(err) <ide> <ide> for (var i = 0; i < self.feeds[0].peers.length; i++) { <del> self.feeds[0].peers[i].stream.extension('hyperdb', new Buffer(JSON.stringify({type: 'get', key: key}))) <add> self.feeds[0].peers[i].stream.extension('hyperdb', toBuffer(JSON.stringify({type: 'get', key: key}))) <ide> } <ide> <ide> self._heads(function (err, heads) {
Java
apache-2.0
a3b3b68cf92d8cb4156ca143f1cd6236634f183d
0
HanSolo/medusademo
/* * Copyright (c) 2016 by Gerrit Grunwald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo; import eu.hansolo.medusa.Fonts; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.KnobType; import eu.hansolo.medusa.Gauge.NeedleBehavior; import eu.hansolo.medusa.Gauge.NeedleShape; import eu.hansolo.medusa.Gauge.NeedleType; import eu.hansolo.medusa.GaugeBuilder; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; import java.util.Locale; import java.util.Random; /** * Created by hansolo on 02.02.16. */ public class CompassGauge extends Application { private static final Random RND = new Random(); private static int noOfNodes = 0; private Gauge gauge; private Label value; private long lastTimerCall; private AnimationTimer timer; @Override public void init() { gauge = GaugeBuilder.create() .prefSize(400, 400) .borderPaint(Gauge.DARK_COLOR) .minValue(0) .maxValue(359) .autoScale(false) .startAngle(180) .angleRange(360) .minorTickMarksVisible(false) .mediumTickMarksVisible(false) .majorTickMarksVisible(false) .customTickLabelsEnabled(true) .customTickLabels("N", "", "", "", "", "", "", "", "", "E", "", "", "", "", "", "", "", "", "S", "", "", "", "", "", "", "", "", "W", "", "", "", "", "", "", "", "") .customTickLabelFontSize(48) .knobType(KnobType.FLAT) .knobColor(Gauge.DARK_COLOR) .needleShape(NeedleShape.FLAT) .needleType(NeedleType.FAT) .needleBehavior(NeedleBehavior.OPTIMIZED) .tickLabelColor(Gauge.DARK_COLOR) .animated(true) .animationDuration(500) .valueVisible(false) .build(); gauge.valueProperty().addListener(o -> { value.setText(String.format(Locale.US, "%.0f\u00B0", gauge.getValue())); }); value = new Label("0\u00B0"); value.setFont(Fonts.latoBold(72)); value.setAlignment(Pos.CENTER); value.setPrefWidth(400); lastTimerCall = System.nanoTime(); timer = new AnimationTimer() { @Override public void handle(long now) { if (now > lastTimerCall + 3_000_000_000l) { gauge.setValue(RND.nextDouble() * 359.9); lastTimerCall = now; } } }; } @Override public void start(Stage stage) { VBox pane = new VBox(gauge, value); pane.setSpacing(20); pane.setPadding(new Insets(10)); Scene scene = new Scene(pane); stage.setTitle("Medusa Compass"); stage.setScene(scene); stage.show(); timer.start(); // Calculate number of nodes calcNoOfNodes(pane); System.out.println(noOfNodes + " Nodes in SceneGraph"); } @Override public void stop() { System.exit(0); } // ******************** Misc ********************************************** private static void calcNoOfNodes(Node node) { if (node instanceof Parent) { if (((Parent) node).getChildrenUnmodifiable().size() != 0) { ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable(); noOfNodes += tempChildren.size(); for (Node n : tempChildren) { calcNoOfNodes(n); } } } } public static void main(String[] args) { launch(args); } }
src/main/java/eu/hansolo/CompassGauge.java
/* * Copyright (c) 2016 by Gerrit Grunwald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.hansolo; import eu.hansolo.medusa.Fonts; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.KnobType; import eu.hansolo.medusa.Gauge.NeedleBehavior; import eu.hansolo.medusa.Gauge.NeedleShape; import eu.hansolo.medusa.Gauge.NeedleType; import eu.hansolo.medusa.GaugeBuilder; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; import java.util.Locale; import java.util.Random; /** * Created by hansolo on 02.02.16. */ public class CompassGauge extends Application { private static final Random RND = new Random(); private static int noOfNodes = 0; private Gauge gauge; private Label value; private long lastTimerCall; private AnimationTimer timer; @Override public void init() { gauge = GaugeBuilder.create() .prefSize(400, 400) .borderPaint(Gauge.DARK_COLOR) .minValue(0) .maxValue(359) .autoScale(false) .startAngle(180) .angleRange(360) .minorTickMarksVisible(false) .mediumTickMarksVisible(false) .majorTickMarksVisible(false) .customTickLabelsEnabled(true) .customTickLabels("N", "", "", "", "", "", "", "", "", "E", "", "", "", "", "", "", "", "", "S", "", "", "", "", "", "", "", "", "W", "", "", "", "", "", "", "", "") .customTickLabelFontSize(48) .knobType(KnobType.FLAT) .knobColor(Gauge.DARK_COLOR) .needleShape(NeedleShape.FLAT) .needleType(NeedleType.FAT) .needleBehavior(NeedleBehavior.OPTIMIZED) .tickLabelColor(Gauge.DARK_COLOR) .animated(true) .animationDuration(500) .valueVisible(false) .build(); gauge.valueProperty().addListener(o -> { value.setText(String.format(Locale.US, "%.0f \u00B0", gauge.getValue())); }); value = new Label("0°"); value.setFont(Fonts.latoBold(72)); value.setAlignment(Pos.CENTER); value.setPrefWidth(400); lastTimerCall = System.nanoTime(); timer = new AnimationTimer() { @Override public void handle(long now) { if (now > lastTimerCall + 3_000_000_000l) { gauge.setValue(RND.nextDouble() * 359.9); lastTimerCall = now; } } }; } @Override public void start(Stage stage) { VBox pane = new VBox(gauge, value); pane.setSpacing(20); pane.setPadding(new Insets(10)); Scene scene = new Scene(pane); stage.setTitle("Medusa Compass"); stage.setScene(scene); stage.show(); timer.start(); // Calculate number of nodes calcNoOfNodes(pane); System.out.println(noOfNodes + " Nodes in SceneGraph"); } @Override public void stop() { System.exit(0); } // ******************** Misc ********************************************** private static void calcNoOfNodes(Node node) { if (node instanceof Parent) { if (((Parent) node).getChildrenUnmodifiable().size() != 0) { ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable(); noOfNodes += tempChildren.size(); for (Node n : tempChildren) { calcNoOfNodes(n); } } } } public static void main(String[] args) { launch(args); } }
Cosmetics related to utf-8 encoding
src/main/java/eu/hansolo/CompassGauge.java
Cosmetics related to utf-8 encoding
<ide><path>rc/main/java/eu/hansolo/CompassGauge.java <ide> .build(); <ide> <ide> gauge.valueProperty().addListener(o -> { <del> value.setText(String.format(Locale.US, "%.0f \u00B0", gauge.getValue())); <add> value.setText(String.format(Locale.US, "%.0f\u00B0", gauge.getValue())); <ide> }); <ide> <del> value = new Label("0°"); <add> value = new Label("0\u00B0"); <ide> value.setFont(Fonts.latoBold(72)); <ide> value.setAlignment(Pos.CENTER); <ide> value.setPrefWidth(400);
Java
apache-2.0
d2942263f279fa836408a7d75c2e66be9209deab
0
wschaeferB/autopsy,millmanorama/autopsy,APriestman/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,rcordovano/autopsy,APriestman/autopsy,APriestman/autopsy,dgrove727/autopsy,rcordovano/autopsy,esaunders/autopsy,narfindustries/autopsy,esaunders/autopsy,wschaeferB/autopsy,APriestman/autopsy,narfindustries/autopsy,rcordovano/autopsy,wschaeferB/autopsy,dgrove727/autopsy,millmanorama/autopsy,wschaeferB/autopsy,rcordovano/autopsy,millmanorama/autopsy,APriestman/autopsy,narfindustries/autopsy,rcordovano/autopsy,esaunders/autopsy,millmanorama/autopsy,dgrove727/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy
/* * Autopsy Forensic Browser * * Copyright 2011-2016 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.corecomponents; import java.awt.Color; import java.awt.Cursor; import java.awt.EventQueue; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.SwingWorker; import org.netbeans.api.progress.ProgressHandle; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.explorer.ExplorerManager; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.NodeEvent; import org.openide.nodes.NodeListener; import org.openide.nodes.NodeMemberEvent; import org.openide.nodes.NodeReorderEvent; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer; import org.sleuthkit.autopsy.coreutils.ImageUtils; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.TskCoreException; /** * Thumbnail view of images in data result with paging support. * * Paging is added to reduce memory footprint and load only up to (currently) * 1000 images at a time. This works whether or not the underlying content nodes * are being lazy loaded or not. * */ // @@@ Restore implementation of DataResultViewerThumbnail as a DataResultViewer // service provider when DataResultViewers can be made compatible with node // multi-selection actions. //@ServiceProvider(service = DataResultViewer.class) final class DataResultViewerThumbnail extends AbstractDataResultViewer { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName()); //flag to keep track if images are being loaded private int curPage; private int totalPages; private int curPageImages; private int iconSize = ImageUtils.ICON_SIZE_MEDIUM; private final PageUpdater pageUpdater = new PageUpdater(); /** * Creates a DataResultViewerThumbnail object that is compatible with node * multiple selection actions. */ public DataResultViewerThumbnail(ExplorerManager explorerManager) { super(explorerManager); initialize(); } /** * Creates a DataResultViewerThumbnail object that is NOT compatible with * node multiple selection actions. */ public DataResultViewerThumbnail() { initialize(); } @NbBundle.Messages({"DataResultViewerThumbnail.thumbnailSizeComboBox.small=Small Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.medium=Medium Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.large=Large Thumbnails" }) private void initialize() { initComponents(); iconView.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); em.addPropertyChangeListener(new ExplorerManagerNodeSelectionListener()); thumbnailSizeComboBox.setModel(new javax.swing.DefaultComboBoxModel<>( new String[] { Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_small(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_medium(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_large() })); curPage = -1; totalPages = 0; curPageImages = 0; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pageLabel = new javax.swing.JLabel(); pagesLabel = new javax.swing.JLabel(); pagePrevButton = new javax.swing.JButton(); pageNextButton = new javax.swing.JButton(); imagesLabel = new javax.swing.JLabel(); imagesRangeLabel = new javax.swing.JLabel(); pageNumLabel = new javax.swing.JLabel(); filePathLabel = new javax.swing.JLabel(); goToPageLabel = new javax.swing.JLabel(); goToPageField = new javax.swing.JTextField(); thumbnailSizeComboBox = new javax.swing.JComboBox<>(); iconView = new org.openide.explorer.view.IconView(); pageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageLabel.text")); // NOI18N pagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagesLabel.text")); // NOI18N pagePrevButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back.png"))); // NOI18N pagePrevButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagePrevButton.text")); // NOI18N pagePrevButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_disabled.png"))); // NOI18N pagePrevButton.setMargin(new java.awt.Insets(2, 0, 2, 0)); pagePrevButton.setPreferredSize(new java.awt.Dimension(55, 23)); pagePrevButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_hover.png"))); // NOI18N pagePrevButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pagePrevButtonActionPerformed(evt); } }); pageNextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward.png"))); // NOI18N pageNextButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNextButton.text")); // NOI18N pageNextButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_disabled.png"))); // NOI18N pageNextButton.setMargin(new java.awt.Insets(2, 0, 2, 0)); pageNextButton.setMaximumSize(new java.awt.Dimension(27, 23)); pageNextButton.setMinimumSize(new java.awt.Dimension(27, 23)); pageNextButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_hover.png"))); // NOI18N pageNextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pageNextButtonActionPerformed(evt); } }); imagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesLabel.text")); // NOI18N imagesRangeLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesRangeLabel.text")); // NOI18N pageNumLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNumLabel.text")); // NOI18N filePathLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.filePathLabel.text")); // NOI18N goToPageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageLabel.text")); // NOI18N goToPageField.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageField.text")); // NOI18N goToPageField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goToPageFieldActionPerformed(evt); } }); thumbnailSizeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { thumbnailSizeComboBoxActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(filePathLabel) .addGroup(layout.createSequentialGroup() .addComponent(pageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pageNumLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(goToPageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(goToPageField, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(imagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(imagesRangeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(thumbnailSizeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(iconView, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pageLabel) .addComponent(pagesLabel) .addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pageNumLabel)) .addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(imagesLabel) .addComponent(imagesRangeLabel) .addComponent(goToPageLabel) .addComponent(goToPageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(thumbnailSizeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(iconView, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filePathLabel)) ); }// </editor-fold>//GEN-END:initComponents private void pagePrevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagePrevButtonActionPerformed previousPage(); }//GEN-LAST:event_pagePrevButtonActionPerformed private void pageNextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pageNextButtonActionPerformed nextPage(); }//GEN-LAST:event_pageNextButtonActionPerformed private void goToPageFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goToPageFieldActionPerformed goToPage(goToPageField.getText()); }//GEN-LAST:event_goToPageFieldActionPerformed private void thumbnailSizeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_thumbnailSizeComboBoxActionPerformed iconSize = ImageUtils.ICON_SIZE_MEDIUM; //default size switch (thumbnailSizeComboBox.getSelectedIndex()) { case 0: iconSize = ImageUtils.ICON_SIZE_SMALL; break; case 2: iconSize = ImageUtils.ICON_SIZE_LARGE; break; } Node root = em.getRootContext(); for (Children c : Arrays.asList(root.getChildren())) { ((ThumbnailViewChildren) c).setIconSize(iconSize); } for (Node page : root.getChildren().getNodes()) { for (Node node : page.getChildren().getNodes()) { ((ThumbnailViewNode) node).setIconSize(iconSize); } } // Temporarily set the explored context to the root, instead of a child node. // This is a workaround hack to convince org.openide.explorer.ExplorerManager to // update even though the new and old Node values are identical. This in turn // will cause the entire view to update completely. After this we // immediately set the node back to the current child by calling switchPage(). em.setExploredContext(root); switchPage(); }//GEN-LAST:event_thumbnailSizeComboBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel filePathLabel; private javax.swing.JTextField goToPageField; private javax.swing.JLabel goToPageLabel; private org.openide.explorer.view.IconView iconView; private javax.swing.JLabel imagesLabel; private javax.swing.JLabel imagesRangeLabel; private javax.swing.JLabel pageLabel; private javax.swing.JButton pageNextButton; private javax.swing.JLabel pageNumLabel; private javax.swing.JButton pagePrevButton; private javax.swing.JLabel pagesLabel; private javax.swing.JComboBox<String> thumbnailSizeComboBox; // End of variables declaration//GEN-END:variables @Override public boolean isSupported(Node selectedNode) { if (selectedNode == null) { return false; } return true; } @Override public void setNode(Node givenNode) { // change the cursor to "waiting cursor" for this operation setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { if (givenNode != null) { ThumbnailViewChildren childNode = new ThumbnailViewChildren(givenNode, iconSize); final Node root = new AbstractNode(childNode); pageUpdater.setRoot(root); root.addNodeListener(pageUpdater); em.setRootContext(root); } else { Node emptyNode = new AbstractNode(Children.LEAF); em.setRootContext(emptyNode); // make empty node iconView.setBackground(Color.BLACK); } } finally { this.setCursor(null); } } @Override public String getTitle() { return NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.title"); } @Override public DataResultViewer createInstance() { return new DataResultViewerThumbnail(); } @Override public void resetComponent() { super.resetComponent(); this.totalPages = 0; this.curPage = -1; curPageImages = 0; updateControls(); } @Override public void clearComponent() { this.iconView.removeAll(); this.iconView = null; super.clearComponent(); } private void nextPage() { if (curPage < totalPages) { curPage++; switchPage(); } } private void previousPage() { if (curPage > 1) { curPage--; switchPage(); } } private void goToPage(String pageNumText) { int newPage; try { newPage = Integer.parseInt(pageNumText); } catch (NumberFormatException e) { //ignore input return; } if (newPage > totalPages || newPage < 1) { JOptionPane.showMessageDialog(this, NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.msgDlg", totalPages), NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.err"), JOptionPane.WARNING_MESSAGE); return; } curPage = newPage; switchPage(); } private void switchPage() { EventQueue.invokeLater(() -> { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); }); //Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps new SwingWorker<Object, Void>() { private ProgressHandle progress; @Override protected Object doInBackground() throws Exception { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); progress = ProgressHandle.createHandle( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.genThumbs")); progress.start(); progress.switchToIndeterminate(); Node root = em.getRootContext(); Node pageNode = root.getChildren().getNodeAt(curPage - 1); em.setExploredContext(pageNode); curPageImages = pageNode.getChildren().getNodesCount(); return null; } @Override protected void done() { progress.finish(); setCursor(null); updateControls(); // see if any exceptions were thrown try { get(); } catch (InterruptedException | ExecutionException ex) { NotifyDescriptor d = new NotifyDescriptor.Message( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.switchPage.done.errMsg", ex.getMessage()), NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(d); logger.log(Level.SEVERE, "Error making thumbnails: {0}", ex.getMessage()); //NON-NLS } // catch and ignore if we were cancelled catch (java.util.concurrent.CancellationException ex) { } } }.execute(); } private void updateControls() { if (totalPages == 0) { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); pageNumLabel.setText(""); imagesRangeLabel.setText(""); thumbnailSizeComboBox.setEnabled(false); } else { pageNumLabel.setText( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.pageNumbers.curOfTotal", Integer.toString(curPage), Integer.toString(totalPages))); final int imagesFrom = (curPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE + 1; final int imagesTo = curPageImages + (curPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE; imagesRangeLabel.setText(imagesFrom + "-" + imagesTo); pageNextButton.setEnabled(!(curPage == totalPages)); pagePrevButton.setEnabled(!(curPage == 1)); goToPageField.setEnabled(totalPages > 1); thumbnailSizeComboBox.setEnabled(true); } } /** * Listens for root change updates and updates the paging controls */ private class PageUpdater implements NodeListener { private Node root; void setRoot(Node root) { this.root = root; } @Override public void propertyChange(PropertyChangeEvent evt) { } @Override public void childrenAdded(NodeMemberEvent nme) { totalPages = root.getChildren().getNodesCount(); if (totalPages == 0) { curPage = -1; updateControls(); return; } if (curPage == -1 || curPage > totalPages) { curPage = 1; } //force load the curPage node final Node pageNode = root.getChildren().getNodeAt(curPage - 1); //em.setSelectedNodes(new Node[]{pageNode}); if (pageNode != null) { pageNode.addNodeListener(new NodeListener() { @Override public void childrenAdded(NodeMemberEvent nme) { curPageImages = pageNode.getChildren().getNodesCount(); updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { curPageImages = 0; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } @Override public void propertyChange(PropertyChangeEvent evt) { } }); em.setExploredContext(pageNode); } updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { totalPages = 0; curPage = -1; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } } private class ExplorerManagerNodeSelectionListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(ExplorerManager.PROP_SELECTED_NODES)) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Node[] selectedNodes = em.getSelectedNodes(); if (selectedNodes.length == 1) { AbstractFile af = selectedNodes[0].getLookup().lookup(AbstractFile.class); if (af == null) { filePathLabel.setText(""); } else { try { String uPath = af.getUniquePath(); filePathLabel.setText(uPath); filePathLabel.setToolTipText(uPath); } catch (TskCoreException e) { logger.log(Level.WARNING, "Could not get unique path for content: {0}", af.getName()); //NON-NLS } } } else { filePathLabel.setText(""); } } finally { setCursor(null); } } } } }
Core/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java
/* * Autopsy Forensic Browser * * Copyright 2013 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.corecomponents; import java.awt.Color; import java.awt.Cursor; import java.awt.EventQueue; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.SwingWorker; import org.netbeans.api.progress.ProgressHandle; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.explorer.ExplorerManager; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.NodeEvent; import org.openide.nodes.NodeListener; import org.openide.nodes.NodeMemberEvent; import org.openide.nodes.NodeReorderEvent; import org.openide.util.NbBundle; import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer; import org.sleuthkit.autopsy.coreutils.ImageUtils; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.TskCoreException; /** * Thumbnail view of images in data result with paging support. * * Paging is added to reduce memory footprint and load only up to (currently) * 1000 images at a time. This works whether or not the underlying content nodes * are being lazy loaded or not. * */ // @@@ Restore implementation of DataResultViewerThumbnail as a DataResultViewer // service provider when DataResultViewers can be made compatible with node // multi-selection actions. //@ServiceProvider(service = DataResultViewer.class) final class DataResultViewerThumbnail extends AbstractDataResultViewer { private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName()); //flag to keep track if images are being loaded private int curPage; private int totalPages; private int curPageImages; private int iconSize = ImageUtils.ICON_SIZE_MEDIUM; private final PageUpdater pageUpdater = new PageUpdater(); /** * Creates a DataResultViewerThumbnail object that is compatible with node * multiple selection actions. */ public DataResultViewerThumbnail(ExplorerManager explorerManager) { super(explorerManager); initialize(); } /** * Creates a DataResultViewerThumbnail object that is NOT compatible with * node multiple selection actions. */ public DataResultViewerThumbnail() { initialize(); } @NbBundle.Messages({"DataResultViewerThumbnail.thumbnailSizeComboBox.small=Small Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.medium=Medium Thumbnails", "DataResultViewerThumbnail.thumbnailSizeComboBox.large=Large Thumbnails" }) private void initialize() { initComponents(); iconView.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); em.addPropertyChangeListener(new ExplorerManagerNodeSelectionListener()); thumbnailSizeComboBox.setModel(new javax.swing.DefaultComboBoxModel<String>( new String[] { Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_small(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_medium(), Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_large() })); curPage = -1; totalPages = 0; curPageImages = 0; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pageLabel = new javax.swing.JLabel(); pagesLabel = new javax.swing.JLabel(); pagePrevButton = new javax.swing.JButton(); pageNextButton = new javax.swing.JButton(); imagesLabel = new javax.swing.JLabel(); imagesRangeLabel = new javax.swing.JLabel(); pageNumLabel = new javax.swing.JLabel(); filePathLabel = new javax.swing.JLabel(); goToPageLabel = new javax.swing.JLabel(); goToPageField = new javax.swing.JTextField(); thumbnailSizeComboBox = new javax.swing.JComboBox<>(); iconView = new org.openide.explorer.view.IconView(); pageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageLabel.text")); // NOI18N pagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagesLabel.text")); // NOI18N pagePrevButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back.png"))); // NOI18N pagePrevButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagePrevButton.text")); // NOI18N pagePrevButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_disabled.png"))); // NOI18N pagePrevButton.setMargin(new java.awt.Insets(2, 0, 2, 0)); pagePrevButton.setPreferredSize(new java.awt.Dimension(55, 23)); pagePrevButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_hover.png"))); // NOI18N pagePrevButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pagePrevButtonActionPerformed(evt); } }); pageNextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward.png"))); // NOI18N pageNextButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNextButton.text")); // NOI18N pageNextButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_disabled.png"))); // NOI18N pageNextButton.setMargin(new java.awt.Insets(2, 0, 2, 0)); pageNextButton.setMaximumSize(new java.awt.Dimension(27, 23)); pageNextButton.setMinimumSize(new java.awt.Dimension(27, 23)); pageNextButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_hover.png"))); // NOI18N pageNextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pageNextButtonActionPerformed(evt); } }); imagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesLabel.text")); // NOI18N imagesRangeLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.imagesRangeLabel.text")); // NOI18N pageNumLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNumLabel.text")); // NOI18N filePathLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.filePathLabel.text")); // NOI18N goToPageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageLabel.text")); // NOI18N goToPageField.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.goToPageField.text")); // NOI18N goToPageField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goToPageFieldActionPerformed(evt); } }); thumbnailSizeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { thumbnailSizeComboBoxActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(filePathLabel) .addGroup(layout.createSequentialGroup() .addComponent(pageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pageNumLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(goToPageLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(goToPageField, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(imagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(imagesRangeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(thumbnailSizeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(iconView, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pageLabel) .addComponent(pagesLabel) .addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pageNumLabel)) .addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(imagesLabel) .addComponent(imagesRangeLabel) .addComponent(goToPageLabel) .addComponent(goToPageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(thumbnailSizeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(iconView, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(filePathLabel)) ); }// </editor-fold>//GEN-END:initComponents private void pagePrevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagePrevButtonActionPerformed previousPage(); }//GEN-LAST:event_pagePrevButtonActionPerformed private void pageNextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pageNextButtonActionPerformed nextPage(); }//GEN-LAST:event_pageNextButtonActionPerformed private void goToPageFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goToPageFieldActionPerformed goToPage(goToPageField.getText()); }//GEN-LAST:event_goToPageFieldActionPerformed private void thumbnailSizeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_thumbnailSizeComboBoxActionPerformed iconSize = ImageUtils.ICON_SIZE_MEDIUM; //default size switch (thumbnailSizeComboBox.getSelectedIndex()) { case 0: iconSize = ImageUtils.ICON_SIZE_SMALL; break; case 2: iconSize = ImageUtils.ICON_SIZE_LARGE; break; } Node root = em.getRootContext(); for (Children c : Arrays.asList(root.getChildren())) { ((ThumbnailViewChildren) c).setIconSize(iconSize); } for (Node page : root.getChildren().getNodes()) { for (Node node : page.getChildren().getNodes()) { ((ThumbnailViewNode) node).setIconSize(iconSize); } } // Temporarily set the explored context to the root, instead of a child node. // This is a workaround hack to convince org.openide.explorer.ExplorerManager to // update even though the new and old Node values are identical. This in turn // will cause the entire view to update completely. After this we // immediately set the node back to the current child by calling switchPage(). em.setExploredContext(root); switchPage(); }//GEN-LAST:event_thumbnailSizeComboBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel filePathLabel; private javax.swing.JTextField goToPageField; private javax.swing.JLabel goToPageLabel; private org.openide.explorer.view.IconView iconView; private javax.swing.JLabel imagesLabel; private javax.swing.JLabel imagesRangeLabel; private javax.swing.JLabel pageLabel; private javax.swing.JButton pageNextButton; private javax.swing.JLabel pageNumLabel; private javax.swing.JButton pagePrevButton; private javax.swing.JLabel pagesLabel; private javax.swing.JComboBox<String> thumbnailSizeComboBox; // End of variables declaration//GEN-END:variables @Override public boolean isSupported(Node selectedNode) { if (selectedNode == null) { return false; } return true; } @Override public void setNode(Node givenNode) { // change the cursor to "waiting cursor" for this operation setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { if (givenNode != null) { ThumbnailViewChildren childNode = new ThumbnailViewChildren(givenNode, iconSize); final Node root = new AbstractNode(childNode); pageUpdater.setRoot(root); root.addNodeListener(pageUpdater); em.setRootContext(root); } else { Node emptyNode = new AbstractNode(Children.LEAF); em.setRootContext(emptyNode); // make empty node iconView.setBackground(Color.BLACK); } } finally { this.setCursor(null); } } @Override public String getTitle() { return NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.title"); } @Override public DataResultViewer createInstance() { return new DataResultViewerThumbnail(); } @Override public void resetComponent() { super.resetComponent(); this.totalPages = 0; this.curPage = -1; curPageImages = 0; updateControls(); } @Override public void clearComponent() { this.iconView.removeAll(); this.iconView = null; super.clearComponent(); } private void nextPage() { if (curPage < totalPages) { curPage++; switchPage(); } } private void previousPage() { if (curPage > 1) { curPage--; switchPage(); } } private void goToPage(String pageNumText) { int newPage; try { newPage = Integer.parseInt(pageNumText); } catch (NumberFormatException e) { //ignore input return; } if (newPage > totalPages || newPage < 1) { JOptionPane.showMessageDialog(this, NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.msgDlg", totalPages), NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.goToPageTextField.err"), JOptionPane.WARNING_MESSAGE); return; } curPage = newPage; switchPage(); } private void switchPage() { EventQueue.invokeLater(new Runnable() { @Override public void run() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } }); //Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps new SwingWorker<Object, Void>() { private ProgressHandle progress; @Override protected Object doInBackground() throws Exception { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); progress = ProgressHandle.createHandle( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.genThumbs")); progress.start(); progress.switchToIndeterminate(); Node root = em.getRootContext(); Node pageNode = root.getChildren().getNodeAt(curPage - 1); em.setExploredContext(pageNode); curPageImages = pageNode.getChildren().getNodesCount(); return null; } @Override protected void done() { progress.finish(); setCursor(null); updateControls(); // see if any exceptions were thrown try { get(); } catch (InterruptedException | ExecutionException ex) { NotifyDescriptor d = new NotifyDescriptor.Message( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.switchPage.done.errMsg", ex.getMessage()), NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(d); logger.log(Level.SEVERE, "Error making thumbnails: " + ex.getMessage()); //NON-NLS } // catch and ignore if we were cancelled catch (java.util.concurrent.CancellationException ex) { } } }.execute(); } private void updateControls() { if (totalPages == 0) { pagePrevButton.setEnabled(false); pageNextButton.setEnabled(false); goToPageField.setEnabled(false); pageNumLabel.setText(""); imagesRangeLabel.setText(""); } else { pageNumLabel.setText( NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.pageNumbers.curOfTotal", Integer.toString(curPage), Integer.toString(totalPages))); final int imagesFrom = (curPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE + 1; final int imagesTo = curPageImages + (curPage - 1) * ThumbnailViewChildren.IMAGES_PER_PAGE; imagesRangeLabel.setText(imagesFrom + "-" + imagesTo); pageNextButton.setEnabled(!(curPage == totalPages)); pagePrevButton.setEnabled(!(curPage == 1)); goToPageField.setEnabled(totalPages > 1); } } /** * Listens for root change updates and updates the paging controls */ private class PageUpdater implements NodeListener { private Node root; void setRoot(Node root) { this.root = root; } @Override public void propertyChange(PropertyChangeEvent evt) { } @Override public void childrenAdded(NodeMemberEvent nme) { totalPages = root.getChildren().getNodesCount(); if (totalPages == 0) { curPage = -1; updateControls(); return; } if (curPage == -1 || curPage > totalPages) { curPage = 1; } //force load the curPage node final Node pageNode = root.getChildren().getNodeAt(curPage - 1); //em.setSelectedNodes(new Node[]{pageNode}); if (pageNode != null) { pageNode.addNodeListener(new NodeListener() { @Override public void childrenAdded(NodeMemberEvent nme) { curPageImages = pageNode.getChildren().getNodesCount(); updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { curPageImages = 0; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } @Override public void propertyChange(PropertyChangeEvent evt) { } }); em.setExploredContext(pageNode); } updateControls(); } @Override public void childrenRemoved(NodeMemberEvent nme) { totalPages = 0; curPage = -1; updateControls(); } @Override public void childrenReordered(NodeReorderEvent nre) { } @Override public void nodeDestroyed(NodeEvent ne) { } } private class ExplorerManagerNodeSelectionListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(ExplorerManager.PROP_SELECTED_NODES)) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Node[] selectedNodes = em.getSelectedNodes(); if (selectedNodes.length == 1) { AbstractFile af = selectedNodes[0].getLookup().lookup(AbstractFile.class); if (af == null) { filePathLabel.setText(""); } else { try { String uPath = af.getUniquePath(); filePathLabel.setText(uPath); filePathLabel.setToolTipText(uPath); } catch (TskCoreException e) { logger.log(Level.WARNING, "Could not get unique path for content: {0}", af.getName()); //NON-NLS } } } else { filePathLabel.setText(""); } } finally { setCursor(null); } } } } }
Fix cause of IndexOutOfBounds exception for DataResultViewerThumbnail
Core/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java
Fix cause of IndexOutOfBounds exception for DataResultViewerThumbnail
<ide><path>ore/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java <ide> /* <ide> * Autopsy Forensic Browser <ide> * <del> * Copyright 2013 Basis Technology Corp. <add> * Copyright 2011-2016 Basis Technology Corp. <ide> * Contact: carrier <at> sleuthkit <dot> org <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> //@ServiceProvider(service = DataResultViewer.class) <ide> final class DataResultViewerThumbnail extends AbstractDataResultViewer { <ide> <add> private static final long serialVersionUID = 1L; <ide> private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName()); <ide> //flag to keep track if images are being loaded <ide> private int curPage; <ide> <ide> iconView.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); <ide> em.addPropertyChangeListener(new ExplorerManagerNodeSelectionListener()); <del> thumbnailSizeComboBox.setModel(new javax.swing.DefaultComboBoxModel<String>( <add> thumbnailSizeComboBox.setModel(new javax.swing.DefaultComboBoxModel<>( <ide> new String[] { Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_small(), <ide> Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_medium(), <ide> Bundle.DataResultViewerThumbnail_thumbnailSizeComboBox_large() })); <ide> <ide> private void switchPage() { <ide> <del> EventQueue.invokeLater(new Runnable() { <del> @Override <del> public void run() { <del> setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); <del> } <add> EventQueue.invokeLater(() -> { <add> setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); <ide> }); <ide> <ide> //Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps <ide> ex.getMessage()), <ide> NotifyDescriptor.ERROR_MESSAGE); <ide> DialogDisplayer.getDefault().notify(d); <del> logger.log(Level.SEVERE, "Error making thumbnails: " + ex.getMessage()); //NON-NLS <add> logger.log(Level.SEVERE, "Error making thumbnails: {0}", ex.getMessage()); //NON-NLS <ide> } // catch and ignore if we were cancelled <ide> catch (java.util.concurrent.CancellationException ex) { <ide> } <ide> goToPageField.setEnabled(false); <ide> pageNumLabel.setText(""); <ide> imagesRangeLabel.setText(""); <add> thumbnailSizeComboBox.setEnabled(false); <ide> } else { <ide> pageNumLabel.setText( <ide> NbBundle.getMessage(this.getClass(), "DataResultViewerThumbnail.pageNumbers.curOfTotal", <ide> pageNextButton.setEnabled(!(curPage == totalPages)); <ide> pagePrevButton.setEnabled(!(curPage == 1)); <ide> goToPageField.setEnabled(totalPages > 1); <del> <add> thumbnailSizeComboBox.setEnabled(true); <ide> } <ide> <ide> }
Java
apache-2.0
b4a7e00f5d5bd69af2e8e781ff7d991dffabe3ae
0
cauchymop/goblob,cauchymop/goblob,cauchymop/goblob
package com.cauchymop.goblob.ui; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.view.MotionEvent; import android.view.View; import com.cauchymop.goblob.R; import com.cauchymop.goblob.model.GoGame; import com.cauchymop.goblob.model.StoneColor; import com.google.common.collect.Sets; import java.util.Set; @SuppressLint("DrawAllocation") public class GoBoardView extends View { private static final Paint lastMovePaint = createLinePaint(0xFFFF0000, 5); private static final Paint linePaint = createLinePaint(0xFF000000, 1); private static final Paint textPaint = createTextPaint(0xFFFF0000, 20); private static final double STONE_RATIO = 0.95; private GoGame game; private Point lastClickedCellCoord = null; private int marginX; private int marginY; private int cellSizeInPixels; private Bitmap whiteStoneBitmap; private Bitmap blackStoneBitmap; private Set<Listener> listeners = Sets.newHashSet(); public GoBoardView(Context context, GoGame game) { super(context, null); this.game = game; setClickable(true); blackStoneBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.black_stone); whiteStoneBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.white_stone); } private static Paint createLinePaint(int color, int width) { Paint paint = new Paint(); paint.setColor(color); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(width); return paint; } private static Paint createTextPaint(int color, int size) { Paint textPaint = new Paint(); textPaint.setColor(color); textPaint.setTextSize(size); return textPaint; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int boardSizeInPixels = Math.min(getWidth(), getHeight()); marginX = (getWidth() - boardSizeInPixels) / 2; marginY = (getHeight() - boardSizeInPixels) / 2; cellSizeInPixels = boardSizeInPixels / game.getBoardSize(); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isClickable()) { return false; } final int action = event.getAction(); int nb_fingers = event.getPointerCount(); if (nb_fingers != 1) { return false; } int x = (int) ((event.getX() - marginX) / cellSizeInPixels); int y = (int) ((event.getY() - marginY) / cellSizeInPixels); if (y < 0 || y >= game.getBoardSize() || x < 0 || x >= game.getBoardSize()) { lastClickedCellCoord = null; return false; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { // Log.i("TOUCH EVENT", "ACTION_DOWN: row:" + row +" col:" + col); lastClickedCellCoord = new Point(x, y); return true; } case MotionEvent.ACTION_UP: { // Log.i("TOUCH EVENT", "ACTION_UP: row:" + row +" col:" + col); if (lastClickedCellCoord != null && lastClickedCellCoord.x == x && lastClickedCellCoord.y == y) { firePlayed(game.getMove(x, y)); lastClickedCellCoord = null; return true; } } } return false; } private void firePlayed(int move) { for (Listener listener : listeners) { listener.played(move); } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int boardSizeInPixels = Math.min(canvas.getWidth(), canvas.getHeight()); int marginX = (canvas.getWidth() - boardSizeInPixels) / 2; int marginY = (canvas.getHeight() - boardSizeInPixels) / 2; int startLineX = marginX + cellSizeInPixels / 2; int startLineY = marginY + cellSizeInPixels / 2; int lineLength = cellSizeInPixels * (game.getBoardSize() - 1); for (int x = 0; x < game.getBoardSize(); x++) { canvas.drawLine(startLineX, startLineY + cellSizeInPixels * x, startLineX + lineLength, startLineY + cellSizeInPixels * x, linePaint); canvas.drawLine(startLineX + cellSizeInPixels * x, startLineY, startLineX + cellSizeInPixels * x, startLineY + lineLength, linePaint); } double[] scores = game.getScores(); Rect rect = new Rect(); int lastMove = game.getLastMove(); for (int x = 0; x < game.getBoardSize(); x++) { for (int y = 0; y < game.getBoardSize(); y++) { StoneColor contentColor = game.getColor(x, y); if (contentColor != StoneColor.Empty) { Bitmap stoneBitmap = (contentColor == StoneColor.Black) ? blackStoneBitmap : whiteStoneBitmap; rect.set(marginX + cellSizeInPixels * x, marginY + cellSizeInPixels * y, marginX + cellSizeInPixels * (x + 1), marginY + cellSizeInPixels * (y + 1)); canvas.drawBitmap(stoneBitmap, null, rect, null); if (lastMove == game.getMove(x, y)) { canvas.drawCircle(startLineX + cellSizeInPixels * x, startLineY + cellSizeInPixels * y, (float) (cellSizeInPixels / 2), lastMovePaint); } } int pos = y * game.getBoardSize() + x; if (scores != null && !Double.isNaN(scores[pos])) { double score = scores[pos]; canvas.drawText(Double.toString(score), startLineX + cellSizeInPixels * x, startLineY + cellSizeInPixels * y, textPaint); } } } } public interface Listener { public void played(int move); } }
goblob/src/main/com/cauchymop/goblob/ui/GoBoardView.java
package com.cauchymop.goblob.ui; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.view.MotionEvent; import android.view.View; import com.cauchymop.goblob.R; import com.cauchymop.goblob.model.GoGame; import com.cauchymop.goblob.model.StoneColor; import com.google.common.collect.Sets; import java.util.Set; @SuppressLint("DrawAllocation") public class GoBoardView extends View { private static final Paint lineColor = createPaint(0xFF000000); private static final Paint textColor = createTextPaint(0xFFFF0000, 20); private static final double STONE_RATIO = 0.95; private GoGame game; private Point lastClickedCellCoord = null; private int marginX; private int marginY; private int cellSizeInPixels; private Bitmap whiteStoneBitmap; private Bitmap blackStoneBitmap; private Set<Listener> listeners = Sets.newHashSet(); public GoBoardView(Context context, GoGame game) { super(context, null); this.game = game; setClickable(true); blackStoneBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.black_stone); whiteStoneBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.white_stone); } private static Paint createPaint(int color) { Paint p = new Paint(); p.setColor(color); return p; } private static Paint createTextPaint(int color, int size) { Paint textPaint = createPaint(color); textPaint.setTextSize(size); return textPaint; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int boardSizeInPixels = Math.min(getWidth(), getHeight()); marginX = (getWidth() - boardSizeInPixels) / 2; marginY = (getHeight() - boardSizeInPixels) / 2; cellSizeInPixels = boardSizeInPixels / game.getBoardSize(); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isClickable()) { return false; } final int action = event.getAction(); int nb_fingers = event.getPointerCount(); if (nb_fingers != 1) { return false; } int x = (int) ((event.getX() - marginX) / cellSizeInPixels); int y = (int) ((event.getY() - marginY) / cellSizeInPixels); if (y < 0 || y >= game.getBoardSize() || x < 0 || x >= game.getBoardSize()) { lastClickedCellCoord = null; return false; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { // Log.i("TOUCH EVENT", "ACTION_DOWN: row:" + row +" col:" + col); lastClickedCellCoord = new Point(x, y); return true; } case MotionEvent.ACTION_UP: { // Log.i("TOUCH EVENT", "ACTION_UP: row:" + row +" col:" + col); if (lastClickedCellCoord != null && lastClickedCellCoord.x == x && lastClickedCellCoord.y == y) { firePlayed(game.getMove(x, y)); lastClickedCellCoord = null; return true; } } } return false; } private void firePlayed(int move) { for (Listener listener : listeners) { listener.played(move); } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int boardSizeInPixels = Math.min(canvas.getWidth(), canvas.getHeight()); int marginX = (canvas.getWidth() - boardSizeInPixels) / 2; int marginY = (canvas.getHeight() - boardSizeInPixels) / 2; int startLineX = marginX + cellSizeInPixels / 2; int startLineY = marginY + cellSizeInPixels / 2; int lineLength = cellSizeInPixels * (game.getBoardSize() - 1); for (int x = 0; x < game.getBoardSize(); x++) { canvas.drawLine(startLineX, startLineY + cellSizeInPixels * x, startLineX + lineLength, startLineY + cellSizeInPixels * x, lineColor); canvas.drawLine(startLineX + cellSizeInPixels * x, startLineY, startLineX + cellSizeInPixels * x, startLineY + lineLength, lineColor); } double[] scores = game.getScores(); Rect rect = new Rect(); for (int x = 0; x < game.getBoardSize(); x++) { for (int y = 0; y < game.getBoardSize(); y++) { StoneColor contentColor = game.getColor(x, y); if (contentColor != StoneColor.Empty) { Bitmap stoneBitmap = (contentColor == StoneColor.Black) ? blackStoneBitmap : whiteStoneBitmap; rect.set(marginX + cellSizeInPixels * x, marginY + cellSizeInPixels * y, marginX + cellSizeInPixels * (x + 1), marginY + cellSizeInPixels * (y + 1)); canvas.drawBitmap(stoneBitmap, null, rect, null); } int pos = y * game.getBoardSize() + x; if (scores != null && !Double.isNaN(scores[pos])) { double score = scores[pos]; canvas.drawText(Double.toString(score), startLineX + cellSizeInPixels * x, startLineY + cellSizeInPixels * y, textColor); } } } } public interface Listener { public void played(int move); } }
Shows last move.
goblob/src/main/com/cauchymop/goblob/ui/GoBoardView.java
Shows last move.
<ide><path>oblob/src/main/com/cauchymop/goblob/ui/GoBoardView.java <ide> @SuppressLint("DrawAllocation") <ide> public class GoBoardView extends View { <ide> <del> private static final Paint lineColor = createPaint(0xFF000000); <del> private static final Paint textColor = createTextPaint(0xFFFF0000, 20); <add> private static final Paint lastMovePaint = createLinePaint(0xFFFF0000, 5); <add> private static final Paint linePaint = createLinePaint(0xFF000000, 1); <add> private static final Paint textPaint = createTextPaint(0xFFFF0000, 20); <ide> <ide> private static final double STONE_RATIO = 0.95; <ide> <ide> whiteStoneBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.white_stone); <ide> } <ide> <del> private static Paint createPaint(int color) { <del> Paint p = new Paint(); <del> p.setColor(color); <del> return p; <add> private static Paint createLinePaint(int color, int width) { <add> Paint paint = new Paint(); <add> paint.setColor(color); <add> paint.setStyle(Paint.Style.STROKE); <add> paint.setStrokeWidth(width); <add> return paint; <ide> } <ide> <ide> private static Paint createTextPaint(int color, int size) { <del> Paint textPaint = createPaint(color); <add> Paint textPaint = new Paint(); <add> textPaint.setColor(color); <ide> textPaint.setTextSize(size); <ide> return textPaint; <ide> } <ide> int lineLength = cellSizeInPixels * (game.getBoardSize() - 1); <ide> for (int x = 0; x < game.getBoardSize(); x++) { <ide> canvas.drawLine(startLineX, startLineY + cellSizeInPixels * x, <del> startLineX + lineLength, startLineY + cellSizeInPixels * x, lineColor); <add> startLineX + lineLength, startLineY + cellSizeInPixels * x, linePaint); <ide> canvas.drawLine(startLineX + cellSizeInPixels * x, startLineY, <del> startLineX + cellSizeInPixels * x, startLineY + lineLength, lineColor); <add> startLineX + cellSizeInPixels * x, startLineY + lineLength, linePaint); <ide> } <ide> double[] scores = game.getScores(); <ide> Rect rect = new Rect(); <add> int lastMove = game.getLastMove(); <ide> for (int x = 0; x < game.getBoardSize(); x++) { <ide> for (int y = 0; y < game.getBoardSize(); y++) { <ide> StoneColor contentColor = game.getColor(x, y); <ide> rect.set(marginX + cellSizeInPixels * x, marginY + cellSizeInPixels * y, <ide> marginX + cellSizeInPixels * (x + 1), marginY + cellSizeInPixels * (y + 1)); <ide> canvas.drawBitmap(stoneBitmap, null, rect, null); <add> if (lastMove == game.getMove(x, y)) { <add> canvas.drawCircle(startLineX + cellSizeInPixels * x, startLineY + cellSizeInPixels * y, <add> (float) (cellSizeInPixels / 2), lastMovePaint); <add> } <ide> } <ide> int pos = y * game.getBoardSize() + x; <ide> if (scores != null && !Double.isNaN(scores[pos])) { <ide> double score = scores[pos]; <ide> canvas.drawText(Double.toString(score), startLineX + cellSizeInPixels * x, <del> startLineY + cellSizeInPixels * y, textColor); <add> startLineY + cellSizeInPixels * y, textPaint); <ide> } <ide> } <ide> }
Java
mit
eda0ae95a621be872064a97257600ff510b5bb7a
0
DemigodsRPG/Demigods3
package com.censoredsoftware.demigods.engine.util; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import com.censoredsoftware.censoredlib.util.WorldGuards; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.player.DPlayer; import com.censoredsoftware.demigods.engine.structure.Structure; import com.censoredsoftware.demigods.engine.structure.StructureData; import com.google.common.base.Predicate; public class Zones { static { WorldGuards.createFlag("STATE", "demigods", true, "ALL"); WorldGuards.registerCreatedFlag("demigods"); WorldGuards.setWhenToOverridePVP(Demigods.PLUGIN, new Predicate<EntityDamageByEntityEvent>() { @Override public boolean apply(EntityDamageByEntityEvent event) { return !Zones.inNoDemigodsZone(event.getEntity().getLocation()); } }); } /** * Returns true if <code>location</code> is within a no-PVP zone. * * @param location the location to check. * @return true/false depending on if it's a no-PVP zone or not. */ public static boolean inNoPvpZone(Location location) { if(Configs.getSettingBoolean("zones.allow_skills_anywhere")) return false; if(WorldGuards.worldGuardEnabled()) return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP) || !WorldGuards.canPVP(location); return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP); } /** * Returns true if <code>location</code> is within a no-build zone * for <code>player</code>. * * @param player the player to check. * @param location the location to check. * @return true/false depending on the position of the <code>player</code>. */ public static boolean inNoBuildZone(Player player, Location location) { if(WorldGuards.worldGuardEnabled() && !WorldGuards.canBuild(player, location)) return true; StructureData save = Structure.Util.getInRadiusWithFlag(location, Structure.Flag.NO_GRIEFING); return save != null && save.getOwner() != null && !save.getOwner().equals(DPlayer.Util.getPlayer(player).getCurrent().getId()); } public static boolean inNoDemigodsZone(Location location) { return isNoDemigodsWorld(location.getWorld()); // || WorldGuards.canWorldGuard() && WorldGuards.checkForCreatedFlagValue("demigods", "deny", location); } public static boolean isNoDemigodsWorld(World world) { return Demigods.DISABLED_WORLDS.contains(world.getName()); } }
Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/util/Zones.java
package com.censoredsoftware.demigods.engine.util; import com.censoredsoftware.censoredlib.util.WorldGuards; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.player.DPlayer; import com.censoredsoftware.demigods.engine.structure.Structure; import com.censoredsoftware.demigods.engine.structure.StructureData; import com.google.common.base.Predicate; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; public class Zones { static { WorldGuards.createFlag("STATE", "demigods", true, "ALL"); WorldGuards.registerCreatedFlag("demigods"); WorldGuards.setWhenToOverridePVP(Demigods.PLUGIN, new Predicate<EntityDamageByEntityEvent>() { @Override public boolean apply(EntityDamageByEntityEvent event) { return !Zones.inNoDemigodsZone(event.getEntity().getLocation()); } }); } /** * Returns true if <code>location</code> is within a no-PVP zone. * * @param location the location to check. * @return true/false depending on if it's a no-PVP zone or not. */ public static boolean inNoPvpZone(Location location) { if(Configs.getSettingBoolean("zones.allow_skills_anywhere")) return false; if(WorldGuards.canWorldGuard()) return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP) || !WorldGuards.canPVP(location); return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP); } /** * Returns true if <code>location</code> is within a no-build zone * for <code>player</code>. * * @param player the player to check. * @param location the location to check. * @return true/false depending on the position of the <code>player</code>. */ public static boolean inNoBuildZone(Player player, Location location) { if(WorldGuards.canWorldGuard() && !WorldGuards.canBuild(player, location)) return true; StructureData save = Structure.Util.getInRadiusWithFlag(location, Structure.Flag.NO_GRIEFING); return save != null && save.getOwner() != null && !save.getOwner().equals(DPlayer.Util.getPlayer(player).getCurrent().getId()); } public static boolean inNoDemigodsZone(Location location) { return isNoDemigodsWorld(location.getWorld()); // || WorldGuards.canWorldGuard() && WorldGuards.checkForCreatedFlagValue("demigods", "deny", location); } public static boolean isNoDemigodsWorld(World world) { return Demigods.DISABLED_WORLDS.contains(world.getName()); } }
Bad error bats! No! Go back to your cave!
Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/util/Zones.java
Bad error bats! No! Go back to your cave!
<ide><path>emigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/util/Zones.java <ide> package com.censoredsoftware.demigods.engine.util; <add> <add>import org.bukkit.Location; <add>import org.bukkit.World; <add>import org.bukkit.entity.Player; <add>import org.bukkit.event.entity.EntityDamageByEntityEvent; <ide> <ide> import com.censoredsoftware.censoredlib.util.WorldGuards; <ide> import com.censoredsoftware.demigods.engine.Demigods; <ide> import com.censoredsoftware.demigods.engine.structure.Structure; <ide> import com.censoredsoftware.demigods.engine.structure.StructureData; <ide> import com.google.common.base.Predicate; <del>import org.bukkit.Location; <del>import org.bukkit.World; <del>import org.bukkit.entity.Player; <del>import org.bukkit.event.entity.EntityDamageByEntityEvent; <ide> <ide> public class Zones <ide> { <ide> public static boolean inNoPvpZone(Location location) <ide> { <ide> if(Configs.getSettingBoolean("zones.allow_skills_anywhere")) return false; <del> if(WorldGuards.canWorldGuard()) return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP) || !WorldGuards.canPVP(location); <add> if(WorldGuards.worldGuardEnabled()) return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP) || !WorldGuards.canPVP(location); <ide> return Structure.Util.isInRadiusWithFlag(location, Structure.Flag.NO_PVP); <ide> } <ide> <ide> */ <ide> public static boolean inNoBuildZone(Player player, Location location) <ide> { <del> if(WorldGuards.canWorldGuard() && !WorldGuards.canBuild(player, location)) return true; <add> if(WorldGuards.worldGuardEnabled() && !WorldGuards.canBuild(player, location)) return true; <ide> StructureData save = Structure.Util.getInRadiusWithFlag(location, Structure.Flag.NO_GRIEFING); <ide> return save != null && save.getOwner() != null && !save.getOwner().equals(DPlayer.Util.getPlayer(player).getCurrent().getId()); <ide> }
Java
apache-2.0
ed0adc0166c498435e4d17386a84b7578e085c00
0
belaban/JGroups,danberindei/JGroups,ibrahimshbat/JGroups,slaskawi/JGroups,pruivo/JGroups,pruivo/JGroups,belaban/JGroups,ligzy/JGroups,rpelisse/JGroups,kedzie/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,deepnarsay/JGroups,rvansa/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,Sanne/JGroups,danberindei/JGroups,dimbleby/JGroups,pferraro/JGroups,Sanne/JGroups,danberindei/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,ligzy/JGroups,vjuranek/JGroups,deepnarsay/JGroups,pruivo/JGroups,belaban/JGroups,pferraro/JGroups,vjuranek/JGroups,TarantulaTechnology/JGroups,rhusar/JGroups,slaskawi/JGroups,kedzie/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,slaskawi/JGroups,kedzie/JGroups,dimbleby/JGroups,rhusar/JGroups,tristantarrant/JGroups,deepnarsay/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,rvansa/JGroups,tristantarrant/JGroups,dimbleby/JGroups,vjuranek/JGroups
package org.jgroups.tests; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.ExtendedReceiver; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.StreamingGetStateEvent; import org.jgroups.StreamingSetStateEvent; import org.jgroups.TimeoutException; import org.jgroups.View; import org.jgroups.ViewId; import org.jgroups.util.Util; /** * Tests streaming state transfer for both pull and push mode of channel * operations. Size of the transfer is configurable. Test runner should * specify "pull" and "size" parameter as JVM parameters when running this * test. If not specified default values are to use push mode and transfer * size of 100 MB. * * <p> * * To specify pull mode and size transfer of 500 MB test runner should pass * JVM parameters: * * <p> * -Dpull=true -Dsize=500 * * * @author Vladimir Blagojevic * @version $Id$ * */ public class StreamingStateTransferTest extends TestCase{ private final static String CHANNEL_PROPS="streaming-state-transfer.xml"; private final static int INITIAL_NUMBER_OF_MEMBERS=5; private int runningTime = 1000*50; // 50 secs private Random r = new Random(); private boolean usePullMode = false; private int size = 100; //100MB private final static int MEGABYTE = 1048576; public StreamingStateTransferTest(String arg0) { super(arg0); } public void testTransfer() throws Exception { long start = System.currentTimeMillis(); boolean running=true; List members=new ArrayList(); //first spawn and join for(int i =0;i<INITIAL_NUMBER_OF_MEMBERS;i++) { GroupMember member = new GroupMember(usePullMode,size); members.add(member); Thread t = new Thread(member); t.start(); Util.sleep(getRandomDelayInSeconds(10,12)*1000); } for (; running;) { //and then flip a coin if(r.nextBoolean()) { Util.sleep(getRandomDelayInSeconds(10,12)*1000); GroupMember member = new GroupMember(usePullMode,size); members.add(member); Thread t = new Thread(member); t.start(); } else if(members.size()>1) { Util.sleep(getRandomDelayInSeconds(3,8)*1000); GroupMember unluckyBastard = (GroupMember) members.get(r.nextInt(members.size())); if(!unluckyBastard.isCoordinator()) { members.remove(unluckyBastard); unluckyBastard.setRunning(false); } else { System.out.println("Not killing coordinator "); } } running =System.currentTimeMillis() - start <= runningTime; System.out.println("Running time " + ((System.currentTimeMillis()-start)/1000) + " secs"); } System.out.println("Done"); } protected int getRandomDelayInSeconds(int from,int to) { return from + r.nextInt(to-from); } protected void setUp() throws Exception { //NOTE use -Dpull=true|false -Dsize=int (size of transfer) String prop = System.getProperty("pull"); if(prop!=null) { usePullMode = prop.equalsIgnoreCase("true"); System.out.println("Using parameter usePullMode=" + usePullMode); } prop = System.getProperty("size"); if(prop!=null) { size = Integer.parseInt(System.getProperty("size")); System.out.println("Using parameter size=" + size); } super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public static Test suite() { return new TestSuite(StreamingStateTransferTest.class); } public static void main(String[] args) { String[] testCaseName={StreamingStateTransferTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } private static class GroupMember implements Runnable,ExtendedReceiver{ JChannel ch = null; View currentView; volatile boolean running = true; private int stateSize; private int bufferSize = 8*1024; private boolean usePullMode; private Random ran = new Random(); public GroupMember(boolean usePullMode,int size) { setStateSize(size*MEGABYTE); //1GB setUsePullMode(usePullMode); } public void setUsePullMode(boolean usePullMode) { this.usePullMode = usePullMode; } public String getAddress() { if(ch!=null && ch.isConnected()) { return ch.getLocalAddress().toString(); } return null; } public void setRunning(boolean b) { running=false; System.out.println("Disconnect " + getAddress()); if(ch!=null)ch.close(); } protected boolean isCoordinator() { if (ch == null) return false; Object local_addr = ch.getLocalAddress(); if (local_addr == null) return false; View view = ch.getView(); if (view == null) return false; ViewId vid = view.getVid(); if (vid == null) return false; Object coord = vid.getCoordAddress(); if (coord == null) return false; return local_addr.equals(coord); } public void setStateSize(int stateSize) { this.stateSize = stateSize; } public void run() { try { ch = new JChannel(CHANNEL_PROPS); ch.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); ch.setOpt(Channel.AUTO_GETSTATE, Boolean.TRUE); if(!usePullMode) { ch.setReceiver(this); } ch.connect("transfer"); if(ran.nextBoolean()) { ch.getState(null,5000); } else { String randomStateId = Long.toString(Math.abs(ran.nextLong()), 36); ch.getState(null,randomStateId,5000); } } catch (Exception e) { e.printStackTrace(); } while (running) { Object msgReceived = null; try { msgReceived = ch.receive(0); if (!running) { // I am not a group member anymore so // I will discard any transient message I // receive } else { if (msgReceived instanceof View) { } else if (msgReceived instanceof StreamingGetStateEvent) { StreamingGetStateEvent evt = (StreamingGetStateEvent) msgReceived; if(evt.getStateId()!=null) { this.getState(evt.getStateId(),evt.getArg()); } else { this.getState(evt.getArg()); } } else if (msgReceived instanceof StreamingSetStateEvent) { StreamingSetStateEvent evt = (StreamingSetStateEvent) msgReceived; if(evt.getStateId()!=null) { this.setState(evt.getStateId(),evt.getArg()); } else { this.setState(evt.getArg()); } } } } catch (TimeoutException e) { } catch (Exception e) { ch.close(); running = false; } } } public void getState(OutputStream ostream) { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("org/jgroups/JChannel.class"); System.out.println(Thread.currentThread() + " at " + getAddress() + " is sending state of " + (stateSize / MEGABYTE) + " MB"); int markSize = 1024*100; //100K should be enough byte buffer [] = new byte[bufferSize]; int bytesRead=-1; int size = stateSize; try { while(size>0) { stream.mark(markSize); bytesRead=stream.read(buffer); ostream.write(buffer); stream.reset(); size = size-bytesRead; } } catch (IOException e) { e.printStackTrace(); } finally { try { ostream.flush(); ostream.close(); } catch (IOException e) { e.printStackTrace(); } } } public void setState(InputStream istream) { int totalRead=0; byte buffer [] = new byte[bufferSize]; int bytesRead=-1; long start = System.currentTimeMillis(); try { while((bytesRead=istream.read(buffer))>=0) { totalRead+=bytesRead; } } catch (IOException e) { e.printStackTrace(); } finally { try { istream.close(); } catch (IOException e) { e.printStackTrace(); } } long readingTime = System.currentTimeMillis()-start; System.out.println(Thread.currentThread() + " at " + getAddress() + " read state of " + (totalRead / MEGABYTE) + " MB in " + readingTime + " msec"); } public void receive(Message msg) { } public void setState(byte[] state) { } public void viewAccepted(View new_view) { } public void suspect(Address suspected_mbr) { } public void block() { } public byte[] getState() { return null; } public byte[] getState(String state_id) { return null; } public void setState(String state_id, byte[] state) { } public void getState(String state_id, OutputStream ostream) { System.out.println("Writing partial streaming state transfer for " + state_id); getState(ostream); } public void setState(String state_id, InputStream istream) { System.out.println("Reading partial streaming state transfer for " + state_id); setState(istream); } } }
tests/junit/org/jgroups/tests/StreamingStateTransferTest.java
package org.jgroups.tests; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.ExtendedReceiver; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.StreamingGetStateEvent; import org.jgroups.StreamingSetStateEvent; import org.jgroups.TimeoutException; import org.jgroups.View; import org.jgroups.ViewId; import org.jgroups.util.Util; /** * Tests streaming state transfer for both pull and push mode of channel * operations. Size of the transfer is configurable. Test runner should * specify "pull" and "size" parameter as JVM parameters when running this * test. If not specified default values are to use push mode and transfer * size of 100 MB. * * <p> * * To specify pull mode and size transfer of 500 MB test runner should pass * JVM parameters: * * <p> * -Dpull=true -Dsize=500 * * * @author Vladimir Blagojevic * @version $Id$ * */ public class StreamingStateTransferTest extends TestCase{ private final static String CHANNEL_PROPS="streaming-state-transfer.xml"; private final static int INITIAL_NUMBER_OF_MEMBERS=5; private int runningTime = 1000*60*3; //3 minutes private Random r = new Random(); private boolean usePullMode = false; private int size = 100; //100MB private final static int MEGABYTE = 1048576; public StreamingStateTransferTest(String arg0) { super(arg0); } public void testTransfer() throws Exception { long start = System.currentTimeMillis(); boolean running=true; List members=new ArrayList(); //first spawn and join for(int i =0;i<INITIAL_NUMBER_OF_MEMBERS;i++) { GroupMember member = new GroupMember(usePullMode,size); members.add(member); Thread t = new Thread(member); t.start(); Util.sleep(getRandomDelayInSeconds(10,12)*1000); } for (; running;) { //and then flip a coin if(r.nextBoolean()) { Util.sleep(getRandomDelayInSeconds(10,12)*1000); GroupMember member = new GroupMember(usePullMode,size); members.add(member); Thread t = new Thread(member); t.start(); } else if(members.size()>1) { Util.sleep(getRandomDelayInSeconds(3,8)*1000); GroupMember unluckyBastard = (GroupMember) members.get(r.nextInt(members.size())); if(!unluckyBastard.isCoordinator()) { members.remove(unluckyBastard); unluckyBastard.setRunning(false); } else { System.out.println("Not killing coordinator "); } } running = System.currentTimeMillis()-start>runningTime?false:true; System.out.println("Running time " + ((System.currentTimeMillis()-start)/1000) + " secs"); } System.out.println("Done"); } protected int getRandomDelayInSeconds(int from,int to) { return from + r.nextInt(to-from); } protected void setUp() throws Exception { //NOTE use -Dpull=true|false -Dsize=int (size of transfer) String prop = System.getProperty("pull"); if(prop!=null) { usePullMode = prop.equalsIgnoreCase("true"); System.out.println("Using parameter usePullMode=" + usePullMode); } prop = System.getProperty("size"); if(prop!=null) { size = Integer.parseInt(System.getProperty("size")); System.out.println("Using parameter size=" + size); } super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public static Test suite() { return new TestSuite(StreamingStateTransferTest.class); } public static void main(String[] args) { String[] testCaseName={StreamingStateTransferTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } private static class GroupMember implements Runnable,ExtendedReceiver{ JChannel ch = null; View currentView; volatile boolean running = true; private int stateSize; private int bufferSize = 8*1024; private boolean usePullMode; private Random ran = new Random(); public GroupMember(boolean usePullMode,int size) { setStateSize(size*MEGABYTE); //1GB setUsePullMode(usePullMode); } public void setUsePullMode(boolean usePullMode) { this.usePullMode = usePullMode; } public String getAddress() { if(ch!=null && ch.isConnected()) { return ch.getLocalAddress().toString(); } return null; } public void setRunning(boolean b) { running=false; System.out.println("Disconnect " + getAddress()); if(ch!=null)ch.close(); } protected boolean isCoordinator() { if (ch == null) return false; Object local_addr = ch.getLocalAddress(); if (local_addr == null) return false; View view = ch.getView(); if (view == null) return false; ViewId vid = view.getVid(); if (vid == null) return false; Object coord = vid.getCoordAddress(); if (coord == null) return false; return local_addr.equals(coord); } public void setStateSize(int stateSize) { this.stateSize = stateSize; } public void run() { try { ch = new JChannel(CHANNEL_PROPS); ch.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); ch.setOpt(Channel.AUTO_GETSTATE, Boolean.TRUE); if(!usePullMode) { ch.setReceiver(this); } ch.connect("transfer"); if(ran.nextBoolean()) { ch.getState(null,5000); } else { String randomStateId = Long.toString(Math.abs(ran.nextLong()), 36); ch.getState(null,randomStateId,5000); } } catch (Exception e) { e.printStackTrace(); } while (running) { Object msgReceived = null; try { msgReceived = ch.receive(0); if (!running) { // I am not a group member anymore so // I will discard any transient message I // receive } else { if (msgReceived instanceof View) { } else if (msgReceived instanceof StreamingGetStateEvent) { StreamingGetStateEvent evt = (StreamingGetStateEvent) msgReceived; if(evt.getStateId()!=null) { this.getState(evt.getStateId(),evt.getArg()); } else { this.getState(evt.getArg()); } } else if (msgReceived instanceof StreamingSetStateEvent) { StreamingSetStateEvent evt = (StreamingSetStateEvent) msgReceived; if(evt.getStateId()!=null) { this.setState(evt.getStateId(),evt.getArg()); } else { this.setState(evt.getArg()); } } } } catch (TimeoutException e) { } catch (Exception e) { ch.close(); running = false; } } } public void getState(OutputStream ostream) { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("org/jgroups/JChannel.class"); System.out.println(Thread.currentThread() + " at " + getAddress() + " is sending state of " + (stateSize / MEGABYTE) + " MB"); int markSize = 1024*100; //100K should be enough byte buffer [] = new byte[bufferSize]; int bytesRead=-1; int size = stateSize; try { while(size>0) { stream.mark(markSize); bytesRead=stream.read(buffer); ostream.write(buffer); stream.reset(); size = size-bytesRead; } } catch (IOException e) { e.printStackTrace(); } finally { try { ostream.flush(); ostream.close(); } catch (IOException e) { e.printStackTrace(); } } } public void setState(InputStream istream) { int totalRead=0; byte buffer [] = new byte[bufferSize]; int bytesRead=-1; long start = System.currentTimeMillis(); try { while((bytesRead=istream.read(buffer))>=0) { totalRead+=bytesRead; } } catch (IOException e) { e.printStackTrace(); } finally { try { istream.close(); } catch (IOException e) { e.printStackTrace(); } } long readingTime = System.currentTimeMillis()-start; System.out.println(Thread.currentThread() + " at " + getAddress() + " read state of " + (totalRead / MEGABYTE) + " MB in " + readingTime + " msec"); } public void receive(Message msg) { } public void setState(byte[] state) { } public void viewAccepted(View new_view) { } public void suspect(Address suspected_mbr) { } public void block() { } public byte[] getState() { return null; } public byte[] getState(String state_id) { return null; } public void setState(String state_id, byte[] state) { } public void getState(String state_id, OutputStream ostream) { System.out.println("Writing partial streaming state transfer for " + state_id); getState(ostream); } public void setState(String state_id, InputStream istream) { System.out.println("Reading partial streaming state transfer for " + state_id); setState(istream); } } }
reduced running time from 3m to 50s, to complete under 120s (mandated by unit tests)
tests/junit/org/jgroups/tests/StreamingStateTransferTest.java
reduced running time from 3m to 50s, to complete under 120s (mandated by unit tests)
<ide><path>ests/junit/org/jgroups/tests/StreamingStateTransferTest.java <ide> <ide> private final static String CHANNEL_PROPS="streaming-state-transfer.xml"; <ide> private final static int INITIAL_NUMBER_OF_MEMBERS=5; <del> private int runningTime = 1000*60*3; //3 minutes <add> private int runningTime = 1000*50; // 50 secs <ide> private Random r = new Random(); <ide> private boolean usePullMode = false; <ide> private int size = 100; //100MB <ide> System.out.println("Not killing coordinator "); <ide> } <ide> } <del> running = System.currentTimeMillis()-start>runningTime?false:true; <add> running =System.currentTimeMillis() - start <= runningTime; <ide> System.out.println("Running time " + ((System.currentTimeMillis()-start)/1000) + " secs"); <ide> } <ide> System.out.println("Done");
Java
apache-2.0
b5e7f6f851fbc29eea5a1001db78b5ec0ac25e2d
0
cherryhill/collectionspace-application
package org.collectionspace.chain.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.TTYOutputter; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.collectionspace.csp.api.ui.UISession; import org.collectionspace.csp.api.ui.UIUmbrella; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class WebUIRequest implements UIRequest { private static final String COOKIENAME="CSPACESESSID"; private HttpServletRequest request; private HttpServletResponse response; private String[] ppath,rpath=null; private boolean failure=false,secondary_redirect=false; private Exception failing_exception; private Operation operation_performed=Operation.READ; private Map<String,String> rargs=new HashMap<String,String>(); private PrintWriter out=null; private String out_data=null; // We store to allow late changes to headers private String body; // XXX what if it's binary? private WebUIUmbrella umbrella; private WebUISession session; private boolean solidified=false; public WebUIRequest(UIUmbrella umbrella,HttpServletRequest request,HttpServletResponse response) throws IOException, UIException { this.request=request; this.response=response; List<String> p=new ArrayList<String>(); for(String part : request.getPathInfo().split("/")) { if("".equals(part)) continue; p.add(part); } this.ppath=p.toArray(new String[0]); body=IOUtils.toString(request.getInputStream(),"UTF-8"); if(!(umbrella instanceof WebUIUmbrella)) throw new UIException("Bad umbrella"); this.umbrella=(WebUIUmbrella)umbrella; session=calculateSessionId(); } private WebUISession calculateSessionId() throws UIException { Cookie[] cookies=request.getCookies(); if(cookies==null) cookies=new Cookie[0]; for(Cookie cookie : cookies) { if(!COOKIENAME.equals(cookie.getName())) continue; WebUISession session=umbrella.getSession(cookie.getValue()); if(session!=null) return session; } // No valid session: make our own return umbrella.createSession(); } // XXX expire sessions private void setSession() { if(session.isOld()) return; // No need to reset session Cookie cookie=new Cookie(COOKIENAME,session.getID()); cookie.setPath("/"); response.addCookie(cookie); } // NOTE No changes to solidified stuff can happen after you get the TTY outputter public TTYOutputter getTTYOutputter() throws UIException { try { WebTTYOutputter tty=new WebTTYOutputter(response); solidify(false); out=tty.getWriter(); return tty; } catch (IOException e) { throw new UIException("Cannot create response PrintWriter",e); } } public String[] getPrincipalPath() throws UIException { return ppath; } public void setFailure(boolean isit, Exception why) throws UIException { failure=isit; failing_exception=why; } public void setOperationPerformed(Operation op) throws UIException { operation_performed=op; } public void setRedirectPath(String[] in) throws UIException { rpath=in; secondary_redirect=false; } public void setSecondaryRedirectPath(String[] in) throws UIException { rpath=in; secondary_redirect=true; } public void deleteRedirectArgument(String key) throws UIException { rargs.remove(key); } public String getRedirectArgument(String key) throws UIException { return rargs.get(key); } public void setRedirectArgument(String key, String value) throws UIException { rargs.put(key,value); } public String getRequestArgument(String key) throws UIException { return request.getParameter(key); } public Set<String> getAllRequestArgument() throws UIException { Set<String> params = new HashSet<String>(); Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); params.add(name); } return params; } public Operation getRequestedOperation() throws UIException { String method=request.getMethod(); if("POST".equals(method)) return Operation.CREATE; else if("PUT".equals(method)) return Operation.UPDATE; else if("DELETE".equals(method)) return Operation.DELETE; else if("GET".equals(method)) return Operation.READ; return Operation.READ; } private void set_status() { switch(operation_performed) { case CREATE: response.setStatus(201); break; default: response.setStatus(200); } } private String aWhileAgoAsExpectedByExpiresHeader() { SimpleDateFormat format=new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz"); Date a_while_ago=new Date(new Date().getTime()-24*60*60*1000); return format.format(a_while_ago); } private void close() { if(out!=null) out.close(); out=null; } public void solidify(boolean close) throws UIException { try { if(out_data!=null) { out=response.getWriter(); out.print(out_data); out_data=null; } if(solidified) { if(close) close(); return; } solidified=true; /* We always disable cacheing for now (for IE). We probably want to be cleverer at some point. XXX */ response.addHeader("Pragma","no-cache"); response.addHeader("Last-Modified",aWhileAgoAsExpectedByExpiresHeader()); response.addHeader("Cache-Control","no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control","post-check=0, pre-check=0"); /* End of cacheing stuff */ if(failure) { // Failed response.setStatus(400); if(failing_exception!=null) response.sendError(400,ExceptionUtils.getFullStackTrace(failing_exception)); else response.sendError(400,"No underlying exception"); } else { // Success setSession(); if(rpath!=null) { // Redirect StringBuffer path=new StringBuffer(); for(String part : rpath) { if("".equals(part)) continue; path.append('/'); path.append(part); } boolean first=true; for(Map.Entry<String,String> e : rargs.entrySet()) { path.append(first?'?':'&'); first=false; path.append(URLEncoder.encode(e.getKey(),"UTF-8")); path.append('='); path.append(URLEncoder.encode(e.getValue(),"UTF-8")); } if(secondary_redirect) set_status(); else response.setStatus(303); response.setHeader("Location",path.toString()); } else { set_status(); } } if(close) close(); } catch (IOException e) { throw new UIException("Could not send error",e); } } public void sendJSONResponse(JSONObject data) throws UIException { response.setContentType("text/json;charset=UTF-8"); out_data=data.toString(); } public void sendJSONResponse(JSONArray data) throws UIException { response.setContentType("text/json;charset=UTF-8"); out_data=data.toString(); } public JSONObject getPostBody() throws UIException { JSONObject jsondata = new JSONObject(); String jsonString = body; try { if(jsonString.length()>0){ String[] data = jsonString.split("&"); for(String item : data){ String[] itembits = item.split("="); jsondata.put(URLDecoder.decode(itembits[0],"UTF-8"), URLDecoder.decode(itembits[1],"UTF-8")); } } } catch (JSONException e) { throw new UIException("Cannot get request body, JSONException",e); } catch (UnsupportedEncodingException e) { throw new UIException("Cannot get request body, UnsupportedEncodingException",e); } return jsondata; } public Boolean isJSON() throws UIException { try{ new JSONObject(body); return true; } catch (JSONException e){ return false; } } public JSONObject getJSONBody() throws UIException { try { String jsonString = body; if (StringUtils.isBlank(jsonString)) { throw new UIException("No JSON content to store"); } // Store it return new JSONObject(jsonString); } catch (JSONException e) { throw new UIException("Cannot get request body, JSONException",e); } } public UISession getSession() throws UIException { return session; } public Storage resetStorage() { return umbrella.getWebUI().regenerateStorage(session); } }
tomcat-main/src/main/java/org/collectionspace/chain/controller/WebUIRequest.java
package org.collectionspace.chain.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.TTYOutputter; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.collectionspace.csp.api.ui.UISession; import org.collectionspace.csp.api.ui.UIUmbrella; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class WebUIRequest implements UIRequest { private static final String COOKIENAME="CSPACESESSID"; private HttpServletRequest request; private HttpServletResponse response; private String[] ppath,rpath=null; private boolean failure=false,secondary_redirect=false; private Exception failing_exception; private Operation operation_performed=Operation.READ; private Map<String,String> rargs=new HashMap<String,String>(); private PrintWriter out=null; private String out_data=null; // We store to allow late changes to headers private String body; // XXX what if it's binary? private WebUIUmbrella umbrella; private WebUISession session; private boolean solidified=false; public WebUIRequest(UIUmbrella umbrella,HttpServletRequest request,HttpServletResponse response) throws IOException, UIException { this.request=request; this.response=response; List<String> p=new ArrayList<String>(); for(String part : request.getPathInfo().split("/")) { if("".equals(part)) continue; p.add(part); } this.ppath=p.toArray(new String[0]); body=IOUtils.toString(request.getInputStream(),"UTF-8"); if(!(umbrella instanceof WebUIUmbrella)) throw new UIException("Bad umbrella"); this.umbrella=(WebUIUmbrella)umbrella; session=calculateSessionId(); } private WebUISession calculateSessionId() throws UIException { Cookie[] cookies=request.getCookies(); if(cookies==null) cookies=new Cookie[0]; for(Cookie cookie : cookies) { if(!COOKIENAME.equals(cookie.getName())) continue; WebUISession session=umbrella.getSession(cookie.getValue()); if(session!=null) return session; } // No valid session: make our own return umbrella.createSession(); } // XXX expire sessions private void setSession() { if(session.isOld()) return; // No need to reset session Cookie cookie=new Cookie(COOKIENAME,session.getID()); response.addCookie(cookie); } // NOTE No changes to solidified stuff can happen after you get the TTY outputter public TTYOutputter getTTYOutputter() throws UIException { try { WebTTYOutputter tty=new WebTTYOutputter(response); solidify(false); out=tty.getWriter(); return tty; } catch (IOException e) { throw new UIException("Cannot create response PrintWriter",e); } } public String[] getPrincipalPath() throws UIException { return ppath; } public void setFailure(boolean isit, Exception why) throws UIException { failure=isit; failing_exception=why; } public void setOperationPerformed(Operation op) throws UIException { operation_performed=op; } public void setRedirectPath(String[] in) throws UIException { rpath=in; secondary_redirect=false; } public void setSecondaryRedirectPath(String[] in) throws UIException { rpath=in; secondary_redirect=true; } public void deleteRedirectArgument(String key) throws UIException { rargs.remove(key); } public String getRedirectArgument(String key) throws UIException { return rargs.get(key); } public void setRedirectArgument(String key, String value) throws UIException { rargs.put(key,value); } public String getRequestArgument(String key) throws UIException { return request.getParameter(key); } public Set<String> getAllRequestArgument() throws UIException { Set<String> params = new HashSet<String>(); Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); params.add(name); } return params; } public Operation getRequestedOperation() throws UIException { String method=request.getMethod(); if("POST".equals(method)) return Operation.CREATE; else if("PUT".equals(method)) return Operation.UPDATE; else if("DELETE".equals(method)) return Operation.DELETE; else if("GET".equals(method)) return Operation.READ; return Operation.READ; } private void set_status() { switch(operation_performed) { case CREATE: response.setStatus(201); break; default: response.setStatus(200); } } private String aWhileAgoAsExpectedByExpiresHeader() { SimpleDateFormat format=new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz"); Date a_while_ago=new Date(new Date().getTime()-24*60*60*1000); return format.format(a_while_ago); } private void close() { if(out!=null) out.close(); out=null; } public void solidify(boolean close) throws UIException { try { if(out_data!=null) { out=response.getWriter(); out.print(out_data); out_data=null; } if(solidified) { if(close) close(); return; } solidified=true; /* We always disable cacheing for now (for IE). We probably want to be cleverer at some point. XXX */ response.addHeader("Pragma","no-cache"); response.addHeader("Last-Modified",aWhileAgoAsExpectedByExpiresHeader()); response.addHeader("Cache-Control","no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control","post-check=0, pre-check=0"); /* End of cacheing stuff */ if(failure) { // Failed response.setStatus(400); if(failing_exception!=null) response.sendError(400,ExceptionUtils.getFullStackTrace(failing_exception)); else response.sendError(400,"No underlying exception"); } else { // Success setSession(); if(rpath!=null) { // Redirect StringBuffer path=new StringBuffer(); for(String part : rpath) { if("".equals(part)) continue; path.append('/'); path.append(part); } boolean first=true; for(Map.Entry<String,String> e : rargs.entrySet()) { path.append(first?'?':'&'); first=false; path.append(URLEncoder.encode(e.getKey(),"UTF-8")); path.append('='); path.append(URLEncoder.encode(e.getValue(),"UTF-8")); } if(secondary_redirect) set_status(); else response.setStatus(303); response.setHeader("Location",path.toString()); } else { set_status(); } } if(close) close(); } catch (IOException e) { throw new UIException("Could not send error",e); } } public void sendJSONResponse(JSONObject data) throws UIException { response.setContentType("text/json;charset=UTF-8"); out_data=data.toString(); } public void sendJSONResponse(JSONArray data) throws UIException { response.setContentType("text/json;charset=UTF-8"); out_data=data.toString(); } public JSONObject getPostBody() throws UIException { JSONObject jsondata = new JSONObject(); String jsonString = body; try { if(jsonString.length()>0){ String[] data = jsonString.split("&"); for(String item : data){ String[] itembits = item.split("="); jsondata.put(URLDecoder.decode(itembits[0],"UTF-8"), URLDecoder.decode(itembits[1],"UTF-8")); } } } catch (JSONException e) { throw new UIException("Cannot get request body, JSONException",e); } catch (UnsupportedEncodingException e) { throw new UIException("Cannot get request body, UnsupportedEncodingException",e); } return jsondata; } public Boolean isJSON() throws UIException { try{ new JSONObject(body); return true; } catch (JSONException e){ return false; } } public JSONObject getJSONBody() throws UIException { try { String jsonString = body; if (StringUtils.isBlank(jsonString)) { throw new UIException("No JSON content to store"); } // Store it return new JSONObject(jsonString); } catch (JSONException e) { throw new UIException("Cannot get request body, JSONException",e); } } public UISession getSession() throws UIException { return session; } public Storage resetStorage() { return umbrella.getWebUI().regenerateStorage(session); } }
CSPACE-3050
tomcat-main/src/main/java/org/collectionspace/chain/controller/WebUIRequest.java
CSPACE-3050
<ide><path>omcat-main/src/main/java/org/collectionspace/chain/controller/WebUIRequest.java <ide> if(session.isOld()) <ide> return; // No need to reset session <ide> Cookie cookie=new Cookie(COOKIENAME,session.getID()); <add> cookie.setPath("/"); <ide> response.addCookie(cookie); <ide> } <ide>
Java
apache-2.0
a396c5d1b1d5af0ddcfdfed19991e214f8c6a3e3
0
sdcuike/java8-learning
package com.doctor.thread; /** * @author sdcuike * @date 2019-07-21 */ public final class SynchronizedKeyWord { public static void main(String[] args) { SynchronizedKeyWord synchronizedKeyWord = new SynchronizedKeyWord(); synchronizedKeyWord.method(); synchronizedKeyWord.method2(); SynchronizedKeyWord.method3(); SynchronizedKeyWord.method5(); } public synchronized void method() { System.out.println("method:" + Thread.holdsLock(this)); } public void method2() { synchronized (this) { System.out.println("method:" + Thread.holdsLock(this)); } } public static synchronized void method3() { System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); } public static void method5() { synchronized (SynchronizedKeyWord.class) { System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); } } }
src/main/java/com/doctor/thread/SynchronizedKeyWord.java
package com.doctor.thread; /** * @author sdcuike * @date 2019-07-21 */ public final class SynchronizedKeyWord { public static void main(String[] args) { SynchronizedKeyWord synchronizedKeyWord = new SynchronizedKeyWord(); synchronizedKeyWord.method(); synchronizedKeyWord.method2(); SynchronizedKeyWord.method3(); SynchronizedKeyWord.method5(); } public synchronized void method() { System.out.println("method:" + Thread.holdsLock(this)); } public void method2() { synchronized (this) { System.out.println("method:" + Thread.holdsLock(this)); } } public static synchronized void method3() { System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); } public static synchronized void method5() { System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); } }
feat:SynchronizedKeyWord
src/main/java/com/doctor/thread/SynchronizedKeyWord.java
feat:SynchronizedKeyWord
<ide><path>rc/main/java/com/doctor/thread/SynchronizedKeyWord.java <ide> System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); <ide> } <ide> <del> public static synchronized void method5() { <del> System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); <del> <add> public static void method5() { <add> synchronized (SynchronizedKeyWord.class) { <add> System.out.println("method:" + Thread.holdsLock(SynchronizedKeyWord.class)); <add> } <ide> } <ide> <ide> }
Java
apache-2.0
1b4e514cff0cde920e052fcb5a0ae2760f7cfc48
0
3dcitydb/importer-exporter,3dcitydb/importer-exporter,3dcitydb/importer-exporter
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.core.operation.importer.concurrent; import org.citydb.config.Config; import org.citydb.config.project.global.LogLevel; import org.citydb.core.database.adapter.AbstractDatabaseAdapter; import org.citydb.core.database.schema.mapping.SchemaMapping; import org.citydb.core.operation.common.cache.IdCacheManager; import org.citydb.core.operation.common.xlink.DBXlink; import org.citydb.core.operation.importer.CityGMLImportException; import org.citydb.core.operation.importer.database.content.CityGMLImportManager; import org.citydb.core.operation.importer.filter.CityGMLFilter; import org.citydb.core.operation.importer.util.AffineTransformer; import org.citydb.core.operation.importer.util.ImportLogger; import org.citydb.core.operation.importer.util.ImportLogger.ImportLogEntry; import org.citydb.core.operation.importer.util.InternalConfig; import org.citydb.core.plugin.PluginException; import org.citydb.core.plugin.PluginManager; import org.citydb.core.plugin.extension.importer.FeatureImportExtension; import org.citydb.util.concurrent.Worker; import org.citydb.util.concurrent.WorkerPool; import org.citydb.util.event.Event; import org.citydb.util.event.EventDispatcher; import org.citydb.util.event.EventHandler; import org.citydb.util.event.global.*; import org.citydb.util.log.Logger; import org.citygml4j.builder.jaxb.CityGMLBuilder; import org.citygml4j.model.citygml.CityGML; import org.citygml4j.model.citygml.appearance.Appearance; import org.citygml4j.model.gml.base.AbstractGML; import org.citygml4j.model.gml.feature.AbstractFeature; import org.citygml4j.util.bbox.BoundingBoxOptions; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.concurrent.locks.ReentrantLock; public class DBImportWorker extends Worker<CityGML> implements EventHandler { private final ReentrantLock runLock = new ReentrantLock(); private volatile boolean shouldRun = true; private volatile boolean shouldWork = true; private final Connection connection; private final boolean isManagedTransaction; private final CityGMLFilter filter; private final ImportLogger importLogger; private final EventDispatcher eventDispatcher; private final BoundingBoxOptions bboxOptions; private final CityGMLImportManager importer; private final List<FeatureImportExtension> plugins; private int globalAppearanceCounter = 0; private int topLevelFeatureCounter = 0; private int commitAfter; public DBImportWorker(Connection connection, boolean isManagedTransaction, AbstractDatabaseAdapter databaseAdapter, SchemaMapping schemaMapping, CityGMLBuilder cityGMLBuilder, WorkerPool<DBXlink> xlinkPool, IdCacheManager idCacheManager, CityGMLFilter filter, AffineTransformer affineTransformer, ImportLogger importLogger, InternalConfig internalConfig, Config config, EventDispatcher eventDispatcher) throws SQLException { this.connection = connection; this.isManagedTransaction = isManagedTransaction; this.filter = filter; this.importLogger = importLogger; this.eventDispatcher = eventDispatcher; importer = new CityGMLImportManager(connection, databaseAdapter, schemaMapping, cityGMLBuilder, xlinkPool, idCacheManager, affineTransformer, internalConfig, config); commitAfter = config.getDatabaseConfig().getImportBatching().getFeatureBatchSize(); if (commitAfter > databaseAdapter.getMaxBatchSize()) { commitAfter = databaseAdapter.getMaxBatchSize(); } bboxOptions = BoundingBoxOptions.defaults() .useExistingEnvelopes(true) .assignResultToFeatures(true) .useReferencePointAsFallbackForImplicitGeometries(true); plugins = PluginManager.getInstance().getEnabledExternalPlugins(FeatureImportExtension.class); eventDispatcher.addEventHandler(EventType.INTERRUPT, this); } @Override public void interrupt() { shouldRun = false; } @Override public void run() { try { if (firstWork != null) { doWork(firstWork); firstWork = null; } while (shouldRun) { try { CityGML work = workQueue.take(); doWork(work); } catch (InterruptedException ie) { // re-check state } } try { if (shouldWork) { importer.executeBatch(); if (!isManagedTransaction) { connection.commit(); } updateImportContext(); } } catch (IOException e) { eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred while updating the import log.", LogLevel.ERROR, e, eventChannel, this)); } catch (Throwable e) { if (!isManagedTransaction) { try { connection.rollback(); } catch (SQLException sql) { // } } eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during import.", LogLevel.ERROR, e, eventChannel, this)); } } finally { try { importer.close(); } catch (CityGMLImportException | SQLException e) { // } if (!isManagedTransaction) { try { connection.close(); } catch (SQLException e) { // } } eventDispatcher.removeEventHandler(this); } } private void doWork(CityGML work) { final ReentrantLock runLock = this.runLock; runLock.lock(); try { if (!shouldWork) { return; } if (work instanceof AbstractFeature) { AbstractFeature feature = (AbstractFeature) work; // invoke import plugins if (!plugins.isEmpty()) { for (FeatureImportExtension plugin : plugins) { try { feature = plugin.process(feature); if (feature == null) { return; } } catch (PluginException e) { throw new CityGMLImportException("Import plugin " + plugin.getClass().getName() + " threw an exception.", e); } } } long id; if (feature instanceof Appearance) { // global appearance id = importer.importGlobalAppearance((Appearance) feature); if (id != 0) { globalAppearanceCounter++; } } else { // compute bounding box feature.calcBoundedBy(bboxOptions); // check import filter if (!filter.getSelectionFilter().isSatisfiedBy(feature)) { return; } id = importer.importObject(feature); if (id != 0) { topLevelFeatureCounter++; } } if (id == 0) { importer.logOrThrowErrorMessage("Failed to import object " + importer.getObjectSignature(feature) + "."); } else if (globalAppearanceCounter + topLevelFeatureCounter == commitAfter) { importer.executeBatch(); if (!isManagedTransaction) { connection.commit(); } updateImportContext(); } } else { String msg = (work instanceof AbstractGML ? importer.getObjectSignature((AbstractGML) work) : work.getCityGMLClass()) + ": Unsupported top-level object type. Skipping import."; if (!importer.isFailOnError()) { Logger.getInstance().error(msg); } else { throw new CityGMLImportException(msg); } } } catch (IOException e) { eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during update of import log.", LogLevel.ERROR, e, eventChannel, this)); } catch (Throwable e) { try { connection.rollback(); } catch (SQLException sql) { // } eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during import.", LogLevel.ERROR, e, eventChannel, this)); } finally { runLock.unlock(); } } private void updateImportContext() throws IOException { eventDispatcher.triggerEvent(new ObjectCounterEvent(importer.getAndResetObjectCounter(), this)); eventDispatcher.triggerEvent(new GeometryCounterEvent(importer.getAndResetGeometryCounter(), this)); eventDispatcher.triggerEvent(new CounterEvent(CounterType.GLOBAL_APPEARANCE, globalAppearanceCounter, this)); eventDispatcher.triggerEvent(new CounterEvent(CounterType.TOPLEVEL_FEATURE, topLevelFeatureCounter, this)); globalAppearanceCounter = 0; topLevelFeatureCounter = 0; // log imported top-level features if (importLogger != null) { for (ImportLogEntry entry : importer.getAndResetImportLogEntries()) { importLogger.write(entry); } } } @Override public void handleEvent(Event event) throws Exception { if (event.getChannel() == eventChannel) { shouldWork = false; } } }
impexp-core/src/main/java/org/citydb/core/operation/importer/concurrent/DBImportWorker.java
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.core.operation.importer.concurrent; import org.citydb.config.Config; import org.citydb.config.project.global.LogLevel; import org.citydb.core.database.adapter.AbstractDatabaseAdapter; import org.citydb.core.database.schema.mapping.SchemaMapping; import org.citydb.core.operation.common.cache.IdCacheManager; import org.citydb.core.operation.common.xlink.DBXlink; import org.citydb.core.operation.importer.CityGMLImportException; import org.citydb.core.operation.importer.database.content.CityGMLImportManager; import org.citydb.core.operation.importer.filter.CityGMLFilter; import org.citydb.core.operation.importer.util.AffineTransformer; import org.citydb.core.operation.importer.util.ImportLogger; import org.citydb.core.operation.importer.util.ImportLogger.ImportLogEntry; import org.citydb.core.operation.importer.util.InternalConfig; import org.citydb.core.plugin.PluginException; import org.citydb.core.plugin.PluginManager; import org.citydb.core.plugin.extension.importer.FeatureImportExtension; import org.citydb.util.concurrent.Worker; import org.citydb.util.concurrent.WorkerPool; import org.citydb.util.event.Event; import org.citydb.util.event.EventDispatcher; import org.citydb.util.event.EventHandler; import org.citydb.util.event.global.*; import org.citydb.util.log.Logger; import org.citygml4j.builder.jaxb.CityGMLBuilder; import org.citygml4j.model.citygml.CityGML; import org.citygml4j.model.citygml.appearance.Appearance; import org.citygml4j.model.gml.base.AbstractGML; import org.citygml4j.model.gml.feature.AbstractFeature; import org.citygml4j.util.bbox.BoundingBoxOptions; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.concurrent.locks.ReentrantLock; public class DBImportWorker extends Worker<CityGML> implements EventHandler { private final ReentrantLock runLock = new ReentrantLock(); private volatile boolean shouldRun = true; private volatile boolean shouldWork = true; private final Connection connection; private final boolean isManagedTransaction; private final CityGMLFilter filter; private final ImportLogger importLogger; private final EventDispatcher eventDispatcher; private final BoundingBoxOptions bboxOptions; private final CityGMLImportManager importer; private final List<FeatureImportExtension> plugins; private int globalAppearanceCounter = 0; private int topLevelFeatureCounter = 0; private int commitAfter; public DBImportWorker(Connection connection, boolean isManagedTransaction, AbstractDatabaseAdapter databaseAdapter, SchemaMapping schemaMapping, CityGMLBuilder cityGMLBuilder, WorkerPool<DBXlink> xlinkPool, IdCacheManager idCacheManager, CityGMLFilter filter, AffineTransformer affineTransformer, ImportLogger importLogger, InternalConfig internalConfig, Config config, EventDispatcher eventDispatcher) throws SQLException { this.connection = connection; this.isManagedTransaction = isManagedTransaction; this.filter = filter; this.importLogger = importLogger; this.eventDispatcher = eventDispatcher; importer = new CityGMLImportManager(connection, databaseAdapter, schemaMapping, cityGMLBuilder, xlinkPool, idCacheManager, affineTransformer, internalConfig, config); commitAfter = config.getDatabaseConfig().getImportBatching().getFeatureBatchSize(); if (commitAfter > databaseAdapter.getMaxBatchSize()) { commitAfter = databaseAdapter.getMaxBatchSize(); } bboxOptions = BoundingBoxOptions.defaults() .useExistingEnvelopes(true) .assignResultToFeatures(true) .useReferencePointAsFallbackForImplicitGeometries(true); plugins = PluginManager.getInstance().getEnabledExternalPlugins(FeatureImportExtension.class); eventDispatcher.addEventHandler(EventType.INTERRUPT, this); } @Override public void interrupt() { shouldRun = false; } @Override public void run() { try { if (firstWork != null) { doWork(firstWork); firstWork = null; } while (shouldRun) { try { CityGML work = workQueue.take(); doWork(work); } catch (InterruptedException ie) { // re-check state } } try { if (shouldWork) { importer.executeBatch(); if (!isManagedTransaction) { connection.commit(); } updateImportContext(); } } catch (IOException e) { eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred while updating the import log.", LogLevel.ERROR, e, eventChannel, this)); } catch (Throwable e) { if (!isManagedTransaction) { try { connection.rollback(); } catch (SQLException sql) { // } } eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during import.", LogLevel.ERROR, e, eventChannel, this)); } } finally { try { importer.close(); } catch (CityGMLImportException | SQLException e) { // } if (!isManagedTransaction) { try { connection.close(); } catch (SQLException e) { // } } eventDispatcher.removeEventHandler(this); } } private void doWork(CityGML work) { final ReentrantLock runLock = this.runLock; runLock.lock(); try { if (!shouldWork) { return; } if (work instanceof AbstractFeature) { AbstractFeature feature = (AbstractFeature) work; // invoke import plugins if (!plugins.isEmpty()) { for (FeatureImportExtension plugin : plugins) { try { feature = plugin.process(feature); if (feature == null) { return; } } catch (PluginException e) { throw new CityGMLImportException("Import plugin " + plugin.getClass().getName() + " threw an exception.", e); } } } long id; if (work instanceof Appearance) { // global appearance id = importer.importGlobalAppearance((Appearance) feature); if (id != 0) { globalAppearanceCounter++; } } else { // compute bounding box feature.calcBoundedBy(bboxOptions); // check import filter if (!filter.getSelectionFilter().isSatisfiedBy(feature)) { return; } id = importer.importObject(feature); if (id != 0) { topLevelFeatureCounter++; } } if (id == 0) { importer.logOrThrowErrorMessage("Failed to import object " + importer.getObjectSignature(feature) + "."); } else if (globalAppearanceCounter + topLevelFeatureCounter == commitAfter) { importer.executeBatch(); if (!isManagedTransaction) { connection.commit(); } updateImportContext(); } } else { String msg = (work instanceof AbstractGML ? importer.getObjectSignature((AbstractGML) work) : work.getCityGMLClass()) + ": Unsupported top-level object type. Skipping import."; if (!importer.isFailOnError()) { Logger.getInstance().error(msg); } else { throw new CityGMLImportException(msg); } } } catch (IOException e) { eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during update of import log.", LogLevel.ERROR, e, eventChannel, this)); } catch (Throwable e) { try { connection.rollback(); } catch (SQLException sql) { // } eventDispatcher.triggerSyncEvent(new InterruptEvent("A fatal error occurred during import.", LogLevel.ERROR, e, eventChannel, this)); } finally { runLock.unlock(); } } private void updateImportContext() throws IOException { eventDispatcher.triggerEvent(new ObjectCounterEvent(importer.getAndResetObjectCounter(), this)); eventDispatcher.triggerEvent(new GeometryCounterEvent(importer.getAndResetGeometryCounter(), this)); eventDispatcher.triggerEvent(new CounterEvent(CounterType.GLOBAL_APPEARANCE, globalAppearanceCounter, this)); eventDispatcher.triggerEvent(new CounterEvent(CounterType.TOPLEVEL_FEATURE, topLevelFeatureCounter, this)); globalAppearanceCounter = 0; topLevelFeatureCounter = 0; // log imported top-level features if (importLogger != null) { for (ImportLogEntry entry : importer.getAndResetImportLogEntries()) { importLogger.write(entry); } } } @Override public void handleEvent(Event event) throws Exception { if (event.getChannel() == eventChannel) { shouldWork = false; } } }
changed work to feature
impexp-core/src/main/java/org/citydb/core/operation/importer/concurrent/DBImportWorker.java
changed work to feature
<ide><path>mpexp-core/src/main/java/org/citydb/core/operation/importer/concurrent/DBImportWorker.java <ide> } <ide> <ide> long id; <del> if (work instanceof Appearance) { <add> if (feature instanceof Appearance) { <ide> // global appearance <ide> id = importer.importGlobalAppearance((Appearance) feature); <ide> if (id != 0) {
Java
apache-2.0
65b94113f49ca185432376396570e0dcb9122193
0
UweTrottmann/trakt-java
package com.jakewharton.trakt.services; import com.jakewharton.trakt.BaseTestCase; import com.jakewharton.trakt.entities.Comment; import com.jakewharton.trakt.entities.TvEntity; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.TvShowEpisode; import com.jakewharton.trakt.entities.TvShowSeason; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.DayOfTheWeek; import org.apache.commons.lang.time.DateUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; public class ShowServiceTest extends BaseTestCase { public void test_episodeComments() { List<Comment> comments = getManager().showService().episodeComments("the-walking-dead", 1, 1).fire(); assertNotNull("Result was null.", comments); assertFalse("Comment list was empty.", comments.isEmpty()); assertNotNull("Comment item was null.", comments.get(0)); } public void test_episodeSummary() { TvEntity entity = getManager().showService().episodeSummary("the-league", 1, 1).fire(); assertNotNull("Result was null.", entity); TvShow show = entity.show; assertNotNull("Show was null.", show); assertEquals("Show title does not match.", "The League", show.title); assertNotNull("Show year was null.", show.year); assertEquals("Show year does not match.", 2009, show.year.intValue()); assertNotNull("Show URL was null.", show.url); //TODO first aired assertEquals("Show country does not match.", "United States", show.country); assertNotNull("Show overview was null.", show.overview); assertNotNull("Show runtime was null.", show.runtime); assertEquals("Show runtime does not match.", 30, show.runtime.intValue()); assertEquals("Show network does not mtach.", "FX", show.network); assertEquals("Show air day does not match.", DayOfTheWeek.Thursday, show.airDay); assertEquals("Show air time does not mtach.", "10:30pm", show.airTime); assertEquals("Show certification does not match.", "TV-MA", show.certification); assertEquals("Show IMDB ID does not match.", "tt1480684", show.imdbId); assertEquals("Show TVDB ID does not match.", "114701", show.tvdbId); assertEquals("Show TV Rage ID does not match.", "24173", show.tvrageId); assertNotNull("Show images was null.", show.images); //TODO own test cases assertNotNull("Show ratings was null.", show.ratings); //TODO own test cases //TODO rating assertNotNull("Show in watchlist boolean was null.", show.inWatchlist); assertEquals("Show in watchlist boolean does not match.", false, show.inWatchlist.booleanValue()); TvShowEpisode episode = entity.episode; assertNotNull("Episode was null."); assertNotNull("Episode season was null.", episode.season); assertEquals("Episode season does not match.", 1, episode.season.intValue()); assertNotNull("Episode number was null.", episode.number); assertEquals("Episode number does not match.", 1, episode.number.intValue()); assertEquals("Episode title does not match.", "The Draft", episode.title); assertNotNull("Episode overview was null.", episode.overview); assertNotNull("Episode URL was null.", episode.url); //TODO first aired assertNotNull("Episode images was null.", episode.images); //TODO own test cases assertNotNull("Episode ratings was null.", episode.ratings); //TODO own test cases assertNotNull("Episode watched boolean was null.", episode.watched); assertEquals("Episode watched boolean does not match.", false, episode.watched.booleanValue()); assertNotNull("Episode plays was null.", episode.plays); assertEquals("Episode plays does not match.", 0, episode.plays.intValue()); //TODO rating assertNotNull("Episode in watchlist boolean was null.", episode.inWatchlist); assertEquals("Episode in watchlist boolean does not match.", false, episode.inWatchlist.booleanValue()); } public void test_episodeWatchingNow() { List<UserProfile> users = getManager().showService().episodeWatchingNow("the-walking-dead", 1, 1).fire(); assertNotNull("Result was null.", users); if (!users.isEmpty()) { assertNotNull("User was null.", users.get(0)); } } public void test_season() { List<TvShowEpisode> episodes = getManager().showService().season("the-walking-dead", 1).fire(); assertNotNull("Result was null.", episodes); assertFalse("Episode list was empty.", episodes.isEmpty()); } public void test_seasons() { List<TvShowSeason> seasons = getManager().showService().seasons("the-walking-dead").fire(); assertNotNull("Result was null.", seasons); assertFalse("Season list was empty.", seasons.isEmpty()); TvShowSeason season = seasons.get(0); assertNotNull("Season was null.", season); assertNotNull("Season number was null.", season.season); assertNotNull("Season episodes was null.", season.episodes); assertNotNull("Season episodes count was null.", season.episodes.count); assertNotNull("Season URL was null.", season.url); assertNotNull("Season images was null.", season.images); //TODO own test cases } public void test_comments() { List<Comment> shouts = getManager().showService().comments("the-walking-dead").fire(); assertNotNull("Result was null.", shouts); assertFalse("Comment list was empty.", shouts.isEmpty()); assertNotNull("Comment was null.", shouts.get(0)); } public void test_watchingNow() { List<UserProfile> users = getManager().showService().watchingNow("the-walking-dead").fire(); assertNotNull("Result was null.", users); if (!users.isEmpty()) { assertNotNull("User was null.", users.get(0)); } } public void test_trending() { List<TvShow> trending = getManager().showService().trending().fire(); assertNotNull("Result was null.", trending); assertFalse("Trending list was empty.", trending.isEmpty()); assertNotNull("Trending item was null.", trending.get(0)); } public void test_summary() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); cal.set(2010, 9, 31, 21, 0); Date firstAired = cal.getTime(); TvShow show = getManager().showService().summary("the-walking-dead").extended().fire(); assertNotNull("Result was null.", show); assertEquals("Show title does not match.", "The Walking Dead", show.title); assertNotNull("Show year was null.", show.year); assertEquals("Show year does not match.", 2010, show.year.intValue()); assertNotNull("Show URL was null.", show.url); assertNotNull("Show first aired was null.", show.firstAired); assertTrue("Show first aired does not match.", DateUtils.isSameDay(firstAired, show.firstAired)); assertEquals("Show country does not match.", "United States", show.country); assertNotNull("Show overview was null.", show.overview); assertNotNull("Show runtime was null.", show.runtime); assertEquals("Show runtime does not match.", 60, show.runtime.intValue()); assertEquals("Show network does not match.", "AMC", show.network); assertEquals("Show air day does not match.", DayOfTheWeek.Sunday, show.airDay); assertEquals("Show air time does not match.", "9:00pm", show.airTime); assertEquals("Show certification does not match.", "TV-MA", show.certification); assertEquals("Show IMDB ID does not match.", "tt1520211", show.imdbId); assertEquals("Show TVDB ID does not match.", "153021", show.tvdbId); assertEquals("Show TV Rage ID does not match.", "25056", show.tvrageId); } public void test_related() { List<TvShow> related = getManager().showService().related("the-walking-dead").extended().fire(); assertNotNull("Result was null.", related); assertFalse("Trending list was empty.", related.isEmpty()); assertNotNull("Trending item was null.", related.get(0)); } }
src/test/java/com/jakewharton/trakt/services/ShowServiceTest.java
package com.jakewharton.trakt.services; import com.jakewharton.trakt.BaseTestCase; import com.jakewharton.trakt.entities.Comment; import com.jakewharton.trakt.entities.TvEntity; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.TvShowEpisode; import com.jakewharton.trakt.entities.TvShowSeason; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.DayOfTheWeek; import org.apache.commons.lang.time.DateUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; public class ShowServiceTest extends BaseTestCase { public void test_episodeComments() { List<Comment> comments = getManager().showService().episodeComments("the-walking-dead", 1, 1).fire(); assertNotNull("Result was null.", comments); assertFalse("Comment list was empty.", comments.isEmpty()); assertNotNull("Comment item was null.", comments.get(0)); } public void test_episodeSummary() { TvEntity entity = getManager().showService().episodeSummary("the-league", 1, 1).fire(); assertNotNull("Result was null.", entity); TvShow show = entity.show; assertNotNull("Show was null.", show); assertEquals("Show title does not match.", "The League", show.title); assertNotNull("Show year was null.", show.year); assertEquals("Show year does not match.", 2009, show.year.intValue()); assertNotNull("Show URL was null.", show.url); //TODO first aired assertEquals("Show country does not match.", "United States", show.country); assertNotNull("Show overview was null.", show.overview); assertNotNull("Show runtime was null.", show.runtime); assertEquals("Show runtime does not match.", 30, show.runtime.intValue()); assertEquals("Show network does not mtach.", "FX", show.network); assertEquals("Show air day does not match.", DayOfTheWeek.Thursday, show.airDay); assertEquals("Show air time does not mtach.", "10:30pm", show.airTime); assertEquals("Show certification does not match.", "TV-MA", show.certification); assertEquals("Show IMDB ID does not match.", "tt1480684", show.imdbId); assertEquals("Show TVDB ID does not match.", "114701", show.tvdbId); assertEquals("Show TV Rage ID does not match.", "24173", show.tvrageId); assertNotNull("Show images was null.", show.images); //TODO own test cases assertNotNull("Show ratings was null.", show.ratings); //TODO own test cases //TODO rating assertNotNull("Show in watchlist boolean was null.", show.inWatchlist); assertEquals("Show in watchlist boolean does not match.", false, show.inWatchlist.booleanValue()); TvShowEpisode episode = entity.episode; assertNotNull("Episode was null."); assertNotNull("Episode season was null.", episode.season); assertEquals("Episode season does not match.", 1, episode.season.intValue()); assertNotNull("Episode number was null.", episode.number); assertEquals("Episode number does not match.", 1, episode.number.intValue()); assertEquals("Episode title does not match.", "The Draft", episode.title); assertNotNull("Episode overview was null.", episode.overview); assertNotNull("Episode URL was null.", episode.url); //TODO first aired assertNotNull("Episode images was null.", episode.images); //TODO own test cases assertNotNull("Episode ratings was null.", episode.ratings); //TODO own test cases assertNotNull("Episode watched boolean was null.", episode.watched); assertEquals("Episode watched boolean does not match.", false, episode.watched.booleanValue()); assertNotNull("Episode plays was null.", episode.plays); assertEquals("Episode plays does not match.", 0, episode.plays.intValue()); //TODO rating assertNotNull("Episode in watchlist boolean was null.", episode.inWatchlist); assertEquals("Episode in watchlist boolean does not match.", false, episode.inWatchlist.booleanValue()); } public void test_episodeWatchingNow() { List<UserProfile> users = getManager().showService().episodeWatchingNow("the-walking-dead", 1, 1).fire(); assertNotNull("Result was null.", users); if (!users.isEmpty()) { assertNotNull("User was null.", users.get(0)); } } public void test_season() { List<TvShowEpisode> episodes = getManager().showService().season("the-walking-dead", 1).fire(); assertNotNull("Result was null.", episodes); assertFalse("Episode list was empty.", episodes.isEmpty()); } public void test_seasons() { List<TvShowSeason> seasons = getManager().showService().seasons("the-walking-dead").fire(); assertNotNull("Result was null.", seasons); assertFalse("Season list was empty.", seasons.isEmpty()); TvShowSeason season = seasons.get(0); assertNotNull("Season was null.", season); assertNotNull("Season number was null.", season.season); assertNotNull("Season episodes was null.", season.episodes); assertNotNull("Season episodes count was null.", season.episodes.count); assertNotNull("Season URL was null.", season.url); assertNotNull("Season images was null.", season.images); //TODO own test cases } public void test_comments() { List<Comment> shouts = getManager().showService().comments("the-walking-dead").fire(); assertNotNull("Result was null.", shouts); assertFalse("Comment list was empty.", shouts.isEmpty()); assertNotNull("Comment was null.", shouts.get(0)); } public void test_watchingNow() { List<UserProfile> users = getManager().showService().watchingNow("the-walking-dead").fire(); assertNotNull("Result was null.", users); if (!users.isEmpty()) { assertNotNull("User was null.", users.get(0)); } } public void test_trending() { List<TvShow> trending = getManager().showService().trending().fire(); assertNotNull("Result was null.", trending); assertFalse("Trending list was empty.", trending.isEmpty()); assertNotNull("Trending item was null.", trending.get(0)); } public void test_summary() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); cal.set(2010, 9, 31, 21, 0); Date firstAired = cal.getTime(); TvShow show = getManager().showService().summary("the-walking-dead").extended().fire(); assertNotNull("Result was null.", show); assertEquals("Show title does not match.", "The Walking Dead", show.title); assertNotNull("Show year was null.", show.year); assertEquals("Show year does not match.", 2010, show.year.intValue()); assertNotNull("Show URL was null.", show.url); assertNotNull("Show first aired was null.", show.firstAired); assertTrue("Show first aired does not match.", DateUtils.isSameDay(firstAired, show.firstAired)); assertEquals("Show country does not match.", "United States", show.country); assertNotNull("Show overview was null.", show.overview); assertNotNull("Show runtime was null.", show.runtime); assertEquals("Show runtime does not match.", 60, show.runtime.intValue()); assertEquals("Show network does not match.", "AMC", show.network); assertEquals("Show air day does not match.", DayOfTheWeek.Sunday, show.airDay); assertEquals("Show air time does not match.", "9:00pm", show.airTime); assertEquals("Show certification does not match.", "TV-14", show.certification); assertEquals("Show IMDB ID does not match.", "tt1520211", show.imdbId); assertEquals("Show TVDB ID does not match.", "153021", show.tvdbId); assertEquals("Show TV Rage ID does not match.", "25056", show.tvrageId); } public void test_related() { List<TvShow> related = getManager().showService().related("the-walking-dead").extended().fire(); assertNotNull("Result was null.", related); assertFalse("Trending list was empty.", related.isEmpty()); assertNotNull("Trending item was null.", related.get(0)); } }
Fix show summary test.
src/test/java/com/jakewharton/trakt/services/ShowServiceTest.java
Fix show summary test.
<ide><path>rc/test/java/com/jakewharton/trakt/services/ShowServiceTest.java <ide> assertEquals("Show network does not match.", "AMC", show.network); <ide> assertEquals("Show air day does not match.", DayOfTheWeek.Sunday, show.airDay); <ide> assertEquals("Show air time does not match.", "9:00pm", show.airTime); <del> assertEquals("Show certification does not match.", "TV-14", show.certification); <add> assertEquals("Show certification does not match.", "TV-MA", show.certification); <ide> assertEquals("Show IMDB ID does not match.", "tt1520211", show.imdbId); <ide> assertEquals("Show TVDB ID does not match.", "153021", show.tvdbId); <ide> assertEquals("Show TV Rage ID does not match.", "25056", show.tvrageId);
Java
bsd-3-clause
a67a2022d3d7f7df93d2e82a9598657642340fa1
0
gaionim/k-9,msdgwzhy6/k-9,leixinstar/k-9,gilbertw1/k-9,dpereira411/k-9,msdgwzhy6/k-9,leixinstar/k-9,tonytamsf/k-9,mawiegand/k-9,ndew623/k-9,vatsalsura/k-9,CodingRmy/k-9,jberkel/k-9,sanderbaas/k-9,philipwhiuk/q-mail,jca02266/k-9,KitAway/k-9,nilsbraden/k-9,indus1/k-9,KitAway/k-9,crr0004/k-9,imaeses/k-9,leixinstar/k-9,icedman21/k-9,nilsbraden/k-9,Eagles2F/k-9,jca02266/k-9,philipwhiuk/q-mail,Eagles2F/k-9,cketti/k-9,huhu/k-9,dpereira411/k-9,dhootha/k-9,msdgwzhy6/k-9,bashrc/k-9,k9mail/k-9,suzp1984/k-9,sedrubal/k-9,dhootha/k-9,sebkur/k-9,gnebsy/k-9,gaionim/k-9,moparisthebest/k-9,philipwhiuk/q-mail,nilsbraden/k-9,bashrc/k-9,GuillaumeSmaha/k-9,huhu/k-9,philipwhiuk/k-9,vasyl-khomko/k-9,konfer/k-9,github201407/k-9,ndew623/k-9,konfer/k-9,denim2x/k-9,sebkur/k-9,farmboy0/k-9,tsunli/k-9,cliniome/pki,mawiegand/k-9,cketti/k-9,cooperpellaton/k-9,WenduanMou1/k-9,rollbrettler/k-9,gilbertw1/k-9,roscrazy/k-9,thuanpq/k-9,dgger/k-9,439teamwork/k-9,dgger/k-9,github201407/k-9,XiveZ/k-9,439teamwork/k-9,G00fY2/k-9_material_design,thuanpq/k-9,cooperpellaton/k-9,deepworks/k-9,rtreffer/openpgp-k-9,herpiko/k-9,gilbertw1/k-9,vasyl-khomko/k-9,mawiegand/k-9,farmboy0/k-9,WenduanMou1/k-9,sanderbaas/k-9,imaeses/k-9,tsunli/k-9,thuanpq/k-9,herpiko/k-9,sebkur/k-9,rollbrettler/k-9,dhootha/k-9,rishabhbitsg/k-9,imaeses/k-9,CodingRmy/k-9,sonork/k-9,indus1/k-9,WenduanMou1/k-9,tonytamsf/k-9,rtreffer/openpgp-k-9,gaionim/k-9,sedrubal/k-9,Eagles2F/k-9,bashrc/k-9,dgger/k-9,cketti/k-9,torte71/k-9,439teamwork/k-9,k9mail/k-9,sonork/k-9,huhu/k-9,jberkel/k-9,icedman21/k-9,moparisthebest/k-9,cketti/k-9,deepworks/k-9,vatsalsura/k-9,crr0004/k-9,tonytamsf/k-9,crr0004/k-9,torte71/k-9,herpiko/k-9,vt0r/k-9,dpereira411/k-9,GuillaumeSmaha/k-9,XiveZ/k-9,moparisthebest/k-9,konfer/k-9,jca02266/k-9,GuillaumeSmaha/k-9,tsunli/k-9,gnebsy/k-9,sanderbaas/k-9,roscrazy/k-9,suzp1984/k-9,rishabhbitsg/k-9,farmboy0/k-9,sonork/k-9,gnebsy/k-9,KitAway/k-9,vt0r/k-9,denim2x/k-9,cliniome/pki,rollbrettler/k-9,denim2x/k-9,cooperpellaton/k-9,deepworks/k-9,cliniome/pki,vasyl-khomko/k-9,Valodim/k-9,G00fY2/k-9_material_design,github201407/k-9,k9mail/k-9,torte71/k-9,philipwhiuk/k-9,suzp1984/k-9,icedman21/k-9,XiveZ/k-9,ndew623/k-9
package com.fsck.k9.mail.store; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import org.apache.commons.io.IOUtils; import android.app.Application; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.text.Html; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.Account.LocalStoreMigrationListener; import com.fsck.k9.controller.MessageRemovalListener; import com.fsck.k9.controller.MessageRetrievalListener; import com.fsck.k9.helper.Regex; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.BodyPart; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.filter.Base64OutputStream; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.StorageManager.StorageProvider; import com.fsck.k9.provider.AttachmentProvider; /** * <pre> * Implements a SQLite database backed local store for Messages. * </pre> */ public class LocalStore extends Store implements Serializable, LocalStoreMigrationListener { /** * Callback interface for DB operations. Concept is similar to Spring * HibernateCallback. * * @param <T> * Return value type for {@link #doDbWork(SQLiteDatabase)} */ public static interface DbCallback<T> { /** * @param db * The locked database on which the work should occur. Never * <code>null</code>. * @return Any relevant data. Can be <code>null</code>. * @throws WrappedException * @throws UnavailableStorageException */ T doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException; } /** * Workaround exception wrapper used to keep the inner exception generated * in a {@link DbCallback}. */ protected static class WrappedException extends RuntimeException { /** * */ private static final long serialVersionUID = 8184421232587399369L; public WrappedException(final Exception cause) { super(cause); } } private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; /** * Immutable empty {@link String} array */ private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final int DB_VERSION = 39; private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN, Flag.FLAGGED }; private static final int MAX_SMART_HTMLIFY_MESSAGE_LENGTH = 1024 * 256 ; private String mStorageProviderId; private SQLiteDatabase mDb; { final ReadWriteLock lock = new ReentrantReadWriteLock(true); mReadLock = lock.readLock(); mWriteLock = lock.writeLock(); } /** * Reentrant read lock */ protected final Lock mReadLock; /** * Reentrant write lock (if you lock it 2x from the same thread, you have to * unlock it 2x to release it) */ protected final Lock mWriteLock; private Application mApplication; private String uUid = null; private static Set<String> HEADERS_TO_SAVE = new HashSet<String>(); static { HEADERS_TO_SAVE.add(K9.K9MAIL_IDENTITY); HEADERS_TO_SAVE.add("To"); HEADERS_TO_SAVE.add("Cc"); HEADERS_TO_SAVE.add("From"); HEADERS_TO_SAVE.add("In-Reply-To"); HEADERS_TO_SAVE.add("References"); HEADERS_TO_SAVE.add("Content-ID"); HEADERS_TO_SAVE.add("Content-Disposition"); HEADERS_TO_SAVE.add("X-User-Agent"); } /* * a String containing the columns getMessages expects to work with * in the correct order. */ static private String GET_MESSAGES_COLS = "subject, sender_list, date, uid, flags, id, to_list, cc_list, " + "bcc_list, reply_to_list, attachment_count, internal_date, message_id, folder_id, preview "; private final StorageListener mStorageListener = new StorageListener(); /** * {@link ThreadLocal} to check whether a DB transaction is occuring in the * current {@link Thread}. * * @see #execute(boolean, DbCallback) */ private ThreadLocal<Boolean> inTransaction = new ThreadLocal<Boolean>(); /** * local://localhost/path/to/database/uuid.db * This constructor is only used by {@link Store#getLocalInstance(Account, Application)} * @throws UnavailableStorageException if not {@link StorageProvider#isReady(Context)} */ public LocalStore(Account account, Application application) throws MessagingException { super(account); mApplication = application; mStorageProviderId = account.getLocalStorageProviderId(); account.setLocalStoreMigrationListener(this); uUid = account.getUuid(); lockWrite(); try { openOrCreateDataspace(application); } finally { unlockWrite(); } StorageManager.getInstance(application).addListener(mStorageListener); } /** * Lock the storage for shared operations (concurrent threads are allowed to * run simultaneously). * * <p> * You <strong>have to</strong> invoke {@link #unlockRead()} when you're * done with the storage. * </p> * * @throws UnavailableStorageException * If storage can't be locked because it is not available */ protected void lockRead() throws UnavailableStorageException { mReadLock.lock(); try { StorageManager.getInstance(mApplication).lockProvider(mStorageProviderId); } catch (UnavailableStorageException e) { mReadLock.unlock(); throw e; } catch (RuntimeException e) { mReadLock.unlock(); throw e; } } protected void unlockRead() { StorageManager.getInstance(mApplication).unlockProvider(mStorageProviderId); mReadLock.unlock(); } /** * Lock the storage for exclusive access (other threads aren't allowed to * run simultaneously) * * <p> * You <strong>have to</strong> invoke {@link #unlockWrite()} when you're * done with the storage. * </p> * * @throws UnavailableStorageException * If storage can't be locked because it is not available. */ protected void lockWrite() throws UnavailableStorageException { lockWrite(mStorageProviderId); } /** * Lock the storage for exclusive access (other threads aren't allowed to * run simultaneously) * * <p> * You <strong>have to</strong> invoke {@link #unlockWrite()} when you're * done with the storage. * </p> * * @param providerId * Never <code>null</code>. * * @throws UnavailableStorageException * If storage can't be locked because it is not available. */ protected void lockWrite(final String providerId) throws UnavailableStorageException { mWriteLock.lock(); try { StorageManager.getInstance(mApplication).lockProvider(providerId); } catch (UnavailableStorageException e) { mWriteLock.unlock(); throw e; } catch (RuntimeException e) { mWriteLock.unlock(); throw e; } } protected void unlockWrite() { unlockWrite(mStorageProviderId); } protected void unlockWrite(final String providerId) { StorageManager.getInstance(mApplication).unlockProvider(providerId); mWriteLock.unlock(); } /** * Execute a DB callback in a shared context (doesn't prevent concurrent * shared executions), taking care of locking the DB storage. * * <p> * Can be instructed to start a transaction if none is currently active in * the current thread. Callback will participe in any active transaction (no * inner transaction created). * </p> * * @param transactional * <code>true</code> the callback must be executed in a * transactional context. * @param callback * Never <code>null</code>. * * @param <T> * @return Whatever {@link DbCallback#doDbWork(SQLiteDatabase)} returns. * @throws UnavailableStorageException */ protected <T> T execute(final boolean transactional, final DbCallback<T> callback) throws UnavailableStorageException { lockRead(); final boolean doTransaction = transactional && inTransaction.get() == null; try { final boolean debug = K9.DEBUG; if (doTransaction) { inTransaction.set(Boolean.TRUE); mDb.beginTransaction(); } try { final T result = callback.doDbWork(mDb); if (doTransaction) { mDb.setTransactionSuccessful(); } return result; } finally { if (doTransaction) { final long begin; if (debug) { begin = System.currentTimeMillis(); } else { begin = 0l; } // not doing endTransaction in the same 'finally' block of unlockRead() because endTransaction() may throw an exception mDb.endTransaction(); if (debug) { Log.v(K9.LOG_TAG, "LocalStore: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms / " + new Exception().getStackTrace()[1].toString()); } } } } finally { if (doTransaction) { inTransaction.set(null); } unlockRead(); } } public void onLocalStoreMigration(final String oldProviderId, final String newProviderId) throws MessagingException { lockWrite(oldProviderId); try { lockWrite(newProviderId); try { try { mDb.close(); } catch (Exception e) { Log.i(K9.LOG_TAG, "Unable to close DB on local store migration", e); } final StorageManager storageManager = StorageManager.getInstance(mApplication); // create new path prepareStorage(newProviderId); // move all database files moveRecursive(storageManager.getDatabase(uUid, oldProviderId), storageManager.getDatabase(uUid, newProviderId)); // move all attachment files moveRecursive(storageManager.getAttachmentDirectory(uUid, oldProviderId), storageManager.getAttachmentDirectory(uUid, newProviderId)); mStorageProviderId = newProviderId; // re-initialize this class with the new Uri openOrCreateDataspace(mApplication); } finally { unlockWrite(newProviderId); } } finally { unlockWrite(oldProviderId); } } private void moveRecursive(File fromDir, File toDir) { if (!fromDir.exists()) { return; } if (!fromDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete already existing file/directory " + toDir.getAbsolutePath() + " during migration to/from SD-card"); } } if (!fromDir.renameTo(toDir)) { Log.w(K9.LOG_TAG, "cannot rename " + fromDir.getAbsolutePath() + " to " + toDir.getAbsolutePath() + " - moving instead"); move(fromDir, toDir); } return; } if (!toDir.exists() || !toDir.isDirectory()) { if (toDir.exists() ) { toDir.delete(); } if (!toDir.mkdirs()) { Log.w(K9.LOG_TAG, "cannot create directory " + toDir.getAbsolutePath() + " during migration to/from SD-card"); } } File[] files = fromDir.listFiles(); for (File file : files) { if (file.isDirectory()) { moveRecursive(file, new File(toDir, file.getName())); file.delete(); } else { File target = new File(toDir, file.getName()); if (!file.renameTo(target)) { Log.w(K9.LOG_TAG, "cannot rename " + file.getAbsolutePath() + " to " + target.getAbsolutePath() + " - moving instead"); move(file, target); } } } if (!fromDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete " + fromDir.getAbsolutePath() + " after migration to/from SD-card"); } } private boolean move(File from, File to) { if (to.exists()) { to.delete(); } to.getParentFile().mkdirs(); try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024]; int count = -1; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); in.close(); from.delete(); return true; } catch (Exception e) { Log.w(K9.LOG_TAG, "cannot move " + from.getAbsolutePath() + " to " + to.getAbsolutePath(), e); return false; } } /** * * @param application * @throws UnavailableStorageException */ void openOrCreateDataspace(final Application application) throws UnavailableStorageException { lockWrite(); try { final File databaseFile = prepareStorage(mStorageProviderId); try { mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); } catch (SQLiteException e) { // try to gracefully handle DB corruption - see issue 2537 Log.w(K9.LOG_TAG, "Unable to open DB " + databaseFile + " - removing file and retrying", e); databaseFile.delete(); mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); } if (mDb.getVersion() != DB_VERSION) { doDbUpgrade(mDb, application); } } finally { unlockWrite(); } } /** * @param providerId * Never <code>null</code>. * @return DB file. * @throws UnavailableStorageException */ protected File prepareStorage(final String providerId) throws UnavailableStorageException { final StorageManager storageManager = StorageManager.getInstance(mApplication); final File databaseFile; final File databaseParentDir; databaseFile = storageManager.getDatabase(uUid, providerId); databaseParentDir = databaseFile.getParentFile(); if (databaseParentDir.isFile()) { // should be safe to inconditionally delete clashing file: user is not supposed to mess with our directory databaseParentDir.delete(); } if (!databaseParentDir.exists()) { if (!databaseParentDir.mkdirs()) { // Android seems to be unmounting the storage... throw new UnavailableStorageException("Unable to access: " + databaseParentDir); } touchFile(databaseParentDir, ".nomedia"); } final File attachmentDir; final File attachmentParentDir; attachmentDir = storageManager .getAttachmentDirectory(uUid, providerId); attachmentParentDir = attachmentDir.getParentFile(); if (!attachmentParentDir.exists()) { attachmentParentDir.mkdirs(); touchFile(attachmentParentDir, ".nomedia"); } if (!attachmentDir.exists()) { attachmentDir.mkdirs(); } return databaseFile; } /** * @param parentDir * @param name * Never <code>null</code>. */ protected void touchFile(final File parentDir, String name) { final File file = new File(parentDir, name); try { if (!file.exists()) { file.createNewFile(); } else { file.setLastModified(System.currentTimeMillis()); } } catch (Exception e) { Log.d(K9.LOG_TAG, "Unable to touch file: " + file.getAbsolutePath(), e); } } private void doDbUpgrade(final SQLiteDatabase db, final Application application) { Log.i(K9.LOG_TAG, String.format("Upgrading database from version %d to version %d", db.getVersion(), DB_VERSION)); AttachmentProvider.clear(application); try { // schema version 29 was when we moved to incremental updates // in the case of a new db or a < v29 db, we blow away and start from scratch if (db.getVersion() < 29) { db.execSQL("DROP TABLE IF EXISTS folders"); db.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, " + "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT, push_state TEXT, last_pushed INTEGER, flagged_count INTEGER default 0)"); db.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)"); db.execSQL("DROP TABLE IF EXISTS messages"); db.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted INTEGER default 0, folder_id INTEGER, uid TEXT, subject TEXT, " + "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, " + "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT, preview TEXT)"); db.execSQL("DROP TABLE IF EXISTS headers"); db.execSQL("CREATE TABLE headers (id INTEGER PRIMARY KEY, message_id INTEGER, name TEXT, value TEXT)"); db.execSQL("CREATE INDEX IF NOT EXISTS header_folder ON headers (message_id)"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)"); db.execSQL("DROP INDEX IF EXISTS msg_folder_id"); db.execSQL("DROP INDEX IF EXISTS msg_folder_id_date"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)"); db.execSQL("DROP TABLE IF EXISTS attachments"); db.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER," + "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT," + "mime_type TEXT, content_id TEXT, content_disposition TEXT)"); db.execSQL("DROP TABLE IF EXISTS pending_commands"); db.execSQL("CREATE TABLE pending_commands " + "(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)"); db.execSQL("DROP TRIGGER IF EXISTS delete_folder"); db.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;"); db.execSQL("DROP TRIGGER IF EXISTS delete_message"); db.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; " + "DELETE FROM headers where old.id = message_id; END;"); } else { // in the case that we're starting out at 29 or newer, run all the needed updates if (db.getVersion() < 30) { try { db.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0"); } catch (SQLiteException e) { if (! e.toString().startsWith("duplicate column name: deleted")) { throw e; } } } if (db.getVersion() < 31) { db.execSQL("DROP INDEX IF EXISTS msg_folder_id_date"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)"); } if (db.getVersion() < 32) { db.execSQL("UPDATE messages SET deleted = 1 WHERE flags LIKE '%DELETED%'"); } if (db.getVersion() < 33) { try { db.execSQL("ALTER TABLE messages ADD preview TEXT"); } catch (SQLiteException e) { if (! e.toString().startsWith("duplicate column name: preview")) { throw e; } } } if (db.getVersion() < 34) { try { db.execSQL("ALTER TABLE folders ADD flagged_count INTEGER default 0"); } catch (SQLiteException e) { if (! e.getMessage().startsWith("duplicate column name: flagged_count")) { throw e; } } } if (db.getVersion() < 35) { try { db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e); } } if (db.getVersion() < 36) { try { db.execSQL("ALTER TABLE attachments ADD content_id TEXT"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments"); } } if (db.getVersion() < 37) { try { db.execSQL("ALTER TABLE attachments ADD content_disposition TEXT"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments"); } } // Database version 38 is solely to prune cached attachments now that we clear them better if (db.getVersion() < 39) { try { db.execSQL("DELETE FROM headers WHERE id in (SELECT headers.id FROM headers LEFT JOIN messages ON headers.message_id = messages.id WHERE messages.id IS NULL)"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to remove extra header data from the database"); } } } } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); throw new Error("Database upgrade failed! Resetting your DB version to 0 to force a full schema recreation."); } db.setVersion(DB_VERSION); if (db.getVersion() != DB_VERSION) { throw new Error("Database upgrade failed!"); } try { pruneCachedAttachments(true); } catch (Exception me) { Log.e(K9.LOG_TAG, "Exception while force pruning attachments during DB update", me); } } public long getSize() throws UnavailableStorageException { final StorageManager storageManager = StorageManager.getInstance(mApplication); final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); return execute(false, new DbCallback<Long>() { @Override public Long doDbWork(final SQLiteDatabase db) { final File[] files = attachmentDirectory.listFiles(); long attachmentLength = 0; for (File file : files) { if (file.exists()) { attachmentLength += file.length(); } } final File dbFile = storageManager.getDatabase(uUid, mStorageProviderId); return dbFile.length() + attachmentLength; } }); } public void compact() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); pruneCachedAttachments(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("VACUUM"); return null; } }); if (K9.DEBUG) Log.i(K9.LOG_TAG, "After compaction size = " + getSize()); } public void clear() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); pruneCachedAttachments(true); if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount()); Log.i(K9.LOG_TAG, "Before clear message count = " + getMessageCount()); Log.i(K9.LOG_TAG, "After prune / before clear size = " + getSize()); } // don't delete messages that are Local, since there is no copy on the server. // Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have // been deleted locally. They take up insignificant space execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) { db.execSQL("DELETE FROM messages WHERE deleted = 0 and uid not like 'Local%'"); db.execSQL("update folders set flagged_count = 0, unread_count = 0"); return null; } }); compact(); if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount()); Log.i(K9.LOG_TAG, "After clear size = " + getSize()); } } public int getMessageCount() throws MessagingException { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages", null); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } public int getFolderCount() throws MessagingException { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM folders", null); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } @Override public LocalFolder getFolder(String name) throws MessagingException { return new LocalFolder(name); } // TODO this takes about 260-300ms, seems slow. @Override public List<? extends Folder> getPersonalNamespaces(boolean forceListAll) throws MessagingException { final List<LocalFolder> folders = new LinkedList<LocalFolder>(); try { execute(false, new DbCallback<List<? extends Folder>>() { @Override public List<? extends Folder> doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.rawQuery("SELECT id, name, unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders ORDER BY name ASC", null); while (cursor.moveToNext()) { LocalFolder folder = new LocalFolder(cursor.getString(1)); folder.open(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8)); folders.add(folder); } return folders; } catch (MessagingException e) { throw new WrappedException(e); } finally { if (cursor != null) { cursor.close(); } } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } return folders; } @Override public void checkSettings() throws MessagingException { } /** * Delete the entire Store and it's backing database. * @throws UnavailableStorageException */ public void delete() throws UnavailableStorageException { lockWrite(); try { try { mDb.close(); } catch (Exception e) { } final StorageManager storageManager = StorageManager.getInstance(mApplication); try { final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); final File[] attachments = attachmentDirectory.listFiles(); for (File attachment : attachments) { if (attachment.exists()) { attachment.delete(); } } if (attachmentDirectory.exists()) { attachmentDirectory.delete(); } } catch (Exception e) { } try { storageManager.getDatabase(uUid, mStorageProviderId).delete(); } catch (Exception e) { Log.i(K9.LOG_TAG, "LocalStore: delete(): Unable to delete backing DB file", e); } // stop waiting for mount/unmount events StorageManager.getInstance(mApplication).removeListener(mStorageListener); } finally { unlockWrite(); } } public void recreate() throws UnavailableStorageException { lockWrite(); try { try { mDb.close(); } catch (Exception e) { } final StorageManager storageManager = StorageManager.getInstance(mApplication); try { final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); final File[] attachments = attachmentDirectory.listFiles(); for (File attachment : attachments) { if (attachment.exists()) { attachment.delete(); } } if (attachmentDirectory.exists()) { attachmentDirectory.delete(); } } catch (Exception e) { } try { storageManager.getDatabase(uUid, mStorageProviderId).delete(); } catch (Exception e) { } openOrCreateDataspace(mApplication); } finally { unlockWrite(); } } public void pruneCachedAttachments() throws MessagingException { pruneCachedAttachments(false); } /** * Deletes all cached attachments for the entire store. */ public void pruneCachedAttachments(final boolean force) throws MessagingException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { if (force) { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, null, null); } final StorageManager storageManager = StorageManager.getInstance(mApplication); File[] files = storageManager.getAttachmentDirectory(uUid, mStorageProviderId).listFiles(); for (File file : files) { if (file.exists()) { if (!force) { Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "store_data" }, "id = ?", new String[] { file.getName() }, null, null, null); if (cursor.moveToNext()) { if (cursor.getString(0) == null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting"); /* * If the attachment has no store data it is not recoverable, so * we won't delete it. */ continue; } } } finally { if (cursor != null) { cursor.close(); } } } if (!force) { try { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, "id = ?", new String[] { file.getName() }); } catch (Exception e) { /* * If the row has gone away before we got to mark it not-downloaded that's * okay. */ } } if (!file.delete()) { file.deleteOnExit(); } } } return null; } }); } public void resetVisibleLimits() throws UnavailableStorageException { resetVisibleLimits(mAccount.getDisplayCount()); } public void resetVisibleLimits(int visibleLimit) throws UnavailableStorageException { final ContentValues cv = new ContentValues(); cv.put("visible_limit", Integer.toString(visibleLimit)); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.update("folders", cv, null, null); return null; } }); } public ArrayList<PendingCommand> getPendingCommands() throws UnavailableStorageException { return execute(false, new DbCallback<ArrayList<PendingCommand>>() { @Override public ArrayList<PendingCommand> doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.query("pending_commands", new String[] { "id", "command", "arguments" }, null, null, null, null, "id ASC"); ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>(); while (cursor.moveToNext()) { PendingCommand command = new PendingCommand(); command.mId = cursor.getLong(0); command.command = cursor.getString(1); String arguments = cursor.getString(2); command.arguments = arguments.split(","); for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]); } commands.add(command); } return commands; } finally { if (cursor != null) { cursor.close(); } } } }); } public void addPendingCommand(PendingCommand command) throws UnavailableStorageException { try { for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8"); } final ContentValues cv = new ContentValues(); cv.put("command", command.command); cv.put("arguments", Utility.combine(command.arguments, ',')); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.insert("pending_commands", "command", cv); return null; } }); } catch (UnsupportedEncodingException usee) { throw new Error("Aparently UTF-8 has been lost to the annals of history."); } } public void removePendingCommand(final PendingCommand command) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) }); return null; } }); } public void removePendingCommands() throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", null, null); return null; } }); } /** * Open the DB on mount and close the DB on unmount */ private class StorageListener implements StorageManager.StorageListener { @Override public void onUnmount(final String providerId) { if (!providerId.equals(mStorageProviderId)) { return; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LocalStore: Closing DB " + uUid + " due to unmount event on StorageProvider: " + providerId); } try { lockWrite(); try { mDb.close(); } finally { unlockWrite(); } } catch (UnavailableStorageException e) { Log.w(K9.LOG_TAG, "Unable to writelock on unmount", e); } } @Override public void onMount(String providerId) { if (!providerId.equals(mStorageProviderId)) { return; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LocalStore: Opening DB " + uUid + " due to mount event on StorageProvider: " + providerId); } try { openOrCreateDataspace(mApplication); } catch (UnavailableStorageException e) { Log.e(K9.LOG_TAG, "Unable to open DB on mount", e); } } } public static class PendingCommand { private long mId; public String command; public String[] arguments; @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(command); sb.append(": "); for (String argument : arguments) { sb.append(", "); sb.append(argument); //sb.append("\n"); } return sb.toString(); } } @Override public boolean isMoveCapable() { return true; } @Override public boolean isCopyCapable() { return true; } public Message[] searchForMessages(MessageRetrievalListener listener, String[] queryFields, String queryString, List<LocalFolder> folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException { List<String> args = new LinkedList<String>(); StringBuilder whereClause = new StringBuilder(); if (queryString != null && queryString.length() > 0) { boolean anyAdded = false; String likeString = "%"+queryString+"%"; whereClause.append(" AND ("); for (String queryField : queryFields) { if (anyAdded) { whereClause.append(" OR "); } whereClause.append(queryField + " LIKE ? "); args.add(likeString); anyAdded = true; } whereClause.append(" )"); } if (folders != null && folders.size() > 0) { whereClause.append(" AND folder_id in ("); boolean anyAdded = false; for (LocalFolder folder : folders) { if (anyAdded) { whereClause.append(","); } anyAdded = true; whereClause.append("?"); args.add(Long.toString(folder.getId())); } whereClause.append(" )"); } if (messages != null && messages.length > 0) { whereClause.append(" AND ( "); boolean anyAdded = false; for (Message message : messages) { if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; whereClause.append(" ( uid = ? AND folder_id = ? ) "); args.add(message.getUid()); args.add(Long.toString(((LocalFolder)message.getFolder()).getId())); } whereClause.append(" )"); } if (forbiddenFlags != null && forbiddenFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; for (Flag flag : forbiddenFlags) { if (anyAdded) { whereClause.append(" AND "); } anyAdded = true; whereClause.append(" flags NOT LIKE ?"); args.add("%" + flag.toString() + "%"); } whereClause.append(" )"); } if (requiredFlags != null && requiredFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; for (Flag flag : requiredFlags) { if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; whereClause.append(" flags LIKE ?"); args.add("%" + flag.toString() + "%"); } whereClause.append(" )"); } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "whereClause = " + whereClause.toString()); Log.v(K9.LOG_TAG, "args = " + args); } return getMessages( listener, null, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE deleted = 0 " + whereClause.toString() + " ORDER BY date DESC" , args.toArray(EMPTY_STRING_ARRAY) ); } /* * Given a query string, actually do the query for the messages and * call the MessageRetrievalListener for each one */ private Message[] getMessages( final MessageRetrievalListener listener, final LocalFolder folder, final String queryString, final String[] placeHolders ) throws MessagingException { final ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>(); final int j = execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; int i = 0; try { cursor = db.rawQuery(queryString + " LIMIT 10", placeHolders); while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); if (listener != null) { listener.messageFinished(message, i, -1); } i++; } cursor.close(); cursor = db.rawQuery(queryString + " LIMIT -1 OFFSET 10", placeHolders); while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); if (listener != null) { listener.messageFinished(message, i, -1); } i++; } } catch (Exception e) { Log.d(K9.LOG_TAG,"Got an exception "+e); } finally { if (cursor != null) { cursor.close(); } } return i; } }); if (listener != null) { listener.messagesFinished(j); } return messages.toArray(EMPTY_MESSAGE_ARRAY); } public String getAttachmentType(final String attachmentId) throws UnavailableStorageException { return execute(false, new DbCallback<String>() { @Override public String doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "mime_type", "name" }, "id = ?", new String[] { attachmentId }, null, null, null); cursor.moveToFirst(); String type = cursor.getString(0); String name = cursor.getString(1); cursor.close(); if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(type)) { type = MimeUtility.getMimeTypeByExtension(name); } return type; } finally { if (cursor != null) { cursor.close(); } } } }); } public AttachmentInfo getAttachmentInfo(final String attachmentId) throws UnavailableStorageException { return execute(false, new DbCallback<AttachmentInfo>() { @Override public AttachmentInfo doDbWork(final SQLiteDatabase db) throws WrappedException { String name = null; int size = -1; Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "name", "size" }, "id = ?", new String[] { attachmentId }, null, null, null); if (!cursor.moveToFirst()) { return null; } name = cursor.getString(0); size = cursor.getInt(1); final AttachmentInfo attachmentInfo = new AttachmentInfo(); attachmentInfo.name = name; attachmentInfo.size = size; return attachmentInfo; } finally { if (cursor != null) { cursor.close(); } } } }); } public static class AttachmentInfo { public String name; public int size; } public class LocalFolder extends Folder implements Serializable { private String mName = null; private long mFolderId = -1; private int mUnreadMessageCount = -1; private int mFlaggedMessageCount = -1; private int mVisibleLimit = -1; private FolderClass displayClass = FolderClass.NO_CLASS; private FolderClass syncClass = FolderClass.INHERITED; private FolderClass pushClass = FolderClass.SECOND_CLASS; private boolean inTopGroup = false; private String prefId = null; private String mPushState = null; private boolean mIntegrate = false; public LocalFolder(String name) { super(LocalStore.this.mAccount); this.mName = name; if (K9.INBOX.equals(getName())) { syncClass = FolderClass.FIRST_CLASS; pushClass = FolderClass.FIRST_CLASS; inTopGroup = true; } } public LocalFolder(long id) { super(LocalStore.this.mAccount); this.mFolderId = id; } public long getId() { return mFolderId; } @Override public void open(final OpenMode mode) throws MessagingException { if (isOpen()) { return; } try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { String baseQuery = "SELECT id, name,unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders "; if (mName != null) { cursor = db.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName }); } else { cursor = db.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) }); } if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); if (folderId > 0) { open(folderId, cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8)); } } else { Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId()); create(FolderType.HOLDS_MESSAGES); open(mode); } } catch (MessagingException e) { throw new WrappedException(e); } finally { if (cursor != null) { cursor.close(); } } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount) throws MessagingException { mFolderId = id; mName = name; mUnreadMessageCount = unreadCount; mVisibleLimit = visibleLimit; mPushState = pushState; mFlaggedMessageCount = flaggedCount; super.setStatus(status); // Only want to set the local variable stored in the super class. This class // does a DB update on setLastChecked super.setLastChecked(lastChecked); super.setLastPush(lastPushed); } @Override public boolean isOpen() { return (mFolderId != -1 && mName != null); } @Override public OpenMode getMode() throws MessagingException { return OpenMode.READ_WRITE; } @Override public String getName() { return mName; } @Override public boolean exists() throws MessagingException { return execute(false, new DbCallback<Boolean>() { @Override public Boolean doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.rawQuery("SELECT id FROM folders " + "where folders.name = ?", new String[] { LocalFolder.this .getName() }); if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); return (folderId > 0); } else { return false; } } finally { if (cursor != null) { cursor.close(); } } } }); } @Override public boolean create(FolderType type) throws MessagingException { if (exists()) { throw new MessagingException("Folder " + mName + " already exists."); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] { mName, mAccount.getDisplayCount() }); return null; } }); return true; } @Override public boolean create(FolderType type, final int visibleLimit) throws MessagingException { if (exists()) { throw new MessagingException("Folder " + mName + " already exists."); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] { mName, visibleLimit }); return null; } }); return true; } @Override public void close() { mFolderId = -1; } @Override public int getMessageCount() throws MessagingException { try { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?", new String[] { Long.toString(mFolderId) }); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mUnreadMessageCount; } @Override public int getFlaggedMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mFlaggedMessageCount; } public void setUnreadMessageCount(final int unreadMessageCount) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mUnreadMessageCount = Math.max(0, unreadMessageCount); db.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?", new Object[] { mUnreadMessageCount, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public void setFlaggedMessageCount(final int flaggedMessageCount) throws MessagingException { try { execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mFlaggedMessageCount = Math.max(0, flaggedMessageCount); db.execSQL("UPDATE folders SET flagged_count = ? WHERE id = ?", new Object[] { mFlaggedMessageCount, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public void setLastChecked(final long lastChecked) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastChecked(lastChecked); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?", new Object[] { lastChecked, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public void setLastPush(final long lastChecked) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastPush(lastChecked); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET last_pushed = ? WHERE id = ?", new Object[] { lastChecked, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public int getVisibleLimit() throws MessagingException { open(OpenMode.READ_WRITE); return mVisibleLimit; } public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException { if ( mVisibleLimit == 0) { return ; } open(OpenMode.READ_WRITE); Message[] messages = getMessages(null, false); for (int i = mVisibleLimit; i < messages.length; i++) { if (listener != null) { listener.messageRemoved(messages[i]); } messages[i].destroy(); } } public void setVisibleLimit(final int visibleLimit) throws MessagingException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mVisibleLimit = visibleLimit; db.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?", new Object[] { mVisibleLimit, mFolderId }); return null; } }); } @Override public void setStatus(final String status) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setStatus(status); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET status = ? WHERE id = ?", new Object[] { status, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public void setPushState(final String pushState) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mPushState = pushState; db.execSQL("UPDATE folders SET push_state = ? WHERE id = ?", new Object[] { pushState, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public String getPushState() { return mPushState; } @Override public FolderClass getDisplayClass() { return displayClass; } @Override public FolderClass getSyncClass() { if (FolderClass.INHERITED == syncClass) { return getDisplayClass(); } else { return syncClass; } } public FolderClass getRawSyncClass() { return syncClass; } @Override public FolderClass getPushClass() { if (FolderClass.INHERITED == pushClass) { return getSyncClass(); } else { return pushClass; } } public FolderClass getRawPushClass() { return pushClass; } public void setDisplayClass(FolderClass displayClass) { this.displayClass = displayClass; } public void setSyncClass(FolderClass syncClass) { this.syncClass = syncClass; } public void setPushClass(FolderClass pushClass) { this.pushClass = pushClass; } public boolean isIntegrate() { return mIntegrate; } public void setIntegrate(boolean integrate) { mIntegrate = integrate; } private String getPrefId() throws MessagingException { open(OpenMode.READ_WRITE); if (prefId == null) { prefId = uUid + "." + mName; } return prefId; } public void delete(Preferences preferences) throws MessagingException { String id = getPrefId(); SharedPreferences.Editor editor = preferences.getPreferences().edit(); editor.remove(id + ".displayMode"); editor.remove(id + ".syncMode"); editor.remove(id + ".pushMode"); editor.remove(id + ".inTopGroup"); editor.remove(id + ".integrate"); editor.commit(); } public void save(Preferences preferences) throws MessagingException { String id = getPrefId(); SharedPreferences.Editor editor = preferences.getPreferences().edit(); // there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX if (displayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".displayMode"); } else { editor.putString(id + ".displayMode", displayClass.name()); } if (syncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName())) { editor.remove(id + ".syncMode"); } else { editor.putString(id + ".syncMode", syncClass.name()); } if (pushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".pushMode"); } else { editor.putString(id + ".pushMode", pushClass.name()); } editor.putBoolean(id + ".inTopGroup", inTopGroup); editor.putBoolean(id + ".integrate", mIntegrate); editor.commit(); } public FolderClass getDisplayClass(Preferences preferences) throws MessagingException { String id = getPrefId(); return FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode", FolderClass.NO_CLASS.name())); } @Override public void refresh(Preferences preferences) throws MessagingException { String id = getPrefId(); try { displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode", FolderClass.NO_CLASS.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e); displayClass = FolderClass.NO_CLASS; } if (displayClass == FolderClass.NONE) { displayClass = FolderClass.NO_CLASS; } FolderClass defSyncClass = FolderClass.INHERITED; if (K9.INBOX.equals(getName())) { defSyncClass = FolderClass.FIRST_CLASS; } try { syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode", defSyncClass.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e); syncClass = defSyncClass; } if (syncClass == FolderClass.NONE) { syncClass = FolderClass.INHERITED; } FolderClass defPushClass = FolderClass.SECOND_CLASS; boolean defInTopGroup = false; boolean defIntegrate = false; if (K9.INBOX.equals(getName())) { defPushClass = FolderClass.FIRST_CLASS; defInTopGroup = true; defIntegrate = true; } try { pushClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".pushMode", defPushClass.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e); pushClass = defPushClass; } if (pushClass == FolderClass.NONE) { pushClass = FolderClass.INHERITED; } inTopGroup = preferences.getPreferences().getBoolean(id + ".inTopGroup", defInTopGroup); mIntegrate = preferences.getPreferences().getBoolean(id + ".integrate", defIntegrate); } @Override public void fetch(final Message[] messages, final FetchProfile fp, final MessageRetrievalListener listener) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); if (fp.contains(FetchProfile.Item.BODY)) { for (Message message : messages) { LocalMessage localMessage = (LocalMessage)message; Cursor cursor = null; MimeMultipart mp = new MimeMultipart(); mp.setSubType("mixed"); try { cursor = db.rawQuery("SELECT html_content, text_content FROM messages " + "WHERE id = ?", new String[] { Long.toString(localMessage.mId) }); cursor.moveToNext(); String htmlContent = cursor.getString(0); String textContent = cursor.getString(1); if (textContent != null) { LocalTextBody body = new LocalTextBody(textContent, htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/plain"); mp.addBodyPart(bp); } else { TextBody body = new TextBody(htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/html"); mp.addBodyPart(bp); } } finally { if (cursor != null) { cursor.close(); } } try { cursor = db.query( "attachments", new String[] { "id", "size", "name", "mime_type", "store_data", "content_uri", "content_id", "content_disposition" }, "message_id = ?", new String[] { Long.toString(localMessage.mId) }, null, null, null); while (cursor.moveToNext()) { long id = cursor.getLong(0); int size = cursor.getInt(1); String name = cursor.getString(2); String type = cursor.getString(3); String storeData = cursor.getString(4); String contentUri = cursor.getString(5); String contentId = cursor.getString(6); String contentDisposition = cursor.getString(7); Body body = null; if (contentDisposition == null) { contentDisposition = "attachment"; } if (contentUri != null) { body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication); } MimeBodyPart bp = new LocalAttachmentBodyPart(body, id); bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"", type, name)); bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format("%s;\n filename=\"%s\";\n size=%d", contentDisposition, name, size)); bp.setHeader(MimeHeader.HEADER_CONTENT_ID, contentId); /* * HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that * we can later pull the attachment from the remote store if neccesary. */ bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData); mp.addBodyPart(bp); } } finally { if (cursor != null) { cursor.close(); } } if (mp.getCount() == 1) { BodyPart part = mp.getBodyPart(0); localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType()); localMessage.setBody(part.getBody()); } else { localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed"); localMessage.setBody(mp); } } } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) throws MessagingException { open(OpenMode.READ_WRITE); throw new MessagingException( "LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented"); } /** * Populate the header fields of the given list of messages by reading * the saved header data from the database. * * @param messages * The messages whose headers should be loaded. * @throws UnavailableStorageException */ private void populateHeaders(final List<LocalMessage> messages) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor cursor = null; if (messages.size() == 0) { return null; } try { Map<Long, LocalMessage> popMessages = new HashMap<Long, LocalMessage>(); List<String> ids = new ArrayList<String>(); StringBuffer questions = new StringBuffer(); for (int i = 0; i < messages.size(); i++) { if (i != 0) { questions.append(", "); } questions.append("?"); LocalMessage message = messages.get(i); Long id = message.getId(); ids.add(Long.toString(id)); popMessages.put(id, message); } cursor = db.rawQuery( "SELECT message_id, name, value FROM headers " + "WHERE message_id in ( " + questions + ") ", ids.toArray(EMPTY_STRING_ARRAY)); while (cursor.moveToNext()) { Long id = cursor.getLong(0); String name = cursor.getString(1); String value = cursor.getString(2); //Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id); popMessages.get(id).addHeader(name, value); } } finally { if (cursor != null) { cursor.close(); } } return null; } }); } @Override public Message getMessage(final String uid) throws MessagingException { try { return execute(false, new DbCallback<Message>() { @Override public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { open(OpenMode.READ_WRITE); LocalMessage message = new LocalMessage(uid, LocalFolder.this); Cursor cursor = null; try { cursor = db.rawQuery( "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE uid = ? AND folder_id = ?", new String[] { message.getUid(), Long.toString(mFolderId) }); if (!cursor.moveToNext()) { return null; } message.populateFromGetMessageCursor(cursor); } finally { if (cursor != null) { cursor.close(); } } return message; } catch (MessagingException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(listener, true); } @Override public Message[] getMessages(final MessageRetrievalListener listener, final boolean includeDeleted) throws MessagingException { try { return execute(false, new DbCallback<Message[]>() { @Override public Message[] doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { open(OpenMode.READ_WRITE); return LocalStore.this.getMessages( listener, LocalFolder.this, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE " + (includeDeleted ? "" : "deleted = 0 AND ") + " folder_id = ? ORDER BY date DESC" , new String[] { Long.toString(mFolderId) } ); } catch (MessagingException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { open(OpenMode.READ_WRITE); if (uids == null) { return getMessages(listener); } ArrayList<Message> messages = new ArrayList<Message>(); for (String uid : uids) { Message message = getMessage(uid); if (message != null) { messages.add(message); } } return messages.toArray(EMPTY_MESSAGE_ARRAY); } @Override public void copyMessages(Message[] msgs, Folder folder) throws MessagingException { if (!(folder instanceof LocalFolder)) { throw new MessagingException("copyMessages called with incorrect Folder"); } ((LocalFolder) folder).appendMessages(msgs, true); } @Override public void moveMessages(final Message[] msgs, final Folder destFolder) throws MessagingException { if (!(destFolder instanceof LocalFolder)) { throw new MessagingException("moveMessages called with non-LocalFolder"); } final LocalFolder lDestFolder = (LocalFolder)destFolder; try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { lDestFolder.open(OpenMode.READ_WRITE); for (Message message : msgs) { LocalMessage lMessage = (LocalMessage)message; if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1); } if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); lDestFolder.setFlaggedMessageCount(lDestFolder.getFlaggedMessageCount() + 1); } String oldUID = message.getUid(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID " + message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName()); message.setUid(K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString()); db.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] { lDestFolder.getId(), message.getUid(), lMessage.getId() }); LocalMessage placeHolder = new LocalMessage(oldUID, LocalFolder.this); placeHolder.setFlagInternal(Flag.DELETED, true); placeHolder.setFlagInternal(Flag.SEEN, true); appendMessages(new Message[] { placeHolder }); } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * The method differs slightly from the contract; If an incoming message already has a uid * assigned and it matches the uid of an existing message then this message will replace the * old message. It is implemented as a delete/insert. This functionality is used in saving * of drafts and re-synchronization of updated server messages. * * NOTE that although this method is located in the LocalStore class, it is not guaranteed * that the messages supplied as parameters are actually {@link LocalMessage} instances (in * fact, in most cases, they are not). Therefore, if you want to make local changes only to a * message, retrieve the appropriate local message instance first (if it already exists). */ @Override public void appendMessages(Message[] messages) throws MessagingException { appendMessages(messages, false); } /** * The method differs slightly from the contract; If an incoming message already has a uid * assigned and it matches the uid of an existing message then this message will replace the * old message. It is implemented as a delete/insert. This functionality is used in saving * of drafts and re-synchronization of updated server messages. * * NOTE that although this method is located in the LocalStore class, it is not guaranteed * that the messages supplied as parameters are actually {@link LocalMessage} instances (in * fact, in most cases, they are not). Therefore, if you want to make local changes only to a * message, retrieve the appropriate local message instance first (if it already exists). */ private void appendMessages(final Message[] messages, final boolean copy) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { for (Message message : messages) { if (!(message instanceof MimeMessage)) { throw new Error("LocalStore can only store Messages that extend MimeMessage"); } String uid = message.getUid(); if (uid == null || copy) { uid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString(); if (!copy) { message.setUid(uid); } } else { Message oldMessage = getMessage(uid); if (oldMessage != null && !oldMessage.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); } if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); } /* * The message may already exist in this Folder, so delete it first. */ deleteAttachments(message.getUid()); db.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?", new Object[] { mFolderId, message.getUid() }); } ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); for (Part viewable : viewables) { try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); } else { sbText.append(text); } } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } String text = sbText.toString(); String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); try { ContentValues cv = new ContentValues(); cv.put("uid", uid); cv.put("subject", message.getSubject()); cv.put("sender_list", Address.pack(message.getFrom())); cv.put("date", message.getSentDate() == null ? System.currentTimeMillis() : message.getSentDate().getTime()); cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase()); cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0); cv.put("folder_id", mFolderId); cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO))); cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC))); cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC))); cv.put("html_content", html.length() > 0 ? html : null); cv.put("text_content", text.length() > 0 ? text : null); cv.put("preview", preview.length() > 0 ? preview : null); cv.put("reply_to_list", Address.pack(message.getReplyTo())); cv.put("attachment_count", attachments.size()); cv.put("internal_date", message.getInternalDate() == null ? System.currentTimeMillis() : message.getInternalDate().getTime()); String messageId = message.getMessageId(); if (messageId != null) { cv.put("message_id", messageId); } long messageUid; messageUid = db.insert("messages", "uid", cv); for (Part attachment : attachments) { saveAttachment(messageUid, attachment, copy); } saveHeaders(messageUid, (MimeMessage)message); if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() + 1); } if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() + 1); } } catch (Exception e) { throw new MessagingException("Error appending message", e); } } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * Update the given message in the LocalStore without first deleting the existing * message (contrast with appendMessages). This method is used to store changes * to the given message while updating attachments and not removing existing * attachment data. * TODO In the future this method should be combined with appendMessages since the Message * contains enough data to decide what to do. * @param message * @throws MessagingException */ public void updateMessage(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); message.buildMimeRepresentation(); MimeUtility.collectParts(message, viewables, attachments); StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); for (int i = 0, count = viewables.size(); i < count; i++) { Part viewable = viewables.get(i); try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); } else { sbText.append(text); } } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } String text = sbText.toString(); String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); if (preview == null || preview.length() == 0) { preview = calculateContentPreview(Html.fromHtml(html).toString()); } try { db.execSQL("UPDATE messages SET " + "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, " + "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, " + "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, " + "attachment_count = ? WHERE id = ?", new Object[] { message.getUid(), message.getSubject(), Address.pack(message.getFrom()), message.getSentDate() == null ? System .currentTimeMillis() : message.getSentDate() .getTime(), Utility.combine(message.getFlags(), ',').toUpperCase(), mFolderId, Address.pack(message .getRecipients(RecipientType.TO)), Address.pack(message .getRecipients(RecipientType.CC)), Address.pack(message .getRecipients(RecipientType.BCC)), html.length() > 0 ? html : null, text.length() > 0 ? text : null, preview.length() > 0 ? preview : null, Address.pack(message.getReplyTo()), attachments.size(), message.mId }); for (int i = 0, count = attachments.size(); i < count; i++) { Part attachment = attachments.get(i); saveAttachment(message.mId, attachment, false); } saveHeaders(message.getId(), message); } catch (Exception e) { throw new MessagingException("Error appending message", e); } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * Save the headers of the given message. Note that the message is not * necessarily a {@link LocalMessage} instance. */ private void saveHeaders(final long id, final MimeMessage message) throws MessagingException { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { boolean saveAllHeaders = mAccount.saveAllHeaders(); boolean gotAdditionalHeaders = false; deleteHeaders(id); for (String name : message.getHeaderNames()) { if (saveAllHeaders || HEADERS_TO_SAVE.contains(name)) { String[] values = message.getHeader(name); for (String value : values) { ContentValues cv = new ContentValues(); cv.put("message_id", id); cv.put("name", name); cv.put("value", value); db.insert("headers", "name", cv); } } else { gotAdditionalHeaders = true; } } if (!gotAdditionalHeaders) { // Remember that all headers for this message have been saved, so it is // not necessary to download them again in case the user wants to see all headers. List<Flag> appendedFlags = new ArrayList<Flag>(); appendedFlags.addAll(Arrays.asList(message.getFlags())); appendedFlags.add(Flag.X_GOT_ALL_HEADERS); db.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[] { Utility.combine(appendedFlags.toArray(), ',').toUpperCase(), id }); } return null; } }); } private void deleteHeaders(final long id) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM headers WHERE message_id = ?", new Object[] { id }); return null; } }); } /** * @param messageId * @param attachment * @param attachmentId -1 to create a new attachment or >= 0 to update an existing * @throws IOException * @throws MessagingException */ private void saveAttachment(final long messageId, final Part attachment, final boolean saveAsNew) throws IOException, MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } final File attachmentDirectory = StorageManager.getInstance(mApplication).getAttachmentDirectory(uUid, mStorageProviderId); if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { /* * If the attachment has a body we're expected to save it into the local store * so we copy the data into a cached attachment file. */ InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, attachmentDirectory); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { /* * If the attachment is not yet downloaded see if we can pull a size * off the Content-Disposition. */ String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader( MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null); String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition()); if (name == null && contentDisposition != null) { name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); cv.put("content_disposition", contentDisposition); attachmentId = db.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); db.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachmentId != -1 && tempAttachmentFile != null) { File attachmentFile = new File(attachmentDirectory, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); contentUri = AttachmentProvider.getAttachmentUri( mAccount, attachmentId); attachment.setBody(new LocalAttachmentBody(contentUri, mApplication)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); db.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } /* The message has attachment with Content-ID */ if (contentId != null && contentUri != null) { Cursor cursor = null; cursor = db.query("messages", new String[] { "html_content" }, "id = ?", new String[] { Long.toString(messageId) }, null, null, null); try { if (cursor.moveToNext()) { String new_html; new_html = cursor.getString(0); new_html = new_html.replaceAll("cid:" + contentId, contentUri.toString()); ContentValues cv = new ContentValues(); cv.put("html_content", new_html); db.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) }); } } finally { if (cursor != null) { cursor.close(); } } } if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } return null; } catch (MessagingException e) { throw new WrappedException(e); } catch (IOException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw (MessagingException) cause; } } } /** * Changes the stored uid of the given message (using it's internal id as a key) to * the uid in the message. * @param message */ public void changeUid(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); final ContentValues cv = new ContentValues(); cv.put("uid", message.getUid()); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) }); return null; } }); } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { open(OpenMode.READ_WRITE); for (Message message : messages) { message.setFlags(flags, value); } } @Override public void setFlags(Flag[] flags, boolean value) throws MessagingException { open(OpenMode.READ_WRITE); for (Message message : getMessages(null)) { message.setFlags(flags, value); } } @Override public String getUidFromMessageId(Message message) throws MessagingException { throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder"); } private void clearMessagesWhere(final String whereClause, final String[] params) throws MessagingException { open(OpenMode.READ_ONLY); Message[] messages = LocalStore.this.getMessages( null, this, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE " + whereClause, params); for (Message message : messages) { deleteAttachments(message.getUid()); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM messages WHERE " + whereClause, params); return null; } }); resetUnreadAndFlaggedCounts(); } public void clearMessagesOlderThan(long cutoff) throws MessagingException { final String where = "folder_id = ? and date < ?"; final String[] params = new String[] { Long.toString(mFolderId), Long.toString(cutoff) }; clearMessagesWhere(where, params); } public void clearAllMessages() throws MessagingException { final String where = "folder_id = ?"; final String[] params = new String[] { Long.toString(mFolderId) }; clearMessagesWhere(where, params); setPushState(null); setLastPush(0); setLastChecked(0); } private void resetUnreadAndFlaggedCounts() { try { int newUnread = 0; int newFlagged = 0; Message[] messages = getMessages(null); for (Message message : messages) { if (!message.isSet(Flag.SEEN)) { newUnread++; } if (message.isSet(Flag.FLAGGED)) { newFlagged++; } } setUnreadMessageCount(newUnread); setFlaggedMessageCount(newFlagged); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to fetch all messages from LocalStore", e); } } @Override public void delete(final boolean recurse) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { // We need to open the folder first to make sure we've got it's id open(OpenMode.READ_ONLY); Message[] messages = getMessages(null); for (Message message : messages) { deleteAttachments(message.getUid()); } } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM folders WHERE id = ?", new Object[] { Long.toString(mFolderId), }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public boolean equals(Object o) { if (o instanceof LocalFolder) { return ((LocalFolder)o).mName.equals(mName); } return super.equals(o); } @Override public int hashCode() { return mName.hashCode(); } @Override public Flag[] getPermanentFlags() throws MessagingException { return PERMANENT_FLAGS; } private void deleteAttachments(final long messageId) throws MessagingException { open(OpenMode.READ_WRITE); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor attachmentsCursor = null; try { attachmentsCursor = db.query("attachments", new String[] { "id" }, "message_id = ?", new String[] { Long.toString(messageId) }, null, null, null); final File attachmentDirectory = StorageManager.getInstance(mApplication) .getAttachmentDirectory(uUid, mStorageProviderId); while (attachmentsCursor.moveToNext()) { long attachmentId = attachmentsCursor.getLong(0); try { File file = new File(attachmentDirectory, Long.toString(attachmentId)); if (file.exists()) { file.delete(); } } catch (Exception e) { } } } finally { if (attachmentsCursor != null) { attachmentsCursor.close(); } } return null; } }); } private void deleteAttachments(final String uid) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor messagesCursor = null; try { messagesCursor = db.query("messages", new String[] { "id" }, "folder_id = ? AND uid = ?", new String[] { Long.toString(mFolderId), uid }, null, null, null); while (messagesCursor.moveToNext()) { long messageId = messagesCursor.getLong(0); deleteAttachments(messageId); } } catch (MessagingException e) { throw new WrappedException(e); } finally { if (messagesCursor != null) { messagesCursor.close(); } } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /* * calculateContentPreview * Takes a plain text message body as a string. * Returns a message summary as a string suitable for showing in a message list * * A message summary should be about the first 160 characters * of unique text written by the message sender * Quoted text, "On $date" and so on will be stripped out. * All newlines and whitespace will be compressed. * */ public String calculateContentPreview(String text) { if (text == null) { return null; } // Only look at the first 8k of a message when calculating // the preview. This should avoid unnecessary // memory usage on large messages if (text.length() > 8192) { text = text.substring(0,8192); } text = text.replaceAll("(?m)^----.*?$",""); text = text.replaceAll("(?m)^[#>].*$",""); text = text.replaceAll("(?m)^On .*wrote.?$",""); text = text.replaceAll("(?m)^.*\\w+:$",""); text = text.replaceAll("https?://\\S+","..."); text = text.replaceAll("(\\r|\\n)+"," "); text = text.replaceAll("\\s+"," "); if (text.length() <= 512) { return text; } else { text = text.substring(0,512); return text; } } public String markupContent(String text, String html) { if (text.length() > 0 && html.length() == 0) { html = htmlifyString(text); } html = convertEmoji2ImgForDocomo(html); return html; } public String htmlifyString(String text) { // Our HTMLification code is somewhat memory intensive // and was causing lots of OOM errors on the market // if the message is big and plain text, just do // a trivial htmlification if (text.length() > MAX_SMART_HTMLIFY_MESSAGE_LENGTH) { return "<html><head/><body>" + htmlifyMessageHeader() + text + htmlifyMessageFooter() + "</body></html>"; } StringReader reader = new StringReader(text); StringBuilder buff = new StringBuilder(text.length() + 512); int c = 0; try { while ((c = reader.read()) != -1) { switch (c) { case '&': buff.append("&amp;"); break; case '<': buff.append("&lt;"); break; case '>': buff.append("&gt;"); break; case '\r': break; default: buff.append((char)c); }//switch } } catch (IOException e) { //Should never happen Log.e(K9.LOG_TAG, null, e); } text = buff.toString(); text = text.replaceAll("\\s*([-=_]{30,}+)\\s*","<hr />"); text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])","$1 "); text = text.replaceAll("(?m)(\r\n|\n|\r){4,}","\n\n"); Matcher m = Regex.WEB_URL_PATTERN.matcher(text); StringBuffer sb = new StringBuffer(text.length() + 512); sb.append("<html><head></head><body>"); sb.append(htmlifyMessageHeader()); while (m.find()) { int start = m.start(); if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) { if (m.group().indexOf(':') > 0) // With no URI-schema we may get "http:/" links with the second / missing { m.appendReplacement(sb, "<a href=\"$0\">$0</a>"); } else { m.appendReplacement(sb, "<a href=\"http://$0\">$0</a>"); } } else { m.appendReplacement(sb, "$0"); } } m.appendTail(sb); sb.append(htmlifyMessageFooter()); sb.append("</body></html>"); text = sb.toString(); return text; } private String htmlifyMessageHeader() { if (K9.messageViewFixedWidthFont()) { return "<pre style=\"white-space: pre-wrap; word-wrap:break-word; \">"; } else { return "<div style=\"white-space: pre-wrap; word-wrap:break-word; \">"; } } private String htmlifyMessageFooter() { if (K9.messageViewFixedWidthFont()) { return "</pre>"; } else { return "</div>"; } } public String convertEmoji2ImgForDocomo(String html) { StringReader reader = new StringReader(html); StringBuilder buff = new StringBuilder(html.length() + 512); int c = 0; try { while ((c = reader.read()) != -1) { switch (c) { // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree case 0xE6F9: //docomo kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE729: //docomo wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xE6D2: //docomo info02 buff.append("<img src=\"file:///android_asset/emoticons/info02.gif\" alt=\"info02\" />"); break; case 0xE753: //docomo smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE68D: //docomo heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE6A5: //docomo downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE6AD: //docomo pouch buff.append("<img src=\"file:///android_asset/emoticons/pouch.gif\" alt=\"pouch\" />"); break; case 0xE6D4: //docomo by-d buff.append("<img src=\"file:///android_asset/emoticons/by-d.gif\" alt=\"by-d\" />"); break; case 0xE6D7: //docomo free buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />"); break; case 0xE6E8: //docomo seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE74E: //docomo snail buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />"); break; case 0xE658: //docomo basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE65A: //docomo pocketbell buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />"); break; case 0xE6E3: //docomo two buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />"); break; case 0xE74A: //docomo cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE6D0: //docomo faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; case 0xE661: //docomo ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE64B: //docomo virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE67E: //docomo ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE6D6: //docomo yen buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />"); break; case 0xE6E0: //docomo sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE6FE: //docomo bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE6E1: //docomo mobaq buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />"); break; case 0xE70A: //docomo sign05 buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />"); break; case 0xE667: //docomo bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE731: //docomo copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE678: //docomo upwardright buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />"); break; case 0xE694: //docomo scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE682: //docomo bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE64D: //docomo scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE6D9: //docomo key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE734: //docomo secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE74F: //docomo chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE691: //docomo eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE70B: //docomo ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE714: //docomo door buff.append("<img src=\"file:///android_asset/emoticons/door.gif\" alt=\"door\" />"); break; case 0xE64F: //docomo capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xE674: //docomo boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE726: //docomo lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE68F: //docomo diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE69B: //docomo wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xE747: //docomo maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE64C: //docomo libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE647: //docomo taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE645: //docomo sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xE6FC: //docomo annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE6E6: //docomo five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE676: //docomo karaoke buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />"); break; case 0xE69D: //docomo moon1 buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />"); break; case 0xE709: //docomo sign04 buff.append("<img src=\"file:///android_asset/emoticons/sign04.gif\" alt=\"sign04\" />"); break; case 0xE72A: //docomo happy02 buff.append("<img src=\"file:///android_asset/emoticons/happy02.gif\" alt=\"happy02\" />"); break; case 0xE669: //docomo hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE71B: //docomo ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; case 0xE644: //docomo mist buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />"); break; case 0xE73B: //docomo full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xE683: //docomo book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE707: //docomo sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE716: //docomo pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE671: //docomo bar buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />"); break; case 0xE72B: //docomo bearing buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />"); break; case 0xE65C: //docomo subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE725: //docomo gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xE745: //docomo apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE65F: //docomo rvcar buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />"); break; case 0xE664: //docomo building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE737: //docomo danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE702: //docomo sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xE6EC: //docomo heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xE660: //docomo bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE72D: //docomo crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE652: //docomo sports buff.append("<img src=\"file:///android_asset/emoticons/sports.gif\" alt=\"sports\" />"); break; case 0xE6B8: //docomo on buff.append("<img src=\"file:///android_asset/emoticons/on.gif\" alt=\"on\" />"); break; case 0xE73C: //docomo leftright buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />"); break; case 0xE6BA: //docomo clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xE6F0: //docomo happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE701: //docomo sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE63E: //docomo sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xE67D: //docomo event buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />"); break; case 0xE689: //docomo memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; case 0xE68B: //docomo game buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />"); break; case 0xE718: //docomo wrench buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />"); break; case 0xE741: //docomo clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE693: //docomo rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE6F6: //docomo note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xE67A: //docomo music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE743: //docomo tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xE656: //docomo soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE69C: //docomo newmoon buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />"); break; case 0xE73E: //docomo school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE750: //docomo penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE696: //docomo downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE6CE: //docomo phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE728: //docomo bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE662: //docomo airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE74C: //docomo noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE704: //docomo sign03 buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />"); break; case 0xE68E: //docomo spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE698: //docomo foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE712: //docomo snowboard buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />"); break; case 0xE684: //docomo ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE6DA: //docomo enter buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />"); break; case 0xE6EA: //docomo nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE722: //docomo coldsweats01 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />"); break; case 0xE6F7: //docomo spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE710: //docomo rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xE73F: //docomo wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE686: //docomo birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE721: //docomo confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE6FF: //docomo notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE724: //docomo pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE6A4: //docomo xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE6FB: //docomo flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE71D: //docomo bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE6DC: //docomo search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE757: //docomo shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE680: //docomo nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xE66D: //docomo signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE66A: //docomo 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE6F4: //docomo wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE641: //docomo snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE6AE: //docomo pen buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />"); break; case 0xE70D: //docomo appli02 buff.append("<img src=\"file:///android_asset/emoticons/appli02.gif\" alt=\"appli02\" />"); break; case 0xE732: //docomo tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE755: //docomo pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE648: //docomo gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE6DE: //docomo flag buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />"); break; case 0xE6A1: //docomo dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE6EF: //docomo heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xE643: //docomo typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE65B: //docomo train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE746: //docomo bud buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />"); break; case 0xE653: //docomo baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE6B2: //docomo chair buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />"); break; case 0xE64A: //docomo leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE6E7: //docomo six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE6E4: //docomo three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xE6DF: //docomo freedial buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />"); break; case 0xE744: //docomo banana buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />"); break; case 0xE6DB: //docomo clear buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />"); break; case 0xE6AC: //docomo slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE666: //docomo hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE663: //docomo house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE695: //docomo paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE67F: //docomo smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE65D: //docomo bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE6B1: //docomo shadow buff.append("<img src=\"file:///android_asset/emoticons/shadow.gif\" alt=\"shadow\" />"); break; case 0xE670: //docomo cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xE654: //docomo golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE708: //docomo dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE748: //docomo cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE6F1: //docomo angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE736: //docomo r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xE6A2: //docomo cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE6D1: //docomo info01 buff.append("<img src=\"file:///android_asset/emoticons/info01.gif\" alt=\"info01\" />"); break; case 0xE687: //docomo telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE68C: //docomo cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE70E: //docomo t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE733: //docomo run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xE679: //docomo carouselpony buff.append("<img src=\"file:///android_asset/emoticons/carouselpony.gif\" alt=\"carouselpony\" />"); break; case 0xE646: //docomo aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE690: //docomo club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE64E: //docomo sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xE6F5: //docomo up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xE720: //docomo think buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />"); break; case 0xE6E2: //docomo one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xE6D8: //docomo id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE675: //docomo hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; case 0xE6B7: //docomo soon buff.append("<img src=\"file:///android_asset/emoticons/soon.gif\" alt=\"soon\" />"); break; case 0xE717: //docomo loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE673: //docomo fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE719: //docomo pencil buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />"); break; case 0xE697: //docomo upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xE730: //docomo clip buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />"); break; case 0xE6ED: //docomo heart02 buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />"); break; case 0xE69A: //docomo eyeglass buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />"); break; case 0xE65E: //docomo car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xE742: //docomo cherry buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />"); break; case 0xE71C: //docomo sandclock buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />"); break; case 0xE735: //docomo recycle buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />"); break; case 0xE752: //docomo delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE69E: //docomo moon2 buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />"); break; case 0xE68A: //docomo tv buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />"); break; case 0xE706: //docomo sweat01 buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />"); break; case 0xE738: //docomo ban buff.append("<img src=\"file:///android_asset/emoticons/ban.gif\" alt=\"ban\" />"); break; case 0xE672: //docomo beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xE640: //docomo rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xE69F: //docomo moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE657: //docomo ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE70C: //docomo appli01 buff.append("<img src=\"file:///android_asset/emoticons/appli01.gif\" alt=\"appli01\" />"); break; case 0xE6E5: //docomo four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE699: //docomo shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xE63F: //docomo cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE72F: //docomo ng buff.append("<img src=\"file:///android_asset/emoticons/ng.gif\" alt=\"ng\" />"); break; case 0xE6A3: //docomo yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE73A: //docomo pass buff.append("<img src=\"file:///android_asset/emoticons/pass.gif\" alt=\"pass\" />"); break; case 0xE67C: //docomo drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xE727: //docomo good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE6EB: //docomo zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xE72C: //docomo catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE6D5: //docomo d-point buff.append("<img src=\"file:///android_asset/emoticons/d-point.gif\" alt=\"d-point\" />"); break; case 0xE6F2: //docomo despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE700: //docomo down buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />"); break; case 0xE655: //docomo tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE703: //docomo sign02 buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />"); break; case 0xE711: //docomo denim buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />"); break; case 0xE705: //docomo impact buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />"); break; case 0xE642: //docomo thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE66C: //docomo parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE6F3: //docomo sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE71E: //docomo japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xE6FD: //docomo punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xE73D: //docomo updown buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />"); break; case 0xE66F: //docomo restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE66E: //docomo toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; case 0xE739: //docomo empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE723: //docomo coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE6B9: //docomo end buff.append("<img src=\"file:///android_asset/emoticons/end.gif\" alt=\"end\" />"); break; case 0xE67B: //docomo art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xE72E: //docomo weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE715: //docomo dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE6CF: //docomo mailto buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />"); break; case 0xE6F8: //docomo cute buff.append("<img src=\"file:///android_asset/emoticons/cute.gif\" alt=\"cute\" />"); break; case 0xE6DD: //docomo new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE651: //docomo pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE756: //docomo wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE649: //docomo cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xE650: //docomo aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE740: //docomo fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE681: //docomo camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE71F: //docomo watch buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />"); break; case 0xE6EE: //docomo heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE71A: //docomo crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE6B3: //docomo night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE66B: //docomo gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE692: //docomo ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE685: //docomo present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE6E9: //docomo eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE70F: //docomo moneybag buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />"); break; case 0xE749: //docomo riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE6A0: //docomo fullmoon buff.append("<img src=\"file:///android_asset/emoticons/fullmoon.gif\" alt=\"fullmoon\" />"); break; case 0xE74D: //docomo bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE665: //docomo postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xE677: //docomo movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE668: //docomo atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE688: //docomo mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE6FA: //docomo shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xE713: //docomo bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xE74B: //docomo bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xE754: //docomo horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE751: //docomo fish buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />"); break; case 0xE659: //docomo motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE6D3: //docomo mail buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />"); break; // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree // The spaces between the < and the img are a hack to avoid triggering // K-9's 'load images' button case 0xE223: //softbank eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE415: //softbank coldsweats01 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />"); break; case 0xE21F: //softbank four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE125: //softbank ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE148: //softbank book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE242: //softbank cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xE31C: //softbank rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xE252: //softbank danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE011: //softbank scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE342: //softbank riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE04B: //softbank rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xE03E: //softbank note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xE43C: //softbank sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xE20A: //softbank wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xE42A: //softbank basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE03D: //softbank movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE30E: //softbank smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE003: //softbank kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE21C: //softbank one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xE237: //softbank upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xE407: //softbank sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE03B: //softbank fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE40E: //softbank gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xE245: //softbank libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE24A: //softbank pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE443: //softbank typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE052: //softbank dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE244: //softbank virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE523: //softbank chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE023: //softbank heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE325: //softbank bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xE239: //softbank downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE20C: //softbank heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE211: //softbank freedial buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />"); break; case 0xE11F: //softbank chair buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />"); break; case 0xE108: //softbank coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE330: //softbank dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE404: //softbank smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE304: //softbank tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xE419: //softbank eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE13D: //softbank thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE013: //softbank ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE136: //softbank bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE059: //softbank angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE01D: //softbank airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE048: //softbank snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE435: //softbank bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE20E: //softbank spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE247: //softbank sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xE157: //softbank school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE10F: //softbank flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE502: //softbank art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xE338: //softbank japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xE34B: //softbank birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE22B: //softbank empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE311: //softbank bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE012: //softbank paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE151: //softbank toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; case 0xE01A: //softbank horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE03A: //softbank gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE03F: //softbank key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE00D: //softbank punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xE24D: //softbank ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE105: //softbank bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE00E: //softbank good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE154: //softbank atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE405: //softbank wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xE030: //softbank cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE057: //softbank happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE229: //softbank id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE016: //softbank baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE044: //softbank wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE115: //softbank run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xE14F: //softbank parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE327: //softbank heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xE014: //softbank golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE021: //softbank sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xE30A: //softbank music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE411: //softbank crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE536: //softbank foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE047: //softbank beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xE43E: //softbank wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE022: //softbank heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xE007: //softbank shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xE010: //softbank rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE32E: //softbank shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xE055: //softbank penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE03C: //softbank karaoke buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />"); break; case 0xE018: //softbank soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE159: //softbank bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE107: //softbank shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE04A: //softbank sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xE156: //softbank 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE110: //softbank clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE034: //softbank ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; case 0xE24F: //softbank r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xE112: //softbank present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE14D: //softbank bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE42E: //softbank rvcar buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />"); break; case 0xE13E: //softbank boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE413: //softbank weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE241: //softbank gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE212: //softbank new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE324: //softbank slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE220: //softbank five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE503: //softbank drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xE248: //softbank capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xE049: //softbank cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE243: //softbank leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE326: //softbank notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE00B: //softbank faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; case 0xE221: //softbank six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE240: //softbank taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE24E: //softbank copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE224: //softbank nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE008: //softbank camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE01E: //softbank train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE20D: //softbank diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE009: //softbank telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE019: //softbank fish buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />"); break; case 0xE01C: //softbank yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE40A: //softbank confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE246: //softbank scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE120: //softbank fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE323: //softbank bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE345: //softbank apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE339: //softbank bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE13C: //softbank sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE106: //softbank lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE340: //softbank noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE20F: //softbank club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE114: //softbank search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE10E: //softbank crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE406: //softbank wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE331: //softbank sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE04F: //softbank cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE301: //softbank memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; case 0xE01B: //softbank car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xE314: //softbank ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE315: //softbank secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE236: //softbank up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xE208: //softbank nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xE006: //softbank t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE12A: //softbank tv buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />"); break; case 0xE238: //softbank downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE10B: //softbank pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE126: //softbank cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE402: //softbank catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE416: //softbank pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE045: //softbank cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xE41B: //softbank ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE23F: //softbank aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE21E: //softbank three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xE056: //softbank delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE14E: //softbank signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE155: //softbank hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE033: //softbank xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE22A: //softbank full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xE123: //softbank spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE132: //softbank motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE434: //softbank subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE403: //softbank think buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />"); break; case 0xE043: //softbank restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE537: //softbank tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE058: //softbank despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE04C: //softbank moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE21D: //softbank two buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />"); break; case 0xE202: //softbank ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE30B: //softbank bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xE118: //softbank maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE103: //softbank loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE225: //softbank zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xE00C: //softbank pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE210: //softbank sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE015: //softbank tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE038: //softbank building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE02D: //softbank clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xE334: //softbank annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE153: //softbank postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xE222: //softbank seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE12F: //softbank dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE00A: //softbank mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE158: //softbank hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE249: //softbank aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE036: //softbank house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE046: //softbank cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE104: //softbank phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE44B: //softbank night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE313: //softbank hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree // The spaces between the < and the img are a hack to avoid triggering // K-9's 'load images' button case 0xE488: //kddi sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xEA88: //kddi id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE4BA: //kddi baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE525: //kddi four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE578: //kddi free buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />"); break; case 0xE4C1: //kddi wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE512: //kddi bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xEB83: //kddi rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE4D0: //kddi cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE473: //kddi crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE48C: //kddi rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xEAC2: //kddi bearing buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />"); break; case 0xE47E: //kddi nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xEAC0: //kddi despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE559: //kddi r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xEB2D: //kddi up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xEA89: //kddi full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xEAC9: //kddi gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xEB79: //kddi recycle buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />"); break; case 0xE5AC: //kddi zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xEAAE: //kddi japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xEB30: //kddi sign03 buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />"); break; case 0xE4B6: //kddi soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE556: //kddi downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE4BE: //kddi slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE4A5: //kddi toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; // Skipping kddi codepoint E523 two // It conflicts with an earlier definition from another carrier: // softbank chick case 0xE496: //kddi scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE4C6: //kddi game buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />"); break; case 0xE5A0: //kddi birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE5B8: //kddi pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE516: //kddi hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; case 0xE475: //kddi sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE4A3: //kddi atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE59A: //kddi basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE497: //kddi sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xEACD: //kddi delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE5A8: //kddi newmoon buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />"); break; case 0xE49E: //kddi ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE5AE: //kddi wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE4E6: //kddi sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE59E: //kddi event buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />"); break; case 0xE4AB: //kddi house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE491: //kddi gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE4C9: //kddi xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE5BE: //kddi note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xEB2F: //kddi sign02 buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />"); break; case 0xE508: //kddi music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE5DF: //kddi hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE5BC: //kddi subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE5C9: //kddi crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE4BC: //kddi spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE514: //kddi ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; // Skipping kddi codepoint E502 tv // It conflicts with an earlier definition from another carrier: // softbank art case 0xE4AC: //kddi restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE529: //kddi eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE518: //kddi search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE505: //kddi notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE498: //kddi capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xEB7E: //kddi snail buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />"); break; case 0xEA97: //kddi bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xEB08: //kddi phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE4D2: //kddi cherry buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />"); break; case 0xE54D: //kddi downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE5C3: //kddi wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xEAAC: //kddi ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE515: //kddi camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE5B6: //kddi t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE5C4: //kddi lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE4AD: //kddi building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE4CE: //kddi maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE5AA: //kddi moon2 buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />"); break; case 0xE5B4: //kddi noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE5A6: //kddi scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE4AA: //kddi bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE4B5: //kddi train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE477: //kddi heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE481: //kddi danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE597: //kddi cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xEB2B: //kddi shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xEB7C: //kddi wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE471: //kddi happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE4CA: //kddi cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE4D5: //kddi riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE587: //kddi wrench buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />"); break; case 0xEB2A: //kddi foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE47D: //kddi smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE4DC: //kddi penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE4B3: //kddi airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE4DE: //kddi pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE59B: //kddi pocketbell buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />"); break; case 0xE4AF: //kddi bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE4A6: //kddi parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE486: //kddi moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE5A4: //kddi eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE50C: //kddi cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE54C: //kddi upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xEA82: //kddi ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE4B1: //kddi car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xEB80: //kddi smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE5B0: //kddi impact buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />"); break; case 0xE504: //kddi moneybag buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />"); break; case 0xE4B9: //kddi motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE494: //kddi virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE595: //kddi heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xEB03: //kddi pen buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />"); break; case 0xE57D: //kddi yen buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />"); break; case 0xE598: //kddi mist buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />"); break; case 0xE5A2: //kddi diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE4A4: //kddi 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE524: //kddi three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xEB7B: //kddi updown buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />"); break; case 0xE5A1: //kddi spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE495: //kddi libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE588: //kddi mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE599: //kddi golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE520: //kddi faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; // Skipping kddi codepoint E503 karaoke // It conflicts with an earlier definition from another carrier: // softbank drama case 0xE4D6: //kddi fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE4A1: //kddi pencil buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />"); break; case 0xE522: //kddi one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xEB84: //kddi sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE476: //kddi flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE46B: //kddi run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xEAF5: //kddi drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xEAB9: //kddi apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE4EB: //kddi kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE55D: //kddi enter buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />"); break; case 0xE59F: //kddi ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE526: //kddi five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE571: //kddi gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE517: //kddi movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE4B8: //kddi snowboard buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />"); break; case 0xEAE8: //kddi sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xEA80: //kddi school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE47C: //kddi sandclock buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />"); break; case 0xEB31: //kddi sign05 buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />"); break; case 0xE5AB: //kddi clear buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />"); break; case 0xE5DE: //kddi postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xEB62: //kddi mailto buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />"); break; case 0xE528: //kddi seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE4C2: //kddi bar buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />"); break; case 0xE487: //kddi thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE5A9: //kddi moon1 buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />"); break; case 0xEB7A: //kddi leftright buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />"); break; case 0xE513: //kddi clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE492: //kddi cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xEB78: //kddi loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE4E0: //kddi chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE4CF: //kddi present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE478: //kddi heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xEAC3: //kddi sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE52A: //kddi nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE482: //kddi sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xEABF: //kddi catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE527: //kddi six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE52C: //kddi mobaq buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />"); break; case 0xE485: //kddi snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE4B7: //kddi tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE5BD: //kddi fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE558: //kddi copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE4D8: //kddi horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE4B0: //kddi bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE596: //kddi telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE48F: //kddi aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE46A: //kddi signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE472: //kddi angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE54E: //kddi tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE51A: //kddi boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE493: //kddi leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE5A3: //kddi club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE499: //kddi aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE4AE: //kddi bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE4E7: //kddi bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE49F: //kddi book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE5AD: //kddi ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE5A7: //kddi paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE4E5: //kddi annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE4A0: //kddi clip buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />"); break; case 0xE509: //kddi rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xEAAF: //kddi bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE519: //kddi key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE594: //kddi clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xEB7D: //kddi bud buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />"); break; case 0xEA8A: //kddi empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE5B5: //kddi new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE47A: //kddi bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE5C6: //kddi coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE49A: //kddi pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE4F3: //kddi punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xEB5D: //kddi pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE469: //kddi typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE5B1: //kddi sweat01 buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />"); break; case 0xE4C7: //kddi dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE5C5: //kddi shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE4F9: //kddi good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE4F1: //kddi secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE4E4: //kddi tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xEA81: //kddi hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE4FE: //kddi eyeglass buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />"); break; case 0xEAF1: //kddi night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE555: //kddi upwardright buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />"); break; case 0xEB2E: //kddi down buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />"); break; case 0xE4DB: //kddi cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE59C: //kddi art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xEB69: //kddi weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE4F4: //kddi dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE490: //kddi taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE57A: //kddi watch buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />"); break; case 0xEB2C: //kddi flag buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />"); break; case 0xEB77: //kddi denim buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />"); break; case 0xEAC5: //kddi confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE4B4: //kddi yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE49C: //kddi bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE5A5: //kddi ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE4E1: //kddi dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE521: //kddi mail buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />"); break; case 0xEB35: //kddi banana buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />"); break; case 0xEAA5: //kddi heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE47F: //kddi wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xEB75: //kddi heart02 buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />"); break; case 0xE48D: //kddi cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE4C3: //kddi beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xEAAB: //kddi shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xEA92: //kddi memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; default: buff.append((char)c); }//switch } } catch (IOException e) { //Should never happen Log.e(K9.LOG_TAG, null, e); } return buff.toString(); } @Override public boolean isInTopGroup() { return inTopGroup; } public void setInTopGroup(boolean inTopGroup) { this.inTopGroup = inTopGroup; } } public class LocalTextBody extends TextBody { private String mBodyForDisplay; public LocalTextBody(String body) { super(body); } public LocalTextBody(String body, String bodyForDisplay) throws MessagingException { super(body); this.mBodyForDisplay = bodyForDisplay; } public String getBodyForDisplay() { return mBodyForDisplay; } public void setBodyForDisplay(String mBodyForDisplay) { this.mBodyForDisplay = mBodyForDisplay; } }//LocalTextBody public class LocalMessage extends MimeMessage { private long mId; private int mAttachmentCount; private String mSubject; private String mPreview = ""; private boolean mHeadersLoaded = false; private boolean mMessageDirty = false; public LocalMessage() { } LocalMessage(String uid, Folder folder) throws MessagingException { this.mUid = uid; this.mFolder = folder; } private void populateFromGetMessageCursor(Cursor cursor) throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); for (String flag : flags) { try { this.setFlagInternal(Flag.valueOf(flag), true); } catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } } } this.mId = cursor.getLong(5); this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6))); this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7))); this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8))); this.setReplyTo(Address.unpack(cursor.getString(9))); this.mAttachmentCount = cursor.getInt(10); this.setInternalDate(new Date(cursor.getLong(11))); this.setMessageId(cursor.getString(12)); final String preview = cursor.getString(14); mPreview = (preview == null ? "" : preview); if (this.mFolder == null) { LocalFolder f = new LocalFolder(cursor.getInt(13)); f.open(LocalFolder.OpenMode.READ_WRITE); this.mFolder = f; } } /* Custom version of writeTo that updates the MIME message based on localMessage * changes. */ @Override public void writeTo(OutputStream out) throws IOException, MessagingException { if (mMessageDirty) buildMimeRepresentation(); super.writeTo(out); } private void buildMimeRepresentation() throws MessagingException { if (!mMessageDirty) { return; } super.setSubject(mSubject); if (this.mFrom != null && this.mFrom.length > 0) { super.setFrom(this.mFrom[0]); } super.setReplyTo(mReplyTo); super.setSentDate(this.getSentDate()); super.setRecipients(RecipientType.TO, mTo); super.setRecipients(RecipientType.CC, mCc); super.setRecipients(RecipientType.BCC, mBcc); if (mMessageId != null) super.setMessageId(mMessageId); mMessageDirty = false; } public String getPreview() { return mPreview; } @Override public String getSubject() { return mSubject; } @Override public void setSubject(String subject) throws MessagingException { mSubject = subject; mMessageDirty = true; } @Override public void setMessageId(String messageId) { mMessageId = messageId; mMessageDirty = true; } public int getAttachmentCount() { return mAttachmentCount; } @Override public void setFrom(Address from) throws MessagingException { this.mFrom = new Address[] { from }; mMessageDirty = true; } @Override public void setReplyTo(Address[] replyTo) throws MessagingException { if (replyTo == null || replyTo.length == 0) { mReplyTo = null; } else { mReplyTo = replyTo; } mMessageDirty = true; } /* * For performance reasons, we add headers instead of setting them (see super implementation) * which removes (expensive) them before adding them */ @Override public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { if (type == RecipientType.TO) { if (addresses == null || addresses.length == 0) { this.mTo = null; } else { this.mTo = addresses; } } else if (type == RecipientType.CC) { if (addresses == null || addresses.length == 0) { this.mCc = null; } else { this.mCc = addresses; } } else if (type == RecipientType.BCC) { if (addresses == null || addresses.length == 0) { this.mBcc = null; } else { this.mBcc = addresses; } } else { throw new MessagingException("Unrecognized recipient type."); } mMessageDirty = true; } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } public long getId() { return mId; } @Override public void setFlag(final Flag flag, final boolean set) throws MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { if (flag == Flag.DELETED && set) { delete(); } updateFolderCountsOnFlag(flag, set); LocalMessage.super.setFlag(flag, set); } catch (MessagingException e) { throw new WrappedException(e); } /* * Set the flags on the message. */ db.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[] { Utility.combine(getFlags(), ',').toUpperCase(), mId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /* * If a message is being marked as deleted we want to clear out it's content * and attachments as well. Delete will not actually remove the row since we need * to retain the uid for synchronization purposes. */ private void delete() throws MessagingException { /* * Delete all of the message's content to save space. */ try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("UPDATE messages SET " + "deleted = 1," + "subject = NULL, " + "sender_list = NULL, " + "date = NULL, " + "to_list = NULL, " + "cc_list = NULL, " + "bcc_list = NULL, " + "preview = NULL, " + "html_content = NULL, " + "text_content = NULL, " + "reply_to_list = NULL " + "WHERE id = ?", new Object[] { mId }); /* * Delete all of the message's attachments to save space. * We do this explicit deletion here because we're not deleting the record * in messages, which means our ON DELETE trigger for messages won't cascade */ try { ((LocalFolder) mFolder).deleteAttachments(mId); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM attachments WHERE message_id = ?", new Object[] { mId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } ((LocalFolder)mFolder).deleteHeaders(mId); } /* * Completely remove a message from the local database */ @Override public void destroy() throws MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { ((LocalFolder) mFolder).deleteAttachments(mId); mDb.execSQL("DELETE FROM messages WHERE id = ?", new Object[] { mId }); updateFolderCountsOnFlag(Flag.X_DESTROYED, true); } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } private void updateFolderCountsOnFlag(Flag flag, boolean set) throws MessagingException { /* * Update the unread count on the folder. */ try { LocalFolder folder = (LocalFolder)mFolder; if (flag == Flag.DELETED || flag == Flag.X_DESTROYED) { if (set != isSet(Flag.SEEN)) { folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? -1:1) ); } if (isSet(Flag.FLAGGED)) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? -1 : 1)); } } if ( !isSet(Flag.DELETED) ) { if ( flag == Flag.SEEN ) { if (set != isSet(Flag.SEEN)) { folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? 1: -1) ); } } if ( flag == Flag.FLAGGED ) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? 1 : -1)); } } } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to update LocalStore unread message count", me); throw new RuntimeException(me); } } private void loadHeaders() throws UnavailableStorageException { ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>(); messages.add(this); mHeadersLoaded = true; // set true before calling populate headers to stop recursion ((LocalFolder) mFolder).populateHeaders(messages); } @Override public void addHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.addHeader(name, value); } @Override public void setHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.setHeader(name, value); } @Override public String[] getHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeader(name); } @Override public void removeHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.removeHeader(name); } @Override public Set<String> getHeaderNames() throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeaderNames(); } } public class LocalAttachmentBodyPart extends MimeBodyPart { private long mAttachmentId = -1; public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException { super(body); mAttachmentId = attachmentId; } /** * Returns the local attachment id of this body, or -1 if it is not stored. * @return */ public long getAttachmentId() { return mAttachmentId; } public void setAttachmentId(long attachmentId) { mAttachmentId = attachmentId; } @Override public String toString() { return "" + mAttachmentId; } } public static class LocalAttachmentBody implements Body { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Application mApplication; private Uri mUri; public LocalAttachmentBody(Uri uri, Application application) { mApplication = application; mUri = uri; } public InputStream getInputStream() throws MessagingException { try { return mApplication.getContentResolver().openInputStream(mUri); } catch (FileNotFoundException fnfe) { /* * Since it's completely normal for us to try to serve up attachments that * have been blown away, we just return an empty stream. */ return new ByteArrayInputStream(EMPTY_BYTE_ARRAY); } } public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream in = getInputStream(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(in, base64Out); base64Out.close(); } public Uri getContentUri() { return mUri; } } }
src/com/fsck/k9/mail/store/LocalStore.java
package com.fsck.k9.mail.store; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import org.apache.commons.io.IOUtils; import android.app.Application; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.text.Html; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.Account.LocalStoreMigrationListener; import com.fsck.k9.controller.MessageRemovalListener; import com.fsck.k9.controller.MessageRetrievalListener; import com.fsck.k9.helper.Regex; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.BodyPart; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.filter.Base64OutputStream; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.StorageManager.StorageProvider; import com.fsck.k9.provider.AttachmentProvider; /** * <pre> * Implements a SQLite database backed local store for Messages. * </pre> */ public class LocalStore extends Store implements Serializable, LocalStoreMigrationListener { /** * Callback interface for DB operations. Concept is similar to Spring * HibernateCallback. * * @param <T> * Return value type for {@link #doDbWork(SQLiteDatabase)} */ public static interface DbCallback<T> { /** * @param db * The locked database on which the work should occur. Never * <code>null</code>. * @return Any relevant data. Can be <code>null</code>. * @throws WrappedException * @throws UnavailableStorageException */ T doDbWork(SQLiteDatabase db) throws WrappedException, UnavailableStorageException; } /** * Workaround exception wrapper used to keep the inner exception generated * in a {@link DbCallback}. */ protected static class WrappedException extends RuntimeException { /** * */ private static final long serialVersionUID = 8184421232587399369L; public WrappedException(final Exception cause) { super(cause); } } private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; /** * Immutable empty {@link String} array */ private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final int DB_VERSION = 39; private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.X_DESTROYED, Flag.SEEN, Flag.FLAGGED }; private static final int MAX_SMART_HTMLIFY_MESSAGE_LENGTH = 1024 * 256 ; private String mStorageProviderId; private SQLiteDatabase mDb; { final ReadWriteLock lock = new ReentrantReadWriteLock(true); mReadLock = lock.readLock(); mWriteLock = lock.writeLock(); } /** * Reentrant read lock */ protected final Lock mReadLock; /** * Reentrant write lock (if you lock it 2x from the same thread, you have to * unlock it 2x to release it) */ protected final Lock mWriteLock; private Application mApplication; private String uUid = null; private static Set<String> HEADERS_TO_SAVE = new HashSet<String>(); static { HEADERS_TO_SAVE.add(K9.K9MAIL_IDENTITY); HEADERS_TO_SAVE.add("To"); HEADERS_TO_SAVE.add("Cc"); HEADERS_TO_SAVE.add("From"); HEADERS_TO_SAVE.add("In-Reply-To"); HEADERS_TO_SAVE.add("References"); HEADERS_TO_SAVE.add("Content-ID"); HEADERS_TO_SAVE.add("Content-Disposition"); HEADERS_TO_SAVE.add("X-User-Agent"); } /* * a String containing the columns getMessages expects to work with * in the correct order. */ static private String GET_MESSAGES_COLS = "subject, sender_list, date, uid, flags, id, to_list, cc_list, " + "bcc_list, reply_to_list, attachment_count, internal_date, message_id, folder_id, preview "; private final StorageListener mStorageListener = new StorageListener(); /** * {@link ThreadLocal} to check whether a DB transaction is occuring in the * current {@link Thread}. * * @see #execute(boolean, DbCallback) */ private ThreadLocal<Boolean> inTransaction = new ThreadLocal<Boolean>(); /** * local://localhost/path/to/database/uuid.db * This constructor is only used by {@link Store#getLocalInstance(Account, Application)} * @throws UnavailableStorageException if not {@link StorageProvider#isReady(Context)} */ public LocalStore(Account account, Application application) throws MessagingException { super(account); mApplication = application; mStorageProviderId = account.getLocalStorageProviderId(); account.setLocalStoreMigrationListener(this); uUid = account.getUuid(); lockWrite(); try { openOrCreateDataspace(application); } finally { unlockWrite(); } StorageManager.getInstance(application).addListener(mStorageListener); } /** * Lock the storage for shared operations (concurrent threads are allowed to * run simultaneously). * * <p> * You <strong>have to</strong> invoke {@link #unlockRead()} when you're * done with the storage. * </p> * * @throws UnavailableStorageException * If storage can't be locked because it is not available */ protected void lockRead() throws UnavailableStorageException { mReadLock.lock(); try { StorageManager.getInstance(mApplication).lockProvider(mStorageProviderId); } catch (UnavailableStorageException e) { mReadLock.unlock(); throw e; } catch (RuntimeException e) { mReadLock.unlock(); throw e; } } protected void unlockRead() { StorageManager.getInstance(mApplication).unlockProvider(mStorageProviderId); mReadLock.unlock(); } /** * Lock the storage for exclusive access (other threads aren't allowed to * run simultaneously) * * <p> * You <strong>have to</strong> invoke {@link #unlockWrite()} when you're * done with the storage. * </p> * * @throws UnavailableStorageException * If storage can't be locked because it is not available. */ protected void lockWrite() throws UnavailableStorageException { lockWrite(mStorageProviderId); } /** * Lock the storage for exclusive access (other threads aren't allowed to * run simultaneously) * * <p> * You <strong>have to</strong> invoke {@link #unlockWrite()} when you're * done with the storage. * </p> * * @param providerId * Never <code>null</code>. * * @throws UnavailableStorageException * If storage can't be locked because it is not available. */ protected void lockWrite(final String providerId) throws UnavailableStorageException { mWriteLock.lock(); try { StorageManager.getInstance(mApplication).lockProvider(providerId); } catch (UnavailableStorageException e) { mWriteLock.unlock(); throw e; } catch (RuntimeException e) { mWriteLock.unlock(); throw e; } } protected void unlockWrite() { unlockWrite(mStorageProviderId); } protected void unlockWrite(final String providerId) { StorageManager.getInstance(mApplication).unlockProvider(providerId); mWriteLock.unlock(); } /** * Execute a DB callback in a shared context (doesn't prevent concurrent * shared executions), taking care of locking the DB storage. * * <p> * Can be instructed to start a transaction if none is currently active in * the current thread. Callback will participe in any active transaction (no * inner transaction created). * </p> * * @param transactional * <code>true</code> the callback must be executed in a * transactional context. * @param callback * Never <code>null</code>. * * @param <T> * @return Whatever {@link DbCallback#doDbWork(SQLiteDatabase)} returns. * @throws UnavailableStorageException */ protected <T> T execute(final boolean transactional, final DbCallback<T> callback) throws UnavailableStorageException { lockRead(); final boolean doTransaction = transactional && inTransaction.get() == null; try { final boolean debug = K9.DEBUG; if (doTransaction) { inTransaction.set(Boolean.TRUE); mDb.beginTransaction(); } try { final T result = callback.doDbWork(mDb); if (doTransaction) { mDb.setTransactionSuccessful(); } return result; } finally { if (doTransaction) { final long begin; if (debug) { begin = System.currentTimeMillis(); } else { begin = 0l; } // not doing endTransaction in the same 'finally' block of unlockRead() because endTransaction() may throw an exception mDb.endTransaction(); if (debug) { Log.v(K9.LOG_TAG, "LocalStore: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms"); } } } } finally { if (doTransaction) { inTransaction.set(null); } unlockRead(); } } public void onLocalStoreMigration(final String oldProviderId, final String newProviderId) throws MessagingException { lockWrite(oldProviderId); try { lockWrite(newProviderId); try { try { mDb.close(); } catch (Exception e) { Log.i(K9.LOG_TAG, "Unable to close DB on local store migration", e); } final StorageManager storageManager = StorageManager.getInstance(mApplication); // create new path prepareStorage(newProviderId); // move all database files moveRecursive(storageManager.getDatabase(uUid, oldProviderId), storageManager.getDatabase(uUid, newProviderId)); // move all attachment files moveRecursive(storageManager.getAttachmentDirectory(uUid, oldProviderId), storageManager.getAttachmentDirectory(uUid, newProviderId)); mStorageProviderId = newProviderId; // re-initialize this class with the new Uri openOrCreateDataspace(mApplication); } finally { unlockWrite(newProviderId); } } finally { unlockWrite(oldProviderId); } } private void moveRecursive(File fromDir, File toDir) { if (!fromDir.exists()) { return; } if (!fromDir.isDirectory()) { if (toDir.exists()) { if (!toDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete already existing file/directory " + toDir.getAbsolutePath() + " during migration to/from SD-card"); } } if (!fromDir.renameTo(toDir)) { Log.w(K9.LOG_TAG, "cannot rename " + fromDir.getAbsolutePath() + " to " + toDir.getAbsolutePath() + " - moving instead"); move(fromDir, toDir); } return; } if (!toDir.exists() || !toDir.isDirectory()) { if (toDir.exists() ) { toDir.delete(); } if (!toDir.mkdirs()) { Log.w(K9.LOG_TAG, "cannot create directory " + toDir.getAbsolutePath() + " during migration to/from SD-card"); } } File[] files = fromDir.listFiles(); for (File file : files) { if (file.isDirectory()) { moveRecursive(file, new File(toDir, file.getName())); file.delete(); } else { File target = new File(toDir, file.getName()); if (!file.renameTo(target)) { Log.w(K9.LOG_TAG, "cannot rename " + file.getAbsolutePath() + " to " + target.getAbsolutePath() + " - moving instead"); move(file, target); } } } if (!fromDir.delete()) { Log.w(K9.LOG_TAG, "cannot delete " + fromDir.getAbsolutePath() + " after migration to/from SD-card"); } } private boolean move(File from, File to) { if (to.exists()) { to.delete(); } to.getParentFile().mkdirs(); try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024]; int count = -1; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); in.close(); from.delete(); return true; } catch (Exception e) { Log.w(K9.LOG_TAG, "cannot move " + from.getAbsolutePath() + " to " + to.getAbsolutePath(), e); return false; } } /** * * @param application * @throws UnavailableStorageException */ void openOrCreateDataspace(final Application application) throws UnavailableStorageException { lockWrite(); try { final File databaseFile = prepareStorage(mStorageProviderId); try { mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); } catch (SQLiteException e) { // try to gracefully handle DB corruption - see issue 2537 Log.w(K9.LOG_TAG, "Unable to open DB " + databaseFile + " - removing file and retrying", e); databaseFile.delete(); mDb = SQLiteDatabase.openOrCreateDatabase(databaseFile, null); } if (mDb.getVersion() != DB_VERSION) { doDbUpgrade(mDb, application); } } finally { unlockWrite(); } } /** * @param providerId * Never <code>null</code>. * @return DB file. * @throws UnavailableStorageException */ protected File prepareStorage(final String providerId) throws UnavailableStorageException { final StorageManager storageManager = StorageManager.getInstance(mApplication); final File databaseFile; final File databaseParentDir; databaseFile = storageManager.getDatabase(uUid, providerId); databaseParentDir = databaseFile.getParentFile(); if (databaseParentDir.isFile()) { // should be safe to inconditionally delete clashing file: user is not supposed to mess with our directory databaseParentDir.delete(); } if (!databaseParentDir.exists()) { if (!databaseParentDir.mkdirs()) { // Android seems to be unmounting the storage... throw new UnavailableStorageException("Unable to access: " + databaseParentDir); } touchFile(databaseParentDir, ".nomedia"); } final File attachmentDir; final File attachmentParentDir; attachmentDir = storageManager .getAttachmentDirectory(uUid, providerId); attachmentParentDir = attachmentDir.getParentFile(); if (!attachmentParentDir.exists()) { attachmentParentDir.mkdirs(); touchFile(attachmentParentDir, ".nomedia"); } if (!attachmentDir.exists()) { attachmentDir.mkdirs(); } return databaseFile; } /** * @param parentDir * @param name * Never <code>null</code>. */ protected void touchFile(final File parentDir, String name) { final File file = new File(parentDir, name); try { if (!file.exists()) { file.createNewFile(); } else { file.setLastModified(System.currentTimeMillis()); } } catch (Exception e) { Log.d(K9.LOG_TAG, "Unable to touch file: " + file.getAbsolutePath(), e); } } private void doDbUpgrade(final SQLiteDatabase db, final Application application) { Log.i(K9.LOG_TAG, String.format("Upgrading database from version %d to version %d", db.getVersion(), DB_VERSION)); AttachmentProvider.clear(application); try { // schema version 29 was when we moved to incremental updates // in the case of a new db or a < v29 db, we blow away and start from scratch if (db.getVersion() < 29) { db.execSQL("DROP TABLE IF EXISTS folders"); db.execSQL("CREATE TABLE folders (id INTEGER PRIMARY KEY, name TEXT, " + "last_updated INTEGER, unread_count INTEGER, visible_limit INTEGER, status TEXT, push_state TEXT, last_pushed INTEGER, flagged_count INTEGER default 0)"); db.execSQL("CREATE INDEX IF NOT EXISTS folder_name ON folders (name)"); db.execSQL("DROP TABLE IF EXISTS messages"); db.execSQL("CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted INTEGER default 0, folder_id INTEGER, uid TEXT, subject TEXT, " + "date INTEGER, flags TEXT, sender_list TEXT, to_list TEXT, cc_list TEXT, bcc_list TEXT, reply_to_list TEXT, " + "html_content TEXT, text_content TEXT, attachment_count INTEGER, internal_date INTEGER, message_id TEXT, preview TEXT)"); db.execSQL("DROP TABLE IF EXISTS headers"); db.execSQL("CREATE TABLE headers (id INTEGER PRIMARY KEY, message_id INTEGER, name TEXT, value TEXT)"); db.execSQL("CREATE INDEX IF NOT EXISTS header_folder ON headers (message_id)"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_uid ON messages (uid, folder_id)"); db.execSQL("DROP INDEX IF EXISTS msg_folder_id"); db.execSQL("DROP INDEX IF EXISTS msg_folder_id_date"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)"); db.execSQL("DROP TABLE IF EXISTS attachments"); db.execSQL("CREATE TABLE attachments (id INTEGER PRIMARY KEY, message_id INTEGER," + "store_data TEXT, content_uri TEXT, size INTEGER, name TEXT," + "mime_type TEXT, content_id TEXT, content_disposition TEXT)"); db.execSQL("DROP TABLE IF EXISTS pending_commands"); db.execSQL("CREATE TABLE pending_commands " + "(id INTEGER PRIMARY KEY, command TEXT, arguments TEXT)"); db.execSQL("DROP TRIGGER IF EXISTS delete_folder"); db.execSQL("CREATE TRIGGER delete_folder BEFORE DELETE ON folders BEGIN DELETE FROM messages WHERE old.id = folder_id; END;"); db.execSQL("DROP TRIGGER IF EXISTS delete_message"); db.execSQL("CREATE TRIGGER delete_message BEFORE DELETE ON messages BEGIN DELETE FROM attachments WHERE old.id = message_id; " + "DELETE FROM headers where old.id = message_id; END;"); } else { // in the case that we're starting out at 29 or newer, run all the needed updates if (db.getVersion() < 30) { try { db.execSQL("ALTER TABLE messages ADD deleted INTEGER default 0"); } catch (SQLiteException e) { if (! e.toString().startsWith("duplicate column name: deleted")) { throw e; } } } if (db.getVersion() < 31) { db.execSQL("DROP INDEX IF EXISTS msg_folder_id_date"); db.execSQL("CREATE INDEX IF NOT EXISTS msg_folder_id_deleted_date ON messages (folder_id,deleted,internal_date)"); } if (db.getVersion() < 32) { db.execSQL("UPDATE messages SET deleted = 1 WHERE flags LIKE '%DELETED%'"); } if (db.getVersion() < 33) { try { db.execSQL("ALTER TABLE messages ADD preview TEXT"); } catch (SQLiteException e) { if (! e.toString().startsWith("duplicate column name: preview")) { throw e; } } } if (db.getVersion() < 34) { try { db.execSQL("ALTER TABLE folders ADD flagged_count INTEGER default 0"); } catch (SQLiteException e) { if (! e.getMessage().startsWith("duplicate column name: flagged_count")) { throw e; } } } if (db.getVersion() < 35) { try { db.execSQL("update messages set flags = replace(flags, 'X_NO_SEEN_INFO', 'X_BAD_FLAG')"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to get rid of obsolete flag X_NO_SEEN_INFO", e); } } if (db.getVersion() < 36) { try { db.execSQL("ALTER TABLE attachments ADD content_id TEXT"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_id column to attachments"); } } if (db.getVersion() < 37) { try { db.execSQL("ALTER TABLE attachments ADD content_disposition TEXT"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to add content_disposition column to attachments"); } } // Database version 38 is solely to prune cached attachments now that we clear them better if (db.getVersion() < 39) { try { db.execSQL("DELETE FROM headers WHERE id in (SELECT headers.id FROM headers LEFT JOIN messages ON headers.message_id = messages.id WHERE messages.id IS NULL)"); } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Unable to remove extra header data from the database"); } } } } catch (SQLiteException e) { Log.e(K9.LOG_TAG, "Exception while upgrading database. Resetting the DB to v0"); db.setVersion(0); throw new Error("Database upgrade failed! Resetting your DB version to 0 to force a full schema recreation."); } db.setVersion(DB_VERSION); if (db.getVersion() != DB_VERSION) { throw new Error("Database upgrade failed!"); } try { pruneCachedAttachments(true); } catch (Exception me) { Log.e(K9.LOG_TAG, "Exception while force pruning attachments during DB update", me); } } public long getSize() throws UnavailableStorageException { final StorageManager storageManager = StorageManager.getInstance(mApplication); final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); return execute(false, new DbCallback<Long>() { @Override public Long doDbWork(final SQLiteDatabase db) { final File[] files = attachmentDirectory.listFiles(); long attachmentLength = 0; for (File file : files) { if (file.exists()) { attachmentLength += file.length(); } } final File dbFile = storageManager.getDatabase(uUid, mStorageProviderId); return dbFile.length() + attachmentLength; } }); } public void compact() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); pruneCachedAttachments(); if (K9.DEBUG) Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("VACUUM"); return null; } }); if (K9.DEBUG) Log.i(K9.LOG_TAG, "After compaction size = " + getSize()); } public void clear() throws MessagingException { if (K9.DEBUG) Log.i(K9.LOG_TAG, "Before prune size = " + getSize()); pruneCachedAttachments(true); if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After prune / before compaction size = " + getSize()); Log.i(K9.LOG_TAG, "Before clear folder count = " + getFolderCount()); Log.i(K9.LOG_TAG, "Before clear message count = " + getMessageCount()); Log.i(K9.LOG_TAG, "After prune / before clear size = " + getSize()); } // don't delete messages that are Local, since there is no copy on the server. // Don't delete deleted messages. They are essentially placeholders for UIDs of messages that have // been deleted locally. They take up insignificant space execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) { db.execSQL("DELETE FROM messages WHERE deleted = 0 and uid not like 'Local%'"); db.execSQL("update folders set flagged_count = 0, unread_count = 0"); return null; } }); compact(); if (K9.DEBUG) { Log.i(K9.LOG_TAG, "After clear message count = " + getMessageCount()); Log.i(K9.LOG_TAG, "After clear size = " + getSize()); } } public int getMessageCount() throws MessagingException { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages", null); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } public int getFolderCount() throws MessagingException { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) { Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM folders", null); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } @Override public LocalFolder getFolder(String name) throws MessagingException { return new LocalFolder(name); } // TODO this takes about 260-300ms, seems slow. @Override public List<? extends Folder> getPersonalNamespaces(boolean forceListAll) throws MessagingException { final List<LocalFolder> folders = new LinkedList<LocalFolder>(); try { execute(false, new DbCallback<List<? extends Folder>>() { @Override public List<? extends Folder> doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.rawQuery("SELECT id, name, unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders ORDER BY name ASC", null); while (cursor.moveToNext()) { LocalFolder folder = new LocalFolder(cursor.getString(1)); folder.open(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8)); folders.add(folder); } return folders; } catch (MessagingException e) { throw new WrappedException(e); } finally { if (cursor != null) { cursor.close(); } } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } return folders; } @Override public void checkSettings() throws MessagingException { } /** * Delete the entire Store and it's backing database. * @throws UnavailableStorageException */ public void delete() throws UnavailableStorageException { lockWrite(); try { try { mDb.close(); } catch (Exception e) { } final StorageManager storageManager = StorageManager.getInstance(mApplication); try { final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); final File[] attachments = attachmentDirectory.listFiles(); for (File attachment : attachments) { if (attachment.exists()) { attachment.delete(); } } if (attachmentDirectory.exists()) { attachmentDirectory.delete(); } } catch (Exception e) { } try { storageManager.getDatabase(uUid, mStorageProviderId).delete(); } catch (Exception e) { Log.i(K9.LOG_TAG, "LocalStore: delete(): Unable to delete backing DB file", e); } // stop waiting for mount/unmount events StorageManager.getInstance(mApplication).removeListener(mStorageListener); } finally { unlockWrite(); } } public void recreate() throws UnavailableStorageException { lockWrite(); try { try { mDb.close(); } catch (Exception e) { } final StorageManager storageManager = StorageManager.getInstance(mApplication); try { final File attachmentDirectory = storageManager.getAttachmentDirectory(uUid, mStorageProviderId); final File[] attachments = attachmentDirectory.listFiles(); for (File attachment : attachments) { if (attachment.exists()) { attachment.delete(); } } if (attachmentDirectory.exists()) { attachmentDirectory.delete(); } } catch (Exception e) { } try { storageManager.getDatabase(uUid, mStorageProviderId).delete(); } catch (Exception e) { } openOrCreateDataspace(mApplication); } finally { unlockWrite(); } } public void pruneCachedAttachments() throws MessagingException { pruneCachedAttachments(false); } /** * Deletes all cached attachments for the entire store. */ public void pruneCachedAttachments(final boolean force) throws MessagingException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { if (force) { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, null, null); } final StorageManager storageManager = StorageManager.getInstance(mApplication); File[] files = storageManager.getAttachmentDirectory(uUid, mStorageProviderId).listFiles(); for (File file : files) { if (file.exists()) { if (!force) { Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "store_data" }, "id = ?", new String[] { file.getName() }, null, null, null); if (cursor.moveToNext()) { if (cursor.getString(0) == null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Attachment " + file.getAbsolutePath() + " has no store data, not deleting"); /* * If the attachment has no store data it is not recoverable, so * we won't delete it. */ continue; } } } finally { if (cursor != null) { cursor.close(); } } } if (!force) { try { ContentValues cv = new ContentValues(); cv.putNull("content_uri"); db.update("attachments", cv, "id = ?", new String[] { file.getName() }); } catch (Exception e) { /* * If the row has gone away before we got to mark it not-downloaded that's * okay. */ } } if (!file.delete()) { file.deleteOnExit(); } } } return null; } }); } public void resetVisibleLimits() throws UnavailableStorageException { resetVisibleLimits(mAccount.getDisplayCount()); } public void resetVisibleLimits(int visibleLimit) throws UnavailableStorageException { final ContentValues cv = new ContentValues(); cv.put("visible_limit", Integer.toString(visibleLimit)); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.update("folders", cv, null, null); return null; } }); } public ArrayList<PendingCommand> getPendingCommands() throws UnavailableStorageException { return execute(false, new DbCallback<ArrayList<PendingCommand>>() { @Override public ArrayList<PendingCommand> doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.query("pending_commands", new String[] { "id", "command", "arguments" }, null, null, null, null, "id ASC"); ArrayList<PendingCommand> commands = new ArrayList<PendingCommand>(); while (cursor.moveToNext()) { PendingCommand command = new PendingCommand(); command.mId = cursor.getLong(0); command.command = cursor.getString(1); String arguments = cursor.getString(2); command.arguments = arguments.split(","); for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = Utility.fastUrlDecode(command.arguments[i]); } commands.add(command); } return commands; } finally { if (cursor != null) { cursor.close(); } } } }); } public void addPendingCommand(PendingCommand command) throws UnavailableStorageException { try { for (int i = 0; i < command.arguments.length; i++) { command.arguments[i] = URLEncoder.encode(command.arguments[i], "UTF-8"); } final ContentValues cv = new ContentValues(); cv.put("command", command.command); cv.put("arguments", Utility.combine(command.arguments, ',')); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.insert("pending_commands", "command", cv); return null; } }); } catch (UnsupportedEncodingException usee) { throw new Error("Aparently UTF-8 has been lost to the annals of history."); } } public void removePendingCommand(final PendingCommand command) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", "id = ?", new String[] { Long.toString(command.mId) }); return null; } }); } public void removePendingCommands() throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.delete("pending_commands", null, null); return null; } }); } /** * Open the DB on mount and close the DB on unmount */ private class StorageListener implements StorageManager.StorageListener { @Override public void onUnmount(final String providerId) { if (!providerId.equals(mStorageProviderId)) { return; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LocalStore: Closing DB " + uUid + " due to unmount event on StorageProvider: " + providerId); } try { lockWrite(); try { mDb.close(); } finally { unlockWrite(); } } catch (UnavailableStorageException e) { Log.w(K9.LOG_TAG, "Unable to writelock on unmount", e); } } @Override public void onMount(String providerId) { if (!providerId.equals(mStorageProviderId)) { return; } if (K9.DEBUG) { Log.d(K9.LOG_TAG, "LocalStore: Opening DB " + uUid + " due to mount event on StorageProvider: " + providerId); } try { openOrCreateDataspace(mApplication); } catch (UnavailableStorageException e) { Log.e(K9.LOG_TAG, "Unable to open DB on mount", e); } } } public static class PendingCommand { private long mId; public String command; public String[] arguments; @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(command); sb.append(": "); for (String argument : arguments) { sb.append(", "); sb.append(argument); //sb.append("\n"); } return sb.toString(); } } @Override public boolean isMoveCapable() { return true; } @Override public boolean isCopyCapable() { return true; } public Message[] searchForMessages(MessageRetrievalListener listener, String[] queryFields, String queryString, List<LocalFolder> folders, Message[] messages, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException { List<String> args = new LinkedList<String>(); StringBuilder whereClause = new StringBuilder(); if (queryString != null && queryString.length() > 0) { boolean anyAdded = false; String likeString = "%"+queryString+"%"; whereClause.append(" AND ("); for (String queryField : queryFields) { if (anyAdded) { whereClause.append(" OR "); } whereClause.append(queryField + " LIKE ? "); args.add(likeString); anyAdded = true; } whereClause.append(" )"); } if (folders != null && folders.size() > 0) { whereClause.append(" AND folder_id in ("); boolean anyAdded = false; for (LocalFolder folder : folders) { if (anyAdded) { whereClause.append(","); } anyAdded = true; whereClause.append("?"); args.add(Long.toString(folder.getId())); } whereClause.append(" )"); } if (messages != null && messages.length > 0) { whereClause.append(" AND ( "); boolean anyAdded = false; for (Message message : messages) { if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; whereClause.append(" ( uid = ? AND folder_id = ? ) "); args.add(message.getUid()); args.add(Long.toString(((LocalFolder)message.getFolder()).getId())); } whereClause.append(" )"); } if (forbiddenFlags != null && forbiddenFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; for (Flag flag : forbiddenFlags) { if (anyAdded) { whereClause.append(" AND "); } anyAdded = true; whereClause.append(" flags NOT LIKE ?"); args.add("%" + flag.toString() + "%"); } whereClause.append(" )"); } if (requiredFlags != null && requiredFlags.length > 0) { whereClause.append(" AND ("); boolean anyAdded = false; for (Flag flag : requiredFlags) { if (anyAdded) { whereClause.append(" OR "); } anyAdded = true; whereClause.append(" flags LIKE ?"); args.add("%" + flag.toString() + "%"); } whereClause.append(" )"); } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "whereClause = " + whereClause.toString()); Log.v(K9.LOG_TAG, "args = " + args); } return getMessages( listener, null, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE deleted = 0 " + whereClause.toString() + " ORDER BY date DESC" , args.toArray(EMPTY_STRING_ARRAY) ); } /* * Given a query string, actually do the query for the messages and * call the MessageRetrievalListener for each one */ private Message[] getMessages( final MessageRetrievalListener listener, final LocalFolder folder, final String queryString, final String[] placeHolders ) throws MessagingException { final ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>(); final int j = execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; int i = 0; try { cursor = db.rawQuery(queryString + " LIMIT 10", placeHolders); while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); if (listener != null) { listener.messageFinished(message, i, -1); } i++; } cursor.close(); cursor = db.rawQuery(queryString + " LIMIT -1 OFFSET 10", placeHolders); while (cursor.moveToNext()) { LocalMessage message = new LocalMessage(null, folder); message.populateFromGetMessageCursor(cursor); messages.add(message); if (listener != null) { listener.messageFinished(message, i, -1); } i++; } } catch (Exception e) { Log.d(K9.LOG_TAG,"Got an exception "+e); } finally { if (cursor != null) { cursor.close(); } } return i; } }); if (listener != null) { listener.messagesFinished(j); } return messages.toArray(EMPTY_MESSAGE_ARRAY); } public String getAttachmentType(final String attachmentId) throws UnavailableStorageException { return execute(false, new DbCallback<String>() { @Override public String doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "mime_type", "name" }, "id = ?", new String[] { attachmentId }, null, null, null); cursor.moveToFirst(); String type = cursor.getString(0); String name = cursor.getString(1); cursor.close(); if (MimeUtility.DEFAULT_ATTACHMENT_MIME_TYPE.equals(type)) { type = MimeUtility.getMimeTypeByExtension(name); } return type; } finally { if (cursor != null) { cursor.close(); } } } }); } public AttachmentInfo getAttachmentInfo(final String attachmentId) throws UnavailableStorageException { return execute(false, new DbCallback<AttachmentInfo>() { @Override public AttachmentInfo doDbWork(final SQLiteDatabase db) throws WrappedException { String name = null; int size = -1; Cursor cursor = null; try { cursor = db.query( "attachments", new String[] { "name", "size" }, "id = ?", new String[] { attachmentId }, null, null, null); if (!cursor.moveToFirst()) { return null; } name = cursor.getString(0); size = cursor.getInt(1); final AttachmentInfo attachmentInfo = new AttachmentInfo(); attachmentInfo.name = name; attachmentInfo.size = size; return attachmentInfo; } finally { if (cursor != null) { cursor.close(); } } } }); } public static class AttachmentInfo { public String name; public int size; } public class LocalFolder extends Folder implements Serializable { private String mName = null; private long mFolderId = -1; private int mUnreadMessageCount = -1; private int mFlaggedMessageCount = -1; private int mVisibleLimit = -1; private FolderClass displayClass = FolderClass.NO_CLASS; private FolderClass syncClass = FolderClass.INHERITED; private FolderClass pushClass = FolderClass.SECOND_CLASS; private boolean inTopGroup = false; private String prefId = null; private String mPushState = null; private boolean mIntegrate = false; public LocalFolder(String name) { super(LocalStore.this.mAccount); this.mName = name; if (K9.INBOX.equals(getName())) { syncClass = FolderClass.FIRST_CLASS; pushClass = FolderClass.FIRST_CLASS; inTopGroup = true; } } public LocalFolder(long id) { super(LocalStore.this.mAccount); this.mFolderId = id; } public long getId() { return mFolderId; } @Override public void open(final OpenMode mode) throws MessagingException { if (isOpen()) { return; } try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { String baseQuery = "SELECT id, name,unread_count, visible_limit, last_updated, status, push_state, last_pushed, flagged_count FROM folders "; if (mName != null) { cursor = db.rawQuery(baseQuery + "where folders.name = ?", new String[] { mName }); } else { cursor = db.rawQuery(baseQuery + "where folders.id = ?", new String[] { Long.toString(mFolderId) }); } if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); if (folderId > 0) { open(folderId, cursor.getString(1), cursor.getInt(2), cursor.getInt(3), cursor.getLong(4), cursor.getString(5), cursor.getString(6), cursor.getLong(7), cursor.getInt(8)); } } else { Log.w(K9.LOG_TAG, "Creating folder " + getName() + " with existing id " + getId()); create(FolderType.HOLDS_MESSAGES); open(mode); } } catch (MessagingException e) { throw new WrappedException(e); } finally { if (cursor != null) { cursor.close(); } } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } private void open(int id, String name, int unreadCount, int visibleLimit, long lastChecked, String status, String pushState, long lastPushed, int flaggedCount) throws MessagingException { mFolderId = id; mName = name; mUnreadMessageCount = unreadCount; mVisibleLimit = visibleLimit; mPushState = pushState; mFlaggedMessageCount = flaggedCount; super.setStatus(status); // Only want to set the local variable stored in the super class. This class // does a DB update on setLastChecked super.setLastChecked(lastChecked); super.setLastPush(lastPushed); } @Override public boolean isOpen() { return (mFolderId != -1 && mName != null); } @Override public OpenMode getMode() throws MessagingException { return OpenMode.READ_WRITE; } @Override public String getName() { return mName; } @Override public boolean exists() throws MessagingException { return execute(false, new DbCallback<Boolean>() { @Override public Boolean doDbWork(final SQLiteDatabase db) throws WrappedException { Cursor cursor = null; try { cursor = db.rawQuery("SELECT id FROM folders " + "where folders.name = ?", new String[] { LocalFolder.this .getName() }); if (cursor.moveToFirst()) { int folderId = cursor.getInt(0); return (folderId > 0); } else { return false; } } finally { if (cursor != null) { cursor.close(); } } } }); } @Override public boolean create(FolderType type) throws MessagingException { if (exists()) { throw new MessagingException("Folder " + mName + " already exists."); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] { mName, mAccount.getDisplayCount() }); return null; } }); return true; } @Override public boolean create(FolderType type, final int visibleLimit) throws MessagingException { if (exists()) { throw new MessagingException("Folder " + mName + " already exists."); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { db.execSQL("INSERT INTO folders (name, visible_limit) VALUES (?, ?)", new Object[] { mName, visibleLimit }); return null; } }); return true; } @Override public void close() { mFolderId = -1; } @Override public int getMessageCount() throws MessagingException { try { return execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } Cursor cursor = null; try { cursor = db.rawQuery("SELECT COUNT(*) FROM messages WHERE messages.folder_id = ?", new String[] { Long.toString(mFolderId) }); cursor.moveToFirst(); int messageCount = cursor.getInt(0); return messageCount; } finally { if (cursor != null) { cursor.close(); } } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mUnreadMessageCount; } @Override public int getFlaggedMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); return mFlaggedMessageCount; } public void setUnreadMessageCount(final int unreadMessageCount) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mUnreadMessageCount = Math.max(0, unreadMessageCount); db.execSQL("UPDATE folders SET unread_count = ? WHERE id = ?", new Object[] { mUnreadMessageCount, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public void setFlaggedMessageCount(final int flaggedMessageCount) throws MessagingException { try { execute(false, new DbCallback<Integer>() { @Override public Integer doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mFlaggedMessageCount = Math.max(0, flaggedMessageCount); db.execSQL("UPDATE folders SET flagged_count = ? WHERE id = ?", new Object[] { mFlaggedMessageCount, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public void setLastChecked(final long lastChecked) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastChecked(lastChecked); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET last_updated = ? WHERE id = ?", new Object[] { lastChecked, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public void setLastPush(final long lastChecked) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setLastPush(lastChecked); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET last_pushed = ? WHERE id = ?", new Object[] { lastChecked, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public int getVisibleLimit() throws MessagingException { open(OpenMode.READ_WRITE); return mVisibleLimit; } public void purgeToVisibleLimit(MessageRemovalListener listener) throws MessagingException { if ( mVisibleLimit == 0) { return ; } open(OpenMode.READ_WRITE); Message[] messages = getMessages(null, false); for (int i = mVisibleLimit; i < messages.length; i++) { if (listener != null) { listener.messageRemoved(messages[i]); } messages[i].destroy(); } } public void setVisibleLimit(final int visibleLimit) throws MessagingException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mVisibleLimit = visibleLimit; db.execSQL("UPDATE folders SET visible_limit = ? WHERE id = ?", new Object[] { mVisibleLimit, mFolderId }); return null; } }); } @Override public void setStatus(final String status) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); LocalFolder.super.setStatus(status); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("UPDATE folders SET status = ? WHERE id = ?", new Object[] { status, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public void setPushState(final String pushState) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); } catch (MessagingException e) { throw new WrappedException(e); } mPushState = pushState; db.execSQL("UPDATE folders SET push_state = ? WHERE id = ?", new Object[] { pushState, mFolderId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } public String getPushState() { return mPushState; } @Override public FolderClass getDisplayClass() { return displayClass; } @Override public FolderClass getSyncClass() { if (FolderClass.INHERITED == syncClass) { return getDisplayClass(); } else { return syncClass; } } public FolderClass getRawSyncClass() { return syncClass; } @Override public FolderClass getPushClass() { if (FolderClass.INHERITED == pushClass) { return getSyncClass(); } else { return pushClass; } } public FolderClass getRawPushClass() { return pushClass; } public void setDisplayClass(FolderClass displayClass) { this.displayClass = displayClass; } public void setSyncClass(FolderClass syncClass) { this.syncClass = syncClass; } public void setPushClass(FolderClass pushClass) { this.pushClass = pushClass; } public boolean isIntegrate() { return mIntegrate; } public void setIntegrate(boolean integrate) { mIntegrate = integrate; } private String getPrefId() throws MessagingException { open(OpenMode.READ_WRITE); if (prefId == null) { prefId = uUid + "." + mName; } return prefId; } public void delete(Preferences preferences) throws MessagingException { String id = getPrefId(); SharedPreferences.Editor editor = preferences.getPreferences().edit(); editor.remove(id + ".displayMode"); editor.remove(id + ".syncMode"); editor.remove(id + ".pushMode"); editor.remove(id + ".inTopGroup"); editor.remove(id + ".integrate"); editor.commit(); } public void save(Preferences preferences) throws MessagingException { String id = getPrefId(); SharedPreferences.Editor editor = preferences.getPreferences().edit(); // there can be a lot of folders. For the defaults, let's not save prefs, saving space, except for INBOX if (displayClass == FolderClass.NO_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".displayMode"); } else { editor.putString(id + ".displayMode", displayClass.name()); } if (syncClass == FolderClass.INHERITED && !K9.INBOX.equals(getName())) { editor.remove(id + ".syncMode"); } else { editor.putString(id + ".syncMode", syncClass.name()); } if (pushClass == FolderClass.SECOND_CLASS && !K9.INBOX.equals(getName())) { editor.remove(id + ".pushMode"); } else { editor.putString(id + ".pushMode", pushClass.name()); } editor.putBoolean(id + ".inTopGroup", inTopGroup); editor.putBoolean(id + ".integrate", mIntegrate); editor.commit(); } public FolderClass getDisplayClass(Preferences preferences) throws MessagingException { String id = getPrefId(); return FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode", FolderClass.NO_CLASS.name())); } @Override public void refresh(Preferences preferences) throws MessagingException { String id = getPrefId(); try { displayClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".displayMode", FolderClass.NO_CLASS.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load displayMode for " + getName(), e); displayClass = FolderClass.NO_CLASS; } if (displayClass == FolderClass.NONE) { displayClass = FolderClass.NO_CLASS; } FolderClass defSyncClass = FolderClass.INHERITED; if (K9.INBOX.equals(getName())) { defSyncClass = FolderClass.FIRST_CLASS; } try { syncClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".syncMode", defSyncClass.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load syncMode for " + getName(), e); syncClass = defSyncClass; } if (syncClass == FolderClass.NONE) { syncClass = FolderClass.INHERITED; } FolderClass defPushClass = FolderClass.SECOND_CLASS; boolean defInTopGroup = false; boolean defIntegrate = false; if (K9.INBOX.equals(getName())) { defPushClass = FolderClass.FIRST_CLASS; defInTopGroup = true; defIntegrate = true; } try { pushClass = FolderClass.valueOf(preferences.getPreferences().getString(id + ".pushMode", defPushClass.name())); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to load pushMode for " + getName(), e); pushClass = defPushClass; } if (pushClass == FolderClass.NONE) { pushClass = FolderClass.INHERITED; } inTopGroup = preferences.getPreferences().getBoolean(id + ".inTopGroup", defInTopGroup); mIntegrate = preferences.getPreferences().getBoolean(id + ".integrate", defIntegrate); } @Override public void fetch(final Message[] messages, final FetchProfile fp, final MessageRetrievalListener listener) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException { try { open(OpenMode.READ_WRITE); if (fp.contains(FetchProfile.Item.BODY)) { for (Message message : messages) { LocalMessage localMessage = (LocalMessage)message; Cursor cursor = null; MimeMultipart mp = new MimeMultipart(); mp.setSubType("mixed"); try { cursor = db.rawQuery("SELECT html_content, text_content FROM messages " + "WHERE id = ?", new String[] { Long.toString(localMessage.mId) }); cursor.moveToNext(); String htmlContent = cursor.getString(0); String textContent = cursor.getString(1); if (textContent != null) { LocalTextBody body = new LocalTextBody(textContent, htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/plain"); mp.addBodyPart(bp); } else { TextBody body = new TextBody(htmlContent); MimeBodyPart bp = new MimeBodyPart(body, "text/html"); mp.addBodyPart(bp); } } finally { if (cursor != null) { cursor.close(); } } try { cursor = db.query( "attachments", new String[] { "id", "size", "name", "mime_type", "store_data", "content_uri", "content_id", "content_disposition" }, "message_id = ?", new String[] { Long.toString(localMessage.mId) }, null, null, null); while (cursor.moveToNext()) { long id = cursor.getLong(0); int size = cursor.getInt(1); String name = cursor.getString(2); String type = cursor.getString(3); String storeData = cursor.getString(4); String contentUri = cursor.getString(5); String contentId = cursor.getString(6); String contentDisposition = cursor.getString(7); Body body = null; if (contentDisposition == null) { contentDisposition = "attachment"; } if (contentUri != null) { body = new LocalAttachmentBody(Uri.parse(contentUri), mApplication); } MimeBodyPart bp = new LocalAttachmentBodyPart(body, id); bp.setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"", type, name)); bp.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); bp.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format("%s;\n filename=\"%s\";\n size=%d", contentDisposition, name, size)); bp.setHeader(MimeHeader.HEADER_CONTENT_ID, contentId); /* * HEADER_ANDROID_ATTACHMENT_STORE_DATA is a custom header we add to that * we can later pull the attachment from the remote store if neccesary. */ bp.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, storeData); mp.addBodyPart(bp); } } finally { if (cursor != null) { cursor.close(); } } if (mp.getCount() == 1) { BodyPart part = mp.getBodyPart(0); localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, part.getContentType()); localMessage.setBody(part.getBody()); } else { localMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed"); localMessage.setBody(mp); } } } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) throws MessagingException { open(OpenMode.READ_WRITE); throw new MessagingException( "LocalStore.getMessages(int, int, MessageRetrievalListener) not yet implemented"); } /** * Populate the header fields of the given list of messages by reading * the saved header data from the database. * * @param messages * The messages whose headers should be loaded. * @throws UnavailableStorageException */ private void populateHeaders(final List<LocalMessage> messages) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor cursor = null; if (messages.size() == 0) { return null; } try { Map<Long, LocalMessage> popMessages = new HashMap<Long, LocalMessage>(); List<String> ids = new ArrayList<String>(); StringBuffer questions = new StringBuffer(); for (int i = 0; i < messages.size(); i++) { if (i != 0) { questions.append(", "); } questions.append("?"); LocalMessage message = messages.get(i); Long id = message.getId(); ids.add(Long.toString(id)); popMessages.put(id, message); } cursor = db.rawQuery( "SELECT message_id, name, value FROM headers " + "WHERE message_id in ( " + questions + ") ", ids.toArray(EMPTY_STRING_ARRAY)); while (cursor.moveToNext()) { Long id = cursor.getLong(0); String name = cursor.getString(1); String value = cursor.getString(2); //Log.i(K9.LOG_TAG, "Retrieved header name= " + name + ", value = " + value + " for message " + id); popMessages.get(id).addHeader(name, value); } } finally { if (cursor != null) { cursor.close(); } } return null; } }); } @Override public Message getMessage(final String uid) throws MessagingException { try { return execute(false, new DbCallback<Message>() { @Override public Message doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { open(OpenMode.READ_WRITE); LocalMessage message = new LocalMessage(uid, LocalFolder.this); Cursor cursor = null; try { cursor = db.rawQuery( "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE uid = ? AND folder_id = ?", new String[] { message.getUid(), Long.toString(mFolderId) }); if (!cursor.moveToNext()) { return null; } message.populateFromGetMessageCursor(cursor); } finally { if (cursor != null) { cursor.close(); } } return message; } catch (MessagingException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(listener, true); } @Override public Message[] getMessages(final MessageRetrievalListener listener, final boolean includeDeleted) throws MessagingException { try { return execute(false, new DbCallback<Message[]>() { @Override public Message[] doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { open(OpenMode.READ_WRITE); return LocalStore.this.getMessages( listener, LocalFolder.this, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE " + (includeDeleted ? "" : "deleted = 0 AND ") + " folder_id = ? ORDER BY date DESC" , new String[] { Long.toString(mFolderId) } ); } catch (MessagingException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { open(OpenMode.READ_WRITE); if (uids == null) { return getMessages(listener); } ArrayList<Message> messages = new ArrayList<Message>(); for (String uid : uids) { Message message = getMessage(uid); if (message != null) { messages.add(message); } } return messages.toArray(EMPTY_MESSAGE_ARRAY); } @Override public void copyMessages(Message[] msgs, Folder folder) throws MessagingException { if (!(folder instanceof LocalFolder)) { throw new MessagingException("copyMessages called with incorrect Folder"); } ((LocalFolder) folder).appendMessages(msgs, true); } @Override public void moveMessages(final Message[] msgs, final Folder destFolder) throws MessagingException { if (!(destFolder instanceof LocalFolder)) { throw new MessagingException("moveMessages called with non-LocalFolder"); } final LocalFolder lDestFolder = (LocalFolder)destFolder; try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { lDestFolder.open(OpenMode.READ_WRITE); for (Message message : msgs) { LocalMessage lMessage = (LocalMessage)message; if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); lDestFolder.setUnreadMessageCount(lDestFolder.getUnreadMessageCount() + 1); } if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); lDestFolder.setFlaggedMessageCount(lDestFolder.getFlaggedMessageCount() + 1); } String oldUID = message.getUid(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Updating folder_id to " + lDestFolder.getId() + " for message with UID " + message.getUid() + ", id " + lMessage.getId() + " currently in folder " + getName()); message.setUid(K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString()); db.execSQL("UPDATE messages " + "SET folder_id = ?, uid = ? " + "WHERE id = ?", new Object[] { lDestFolder.getId(), message.getUid(), lMessage.getId() }); LocalMessage placeHolder = new LocalMessage(oldUID, LocalFolder.this); placeHolder.setFlagInternal(Flag.DELETED, true); placeHolder.setFlagInternal(Flag.SEEN, true); appendMessages(new Message[] { placeHolder }); } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * The method differs slightly from the contract; If an incoming message already has a uid * assigned and it matches the uid of an existing message then this message will replace the * old message. It is implemented as a delete/insert. This functionality is used in saving * of drafts and re-synchronization of updated server messages. * * NOTE that although this method is located in the LocalStore class, it is not guaranteed * that the messages supplied as parameters are actually {@link LocalMessage} instances (in * fact, in most cases, they are not). Therefore, if you want to make local changes only to a * message, retrieve the appropriate local message instance first (if it already exists). */ @Override public void appendMessages(Message[] messages) throws MessagingException { appendMessages(messages, false); } /** * The method differs slightly from the contract; If an incoming message already has a uid * assigned and it matches the uid of an existing message then this message will replace the * old message. It is implemented as a delete/insert. This functionality is used in saving * of drafts and re-synchronization of updated server messages. * * NOTE that although this method is located in the LocalStore class, it is not guaranteed * that the messages supplied as parameters are actually {@link LocalMessage} instances (in * fact, in most cases, they are not). Therefore, if you want to make local changes only to a * message, retrieve the appropriate local message instance first (if it already exists). */ private void appendMessages(final Message[] messages, final boolean copy) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { for (Message message : messages) { if (!(message instanceof MimeMessage)) { throw new Error("LocalStore can only store Messages that extend MimeMessage"); } String uid = message.getUid(); if (uid == null || copy) { uid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString(); if (!copy) { message.setUid(uid); } } else { Message oldMessage = getMessage(uid); if (oldMessage != null && !oldMessage.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() - 1); } if (oldMessage != null && oldMessage.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() - 1); } /* * The message may already exist in this Folder, so delete it first. */ deleteAttachments(message.getUid()); db.execSQL("DELETE FROM messages WHERE folder_id = ? AND uid = ?", new Object[] { mFolderId, message.getUid() }); } ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); for (Part viewable : viewables) { try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); } else { sbText.append(text); } } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } String text = sbText.toString(); String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); try { ContentValues cv = new ContentValues(); cv.put("uid", uid); cv.put("subject", message.getSubject()); cv.put("sender_list", Address.pack(message.getFrom())); cv.put("date", message.getSentDate() == null ? System.currentTimeMillis() : message.getSentDate().getTime()); cv.put("flags", Utility.combine(message.getFlags(), ',').toUpperCase()); cv.put("deleted", message.isSet(Flag.DELETED) ? 1 : 0); cv.put("folder_id", mFolderId); cv.put("to_list", Address.pack(message.getRecipients(RecipientType.TO))); cv.put("cc_list", Address.pack(message.getRecipients(RecipientType.CC))); cv.put("bcc_list", Address.pack(message.getRecipients(RecipientType.BCC))); cv.put("html_content", html.length() > 0 ? html : null); cv.put("text_content", text.length() > 0 ? text : null); cv.put("preview", preview.length() > 0 ? preview : null); cv.put("reply_to_list", Address.pack(message.getReplyTo())); cv.put("attachment_count", attachments.size()); cv.put("internal_date", message.getInternalDate() == null ? System.currentTimeMillis() : message.getInternalDate().getTime()); String messageId = message.getMessageId(); if (messageId != null) { cv.put("message_id", messageId); } long messageUid; messageUid = db.insert("messages", "uid", cv); for (Part attachment : attachments) { saveAttachment(messageUid, attachment, copy); } saveHeaders(messageUid, (MimeMessage)message); if (!message.isSet(Flag.SEEN)) { setUnreadMessageCount(getUnreadMessageCount() + 1); } if (message.isSet(Flag.FLAGGED)) { setFlaggedMessageCount(getFlaggedMessageCount() + 1); } } catch (Exception e) { throw new MessagingException("Error appending message", e); } } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * Update the given message in the LocalStore without first deleting the existing * message (contrast with appendMessages). This method is used to store changes * to the given message while updating attachments and not removing existing * attachment data. * TODO In the future this method should be combined with appendMessages since the Message * contains enough data to decide what to do. * @param message * @throws MessagingException */ public void updateMessage(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); message.buildMimeRepresentation(); MimeUtility.collectParts(message, viewables, attachments); StringBuffer sbHtml = new StringBuffer(); StringBuffer sbText = new StringBuffer(); for (int i = 0, count = viewables.size(); i < count; i++) { Part viewable = viewables.get(i); try { String text = MimeUtility.getTextFromPart(viewable); /* * Anything with MIME type text/html will be stored as such. Anything * else will be stored as text/plain. */ if (viewable.getMimeType().equalsIgnoreCase("text/html")) { sbHtml.append(text); } else { sbText.append(text); } } catch (Exception e) { throw new MessagingException("Unable to get text for message part", e); } } String text = sbText.toString(); String html = markupContent(text, sbHtml.toString()); String preview = calculateContentPreview(text); if (preview == null || preview.length() == 0) { preview = calculateContentPreview(Html.fromHtml(html).toString()); } try { db.execSQL("UPDATE messages SET " + "uid = ?, subject = ?, sender_list = ?, date = ?, flags = ?, " + "folder_id = ?, to_list = ?, cc_list = ?, bcc_list = ?, " + "html_content = ?, text_content = ?, preview = ?, reply_to_list = ?, " + "attachment_count = ? WHERE id = ?", new Object[] { message.getUid(), message.getSubject(), Address.pack(message.getFrom()), message.getSentDate() == null ? System .currentTimeMillis() : message.getSentDate() .getTime(), Utility.combine(message.getFlags(), ',').toUpperCase(), mFolderId, Address.pack(message .getRecipients(RecipientType.TO)), Address.pack(message .getRecipients(RecipientType.CC)), Address.pack(message .getRecipients(RecipientType.BCC)), html.length() > 0 ? html : null, text.length() > 0 ? text : null, preview.length() > 0 ? preview : null, Address.pack(message.getReplyTo()), attachments.size(), message.mId }); for (int i = 0, count = attachments.size(); i < count; i++) { Part attachment = attachments.get(i); saveAttachment(message.mId, attachment, false); } saveHeaders(message.getId(), message); } catch (Exception e) { throw new MessagingException("Error appending message", e); } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /** * Save the headers of the given message. Note that the message is not * necessarily a {@link LocalMessage} instance. */ private void saveHeaders(final long id, final MimeMessage message) throws MessagingException { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { boolean saveAllHeaders = mAccount.saveAllHeaders(); boolean gotAdditionalHeaders = false; deleteHeaders(id); for (String name : message.getHeaderNames()) { if (saveAllHeaders || HEADERS_TO_SAVE.contains(name)) { String[] values = message.getHeader(name); for (String value : values) { ContentValues cv = new ContentValues(); cv.put("message_id", id); cv.put("name", name); cv.put("value", value); db.insert("headers", "name", cv); } } else { gotAdditionalHeaders = true; } } if (!gotAdditionalHeaders) { // Remember that all headers for this message have been saved, so it is // not necessary to download them again in case the user wants to see all headers. List<Flag> appendedFlags = new ArrayList<Flag>(); appendedFlags.addAll(Arrays.asList(message.getFlags())); appendedFlags.add(Flag.X_GOT_ALL_HEADERS); db.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[] { Utility.combine(appendedFlags.toArray(), ',').toUpperCase(), id }); } return null; } }); } private void deleteHeaders(final long id) throws UnavailableStorageException { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM headers WHERE message_id = ?", new Object[] { id }); return null; } }); } /** * @param messageId * @param attachment * @param attachmentId -1 to create a new attachment or >= 0 to update an existing * @throws IOException * @throws MessagingException */ private void saveAttachment(final long messageId, final Part attachment, final boolean saveAsNew) throws IOException, MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } final File attachmentDirectory = StorageManager.getInstance(mApplication).getAttachmentDirectory(uUid, mStorageProviderId); if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { /* * If the attachment has a body we're expected to save it into the local store * so we copy the data into a cached attachment file. */ InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, attachmentDirectory); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { /* * If the attachment is not yet downloaded see if we can pull a size * off the Content-Disposition. */ String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader( MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = MimeUtility.getHeaderParameter(attachment.getContentId(), null); String contentDisposition = MimeUtility.unfoldAndDecode(attachment.getDisposition()); if (name == null && contentDisposition != null) { name = MimeUtility.getHeaderParameter(contentDisposition, "filename"); } if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); cv.put("content_disposition", contentDisposition); attachmentId = db.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); db.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachmentId != -1 && tempAttachmentFile != null) { File attachmentFile = new File(attachmentDirectory, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); contentUri = AttachmentProvider.getAttachmentUri( mAccount, attachmentId); attachment.setBody(new LocalAttachmentBody(contentUri, mApplication)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); db.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } /* The message has attachment with Content-ID */ if (contentId != null && contentUri != null) { Cursor cursor = null; cursor = db.query("messages", new String[] { "html_content" }, "id = ?", new String[] { Long.toString(messageId) }, null, null, null); try { if (cursor.moveToNext()) { String new_html; new_html = cursor.getString(0); new_html = new_html.replaceAll("cid:" + contentId, contentUri.toString()); ContentValues cv = new ContentValues(); cv.put("html_content", new_html); db.update("messages", cv, "id = ?", new String[] { Long.toString(messageId) }); } } finally { if (cursor != null) { cursor.close(); } } } if (attachmentId != -1 && attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } return null; } catch (MessagingException e) { throw new WrappedException(e); } catch (IOException e) { throw new WrappedException(e); } } }); } catch (WrappedException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw (MessagingException) cause; } } } /** * Changes the stored uid of the given message (using it's internal id as a key) to * the uid in the message. * @param message */ public void changeUid(final LocalMessage message) throws MessagingException { open(OpenMode.READ_WRITE); final ContentValues cv = new ContentValues(); cv.put("uid", message.getUid()); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.update("messages", cv, "id = ?", new String[] { Long.toString(message.mId) }); return null; } }); } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { open(OpenMode.READ_WRITE); for (Message message : messages) { message.setFlags(flags, value); } } @Override public void setFlags(Flag[] flags, boolean value) throws MessagingException { open(OpenMode.READ_WRITE); for (Message message : getMessages(null)) { message.setFlags(flags, value); } } @Override public String getUidFromMessageId(Message message) throws MessagingException { throw new MessagingException("Cannot call getUidFromMessageId on LocalFolder"); } private void clearMessagesWhere(final String whereClause, final String[] params) throws MessagingException { open(OpenMode.READ_ONLY); Message[] messages = LocalStore.this.getMessages( null, this, "SELECT " + GET_MESSAGES_COLS + "FROM messages WHERE " + whereClause, params); for (Message message : messages) { deleteAttachments(message.getUid()); } execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("DELETE FROM messages WHERE " + whereClause, params); return null; } }); resetUnreadAndFlaggedCounts(); } public void clearMessagesOlderThan(long cutoff) throws MessagingException { final String where = "folder_id = ? and date < ?"; final String[] params = new String[] { Long.toString(mFolderId), Long.toString(cutoff) }; clearMessagesWhere(where, params); } public void clearAllMessages() throws MessagingException { final String where = "folder_id = ?"; final String[] params = new String[] { Long.toString(mFolderId) }; clearMessagesWhere(where, params); setPushState(null); setLastPush(0); setLastChecked(0); } private void resetUnreadAndFlaggedCounts() { try { int newUnread = 0; int newFlagged = 0; Message[] messages = getMessages(null); for (Message message : messages) { if (!message.isSet(Flag.SEEN)) { newUnread++; } if (message.isSet(Flag.FLAGGED)) { newFlagged++; } } setUnreadMessageCount(newUnread); setFlaggedMessageCount(newFlagged); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to fetch all messages from LocalStore", e); } } @Override public void delete(final boolean recurse) throws MessagingException { try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { // We need to open the folder first to make sure we've got it's id open(OpenMode.READ_ONLY); Message[] messages = getMessages(null); for (Message message : messages) { deleteAttachments(message.getUid()); } } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM folders WHERE id = ?", new Object[] { Long.toString(mFolderId), }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } @Override public boolean equals(Object o) { if (o instanceof LocalFolder) { return ((LocalFolder)o).mName.equals(mName); } return super.equals(o); } @Override public int hashCode() { return mName.hashCode(); } @Override public Flag[] getPermanentFlags() throws MessagingException { return PERMANENT_FLAGS; } private void deleteAttachments(final long messageId) throws MessagingException { open(OpenMode.READ_WRITE); execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor attachmentsCursor = null; try { attachmentsCursor = db.query("attachments", new String[] { "id" }, "message_id = ?", new String[] { Long.toString(messageId) }, null, null, null); final File attachmentDirectory = StorageManager.getInstance(mApplication) .getAttachmentDirectory(uUid, mStorageProviderId); while (attachmentsCursor.moveToNext()) { long attachmentId = attachmentsCursor.getLong(0); try { File file = new File(attachmentDirectory, Long.toString(attachmentId)); if (file.exists()) { file.delete(); } } catch (Exception e) { } } } finally { if (attachmentsCursor != null) { attachmentsCursor.close(); } } return null; } }); } private void deleteAttachments(final String uid) throws MessagingException { open(OpenMode.READ_WRITE); try { execute(false, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor messagesCursor = null; try { messagesCursor = db.query("messages", new String[] { "id" }, "folder_id = ? AND uid = ?", new String[] { Long.toString(mFolderId), uid }, null, null, null); while (messagesCursor.moveToNext()) { long messageId = messagesCursor.getLong(0); deleteAttachments(messageId); } } catch (MessagingException e) { throw new WrappedException(e); } finally { if (messagesCursor != null) { messagesCursor.close(); } } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /* * calculateContentPreview * Takes a plain text message body as a string. * Returns a message summary as a string suitable for showing in a message list * * A message summary should be about the first 160 characters * of unique text written by the message sender * Quoted text, "On $date" and so on will be stripped out. * All newlines and whitespace will be compressed. * */ public String calculateContentPreview(String text) { if (text == null) { return null; } // Only look at the first 8k of a message when calculating // the preview. This should avoid unnecessary // memory usage on large messages if (text.length() > 8192) { text = text.substring(0,8192); } text = text.replaceAll("(?m)^----.*?$",""); text = text.replaceAll("(?m)^[#>].*$",""); text = text.replaceAll("(?m)^On .*wrote.?$",""); text = text.replaceAll("(?m)^.*\\w+:$",""); text = text.replaceAll("https?://\\S+","..."); text = text.replaceAll("(\\r|\\n)+"," "); text = text.replaceAll("\\s+"," "); if (text.length() <= 512) { return text; } else { text = text.substring(0,512); return text; } } public String markupContent(String text, String html) { if (text.length() > 0 && html.length() == 0) { html = htmlifyString(text); } html = convertEmoji2ImgForDocomo(html); return html; } public String htmlifyString(String text) { // Our HTMLification code is somewhat memory intensive // and was causing lots of OOM errors on the market // if the message is big and plain text, just do // a trivial htmlification if (text.length() > MAX_SMART_HTMLIFY_MESSAGE_LENGTH) { return "<html><head/><body>" + htmlifyMessageHeader() + text + htmlifyMessageFooter() + "</body></html>"; } StringReader reader = new StringReader(text); StringBuilder buff = new StringBuilder(text.length() + 512); int c = 0; try { while ((c = reader.read()) != -1) { switch (c) { case '&': buff.append("&amp;"); break; case '<': buff.append("&lt;"); break; case '>': buff.append("&gt;"); break; case '\r': break; default: buff.append((char)c); }//switch } } catch (IOException e) { //Should never happen Log.e(K9.LOG_TAG, null, e); } text = buff.toString(); text = text.replaceAll("\\s*([-=_]{30,}+)\\s*","<hr />"); text = text.replaceAll("(?m)^([^\r\n]{4,}[\\s\\w,:;+/])(?:\r\n|\n|\r)(?=[a-z]\\S{0,10}[\\s\\n\\r])","$1 "); text = text.replaceAll("(?m)(\r\n|\n|\r){4,}","\n\n"); Matcher m = Regex.WEB_URL_PATTERN.matcher(text); StringBuffer sb = new StringBuffer(text.length() + 512); sb.append("<html><head></head><body>"); sb.append(htmlifyMessageHeader()); while (m.find()) { int start = m.start(); if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) { if (m.group().indexOf(':') > 0) // With no URI-schema we may get "http:/" links with the second / missing { m.appendReplacement(sb, "<a href=\"$0\">$0</a>"); } else { m.appendReplacement(sb, "<a href=\"http://$0\">$0</a>"); } } else { m.appendReplacement(sb, "$0"); } } m.appendTail(sb); sb.append(htmlifyMessageFooter()); sb.append("</body></html>"); text = sb.toString(); return text; } private String htmlifyMessageHeader() { if (K9.messageViewFixedWidthFont()) { return "<pre style=\"white-space: pre-wrap; word-wrap:break-word; \">"; } else { return "<div style=\"white-space: pre-wrap; word-wrap:break-word; \">"; } } private String htmlifyMessageFooter() { if (K9.messageViewFixedWidthFont()) { return "</pre>"; } else { return "</div>"; } } public String convertEmoji2ImgForDocomo(String html) { StringReader reader = new StringReader(html); StringBuilder buff = new StringBuilder(html.length() + 512); int c = 0; try { while ((c = reader.read()) != -1) { switch (c) { // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree case 0xE6F9: //docomo kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE729: //docomo wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xE6D2: //docomo info02 buff.append("<img src=\"file:///android_asset/emoticons/info02.gif\" alt=\"info02\" />"); break; case 0xE753: //docomo smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE68D: //docomo heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE6A5: //docomo downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE6AD: //docomo pouch buff.append("<img src=\"file:///android_asset/emoticons/pouch.gif\" alt=\"pouch\" />"); break; case 0xE6D4: //docomo by-d buff.append("<img src=\"file:///android_asset/emoticons/by-d.gif\" alt=\"by-d\" />"); break; case 0xE6D7: //docomo free buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />"); break; case 0xE6E8: //docomo seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE74E: //docomo snail buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />"); break; case 0xE658: //docomo basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE65A: //docomo pocketbell buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />"); break; case 0xE6E3: //docomo two buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />"); break; case 0xE74A: //docomo cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE6D0: //docomo faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; case 0xE661: //docomo ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE64B: //docomo virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE67E: //docomo ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE6D6: //docomo yen buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />"); break; case 0xE6E0: //docomo sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE6FE: //docomo bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE6E1: //docomo mobaq buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />"); break; case 0xE70A: //docomo sign05 buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />"); break; case 0xE667: //docomo bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE731: //docomo copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE678: //docomo upwardright buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />"); break; case 0xE694: //docomo scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE682: //docomo bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE64D: //docomo scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE6D9: //docomo key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE734: //docomo secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE74F: //docomo chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE691: //docomo eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE70B: //docomo ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE714: //docomo door buff.append("<img src=\"file:///android_asset/emoticons/door.gif\" alt=\"door\" />"); break; case 0xE64F: //docomo capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xE674: //docomo boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE726: //docomo lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE68F: //docomo diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE69B: //docomo wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xE747: //docomo maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE64C: //docomo libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE647: //docomo taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE645: //docomo sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xE6FC: //docomo annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE6E6: //docomo five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE676: //docomo karaoke buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />"); break; case 0xE69D: //docomo moon1 buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />"); break; case 0xE709: //docomo sign04 buff.append("<img src=\"file:///android_asset/emoticons/sign04.gif\" alt=\"sign04\" />"); break; case 0xE72A: //docomo happy02 buff.append("<img src=\"file:///android_asset/emoticons/happy02.gif\" alt=\"happy02\" />"); break; case 0xE669: //docomo hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE71B: //docomo ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; case 0xE644: //docomo mist buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />"); break; case 0xE73B: //docomo full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xE683: //docomo book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE707: //docomo sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE716: //docomo pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE671: //docomo bar buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />"); break; case 0xE72B: //docomo bearing buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />"); break; case 0xE65C: //docomo subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE725: //docomo gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xE745: //docomo apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE65F: //docomo rvcar buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />"); break; case 0xE664: //docomo building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE737: //docomo danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE702: //docomo sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xE6EC: //docomo heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xE660: //docomo bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE72D: //docomo crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE652: //docomo sports buff.append("<img src=\"file:///android_asset/emoticons/sports.gif\" alt=\"sports\" />"); break; case 0xE6B8: //docomo on buff.append("<img src=\"file:///android_asset/emoticons/on.gif\" alt=\"on\" />"); break; case 0xE73C: //docomo leftright buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />"); break; case 0xE6BA: //docomo clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xE6F0: //docomo happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE701: //docomo sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE63E: //docomo sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xE67D: //docomo event buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />"); break; case 0xE689: //docomo memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; case 0xE68B: //docomo game buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />"); break; case 0xE718: //docomo wrench buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />"); break; case 0xE741: //docomo clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE693: //docomo rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE6F6: //docomo note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xE67A: //docomo music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE743: //docomo tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xE656: //docomo soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE69C: //docomo newmoon buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />"); break; case 0xE73E: //docomo school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE750: //docomo penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE696: //docomo downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE6CE: //docomo phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE728: //docomo bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE662: //docomo airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE74C: //docomo noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE704: //docomo sign03 buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />"); break; case 0xE68E: //docomo spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE698: //docomo foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE712: //docomo snowboard buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />"); break; case 0xE684: //docomo ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE6DA: //docomo enter buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />"); break; case 0xE6EA: //docomo nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE722: //docomo coldsweats01 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />"); break; case 0xE6F7: //docomo spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE710: //docomo rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xE73F: //docomo wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE686: //docomo birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE721: //docomo confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE6FF: //docomo notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE724: //docomo pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE6A4: //docomo xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE6FB: //docomo flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE71D: //docomo bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE6DC: //docomo search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE757: //docomo shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE680: //docomo nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xE66D: //docomo signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE66A: //docomo 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE6F4: //docomo wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE641: //docomo snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE6AE: //docomo pen buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />"); break; case 0xE70D: //docomo appli02 buff.append("<img src=\"file:///android_asset/emoticons/appli02.gif\" alt=\"appli02\" />"); break; case 0xE732: //docomo tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE755: //docomo pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE648: //docomo gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE6DE: //docomo flag buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />"); break; case 0xE6A1: //docomo dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE6EF: //docomo heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xE643: //docomo typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE65B: //docomo train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE746: //docomo bud buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />"); break; case 0xE653: //docomo baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE6B2: //docomo chair buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />"); break; case 0xE64A: //docomo leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE6E7: //docomo six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE6E4: //docomo three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xE6DF: //docomo freedial buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />"); break; case 0xE744: //docomo banana buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />"); break; case 0xE6DB: //docomo clear buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />"); break; case 0xE6AC: //docomo slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE666: //docomo hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE663: //docomo house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE695: //docomo paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE67F: //docomo smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE65D: //docomo bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE6B1: //docomo shadow buff.append("<img src=\"file:///android_asset/emoticons/shadow.gif\" alt=\"shadow\" />"); break; case 0xE670: //docomo cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xE654: //docomo golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE708: //docomo dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE748: //docomo cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE6F1: //docomo angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE736: //docomo r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xE6A2: //docomo cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE6D1: //docomo info01 buff.append("<img src=\"file:///android_asset/emoticons/info01.gif\" alt=\"info01\" />"); break; case 0xE687: //docomo telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE68C: //docomo cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE70E: //docomo t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE733: //docomo run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xE679: //docomo carouselpony buff.append("<img src=\"file:///android_asset/emoticons/carouselpony.gif\" alt=\"carouselpony\" />"); break; case 0xE646: //docomo aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE690: //docomo club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE64E: //docomo sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xE6F5: //docomo up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xE720: //docomo think buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />"); break; case 0xE6E2: //docomo one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xE6D8: //docomo id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE675: //docomo hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; case 0xE6B7: //docomo soon buff.append("<img src=\"file:///android_asset/emoticons/soon.gif\" alt=\"soon\" />"); break; case 0xE717: //docomo loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE673: //docomo fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE719: //docomo pencil buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />"); break; case 0xE697: //docomo upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xE730: //docomo clip buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />"); break; case 0xE6ED: //docomo heart02 buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />"); break; case 0xE69A: //docomo eyeglass buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />"); break; case 0xE65E: //docomo car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xE742: //docomo cherry buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />"); break; case 0xE71C: //docomo sandclock buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />"); break; case 0xE735: //docomo recycle buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />"); break; case 0xE752: //docomo delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE69E: //docomo moon2 buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />"); break; case 0xE68A: //docomo tv buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />"); break; case 0xE706: //docomo sweat01 buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />"); break; case 0xE738: //docomo ban buff.append("<img src=\"file:///android_asset/emoticons/ban.gif\" alt=\"ban\" />"); break; case 0xE672: //docomo beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xE640: //docomo rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xE69F: //docomo moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE657: //docomo ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE70C: //docomo appli01 buff.append("<img src=\"file:///android_asset/emoticons/appli01.gif\" alt=\"appli01\" />"); break; case 0xE6E5: //docomo four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE699: //docomo shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xE63F: //docomo cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE72F: //docomo ng buff.append("<img src=\"file:///android_asset/emoticons/ng.gif\" alt=\"ng\" />"); break; case 0xE6A3: //docomo yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE73A: //docomo pass buff.append("<img src=\"file:///android_asset/emoticons/pass.gif\" alt=\"pass\" />"); break; case 0xE67C: //docomo drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xE727: //docomo good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE6EB: //docomo zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xE72C: //docomo catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE6D5: //docomo d-point buff.append("<img src=\"file:///android_asset/emoticons/d-point.gif\" alt=\"d-point\" />"); break; case 0xE6F2: //docomo despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE700: //docomo down buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />"); break; case 0xE655: //docomo tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE703: //docomo sign02 buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />"); break; case 0xE711: //docomo denim buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />"); break; case 0xE705: //docomo impact buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />"); break; case 0xE642: //docomo thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE66C: //docomo parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE6F3: //docomo sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE71E: //docomo japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xE6FD: //docomo punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xE73D: //docomo updown buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />"); break; case 0xE66F: //docomo restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE66E: //docomo toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; case 0xE739: //docomo empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE723: //docomo coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE6B9: //docomo end buff.append("<img src=\"file:///android_asset/emoticons/end.gif\" alt=\"end\" />"); break; case 0xE67B: //docomo art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xE72E: //docomo weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE715: //docomo dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE6CF: //docomo mailto buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />"); break; case 0xE6F8: //docomo cute buff.append("<img src=\"file:///android_asset/emoticons/cute.gif\" alt=\"cute\" />"); break; case 0xE6DD: //docomo new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE651: //docomo pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE756: //docomo wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE649: //docomo cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xE650: //docomo aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE740: //docomo fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE681: //docomo camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE71F: //docomo watch buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />"); break; case 0xE6EE: //docomo heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE71A: //docomo crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE6B3: //docomo night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE66B: //docomo gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE692: //docomo ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE685: //docomo present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE6E9: //docomo eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE70F: //docomo moneybag buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />"); break; case 0xE749: //docomo riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE6A0: //docomo fullmoon buff.append("<img src=\"file:///android_asset/emoticons/fullmoon.gif\" alt=\"fullmoon\" />"); break; case 0xE74D: //docomo bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE665: //docomo postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xE677: //docomo movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE668: //docomo atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE688: //docomo mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE6FA: //docomo shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xE713: //docomo bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xE74B: //docomo bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xE754: //docomo horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE751: //docomo fish buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />"); break; case 0xE659: //docomo motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE6D3: //docomo mail buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />"); break; // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree // The spaces between the < and the img are a hack to avoid triggering // K-9's 'load images' button case 0xE223: //softbank eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE415: //softbank coldsweats01 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats01.gif\" alt=\"coldsweats01\" />"); break; case 0xE21F: //softbank four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE125: //softbank ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE148: //softbank book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE242: //softbank cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xE31C: //softbank rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xE252: //softbank danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE011: //softbank scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE342: //softbank riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE04B: //softbank rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xE03E: //softbank note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xE43C: //softbank sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xE20A: //softbank wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xE42A: //softbank basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE03D: //softbank movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE30E: //softbank smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE003: //softbank kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE21C: //softbank one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xE237: //softbank upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xE407: //softbank sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE03B: //softbank fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE40E: //softbank gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xE245: //softbank libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE24A: //softbank pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE443: //softbank typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE052: //softbank dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE244: //softbank virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE523: //softbank chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE023: //softbank heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE325: //softbank bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xE239: //softbank downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE20C: //softbank heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE211: //softbank freedial buff.append("<img src=\"file:///android_asset/emoticons/freedial.gif\" alt=\"freedial\" />"); break; case 0xE11F: //softbank chair buff.append("<img src=\"file:///android_asset/emoticons/chair.gif\" alt=\"chair\" />"); break; case 0xE108: //softbank coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE330: //softbank dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE404: //softbank smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE304: //softbank tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xE419: //softbank eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE13D: //softbank thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE013: //softbank ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE136: //softbank bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE059: //softbank angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE01D: //softbank airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE048: //softbank snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE435: //softbank bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE20E: //softbank spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE247: //softbank sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xE157: //softbank school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE10F: //softbank flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE502: //softbank art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xE338: //softbank japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xE34B: //softbank birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE22B: //softbank empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE311: //softbank bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE012: //softbank paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE151: //softbank toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; case 0xE01A: //softbank horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE03A: //softbank gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE03F: //softbank key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE00D: //softbank punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xE24D: //softbank ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE105: //softbank bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE00E: //softbank good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE154: //softbank atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE405: //softbank wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xE030: //softbank cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE057: //softbank happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE229: //softbank id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE016: //softbank baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE044: //softbank wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE115: //softbank run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xE14F: //softbank parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE327: //softbank heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xE014: //softbank golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE021: //softbank sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xE30A: //softbank music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE411: //softbank crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE536: //softbank foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE047: //softbank beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xE43E: //softbank wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE022: //softbank heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xE007: //softbank shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xE010: //softbank rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE32E: //softbank shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xE055: //softbank penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE03C: //softbank karaoke buff.append("<img src=\"file:///android_asset/emoticons/karaoke.gif\" alt=\"karaoke\" />"); break; case 0xE018: //softbank soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE159: //softbank bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE107: //softbank shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE04A: //softbank sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xE156: //softbank 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE110: //softbank clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE034: //softbank ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; case 0xE24F: //softbank r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xE112: //softbank present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE14D: //softbank bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE42E: //softbank rvcar buff.append("<img src=\"file:///android_asset/emoticons/rvcar.gif\" alt=\"rvcar\" />"); break; case 0xE13E: //softbank boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE413: //softbank weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE241: //softbank gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE212: //softbank new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE324: //softbank slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE220: //softbank five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE503: //softbank drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xE248: //softbank capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xE049: //softbank cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE243: //softbank leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE326: //softbank notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE00B: //softbank faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; case 0xE221: //softbank six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE240: //softbank taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE24E: //softbank copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE224: //softbank nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE008: //softbank camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE01E: //softbank train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE20D: //softbank diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE009: //softbank telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE019: //softbank fish buff.append("<img src=\"file:///android_asset/emoticons/fish.gif\" alt=\"fish\" />"); break; case 0xE01C: //softbank yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE40A: //softbank confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE246: //softbank scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE120: //softbank fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE323: //softbank bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE345: //softbank apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE339: //softbank bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE13C: //softbank sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE106: //softbank lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE340: //softbank noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE20F: //softbank club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE114: //softbank search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE10E: //softbank crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE406: //softbank wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE331: //softbank sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE04F: //softbank cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE301: //softbank memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; case 0xE01B: //softbank car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xE314: //softbank ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE315: //softbank secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE236: //softbank up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xE208: //softbank nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xE006: //softbank t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE12A: //softbank tv buff.append("<img src=\"file:///android_asset/emoticons/tv.gif\" alt=\"tv\" />"); break; case 0xE238: //softbank downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE10B: //softbank pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE126: //softbank cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE402: //softbank catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE416: //softbank pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE045: //softbank cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xE41B: //softbank ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE23F: //softbank aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE21E: //softbank three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xE056: //softbank delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE14E: //softbank signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE155: //softbank hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE033: //softbank xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE22A: //softbank full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xE123: //softbank spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE132: //softbank motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE434: //softbank subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE403: //softbank think buff.append("<img src=\"file:///android_asset/emoticons/think.gif\" alt=\"think\" />"); break; case 0xE043: //softbank restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE537: //softbank tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE058: //softbank despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE04C: //softbank moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE21D: //softbank two buff.append("<img src=\"file:///android_asset/emoticons/two.gif\" alt=\"two\" />"); break; case 0xE202: //softbank ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE30B: //softbank bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xE118: //softbank maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE103: //softbank loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE225: //softbank zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xE00C: //softbank pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE210: //softbank sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE015: //softbank tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE038: //softbank building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE02D: //softbank clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xE334: //softbank annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE153: //softbank postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xE222: //softbank seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE12F: //softbank dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE00A: //softbank mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE158: //softbank hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE249: //softbank aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE036: //softbank house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE046: //softbank cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE104: //softbank phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE44B: //softbank night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE313: //softbank hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; // These emoji codepoints are generated by tools/make_emoji in the K-9 source tree // The spaces between the < and the img are a hack to avoid triggering // K-9's 'load images' button case 0xE488: //kddi sun buff.append("<img src=\"file:///android_asset/emoticons/sun.gif\" alt=\"sun\" />"); break; case 0xEA88: //kddi id buff.append("<img src=\"file:///android_asset/emoticons/id.gif\" alt=\"id\" />"); break; case 0xE4BA: //kddi baseball buff.append("<img src=\"file:///android_asset/emoticons/baseball.gif\" alt=\"baseball\" />"); break; case 0xE525: //kddi four buff.append("<img src=\"file:///android_asset/emoticons/four.gif\" alt=\"four\" />"); break; case 0xE578: //kddi free buff.append("<img src=\"file:///android_asset/emoticons/free.gif\" alt=\"free\" />"); break; case 0xE4C1: //kddi wine buff.append("<img src=\"file:///android_asset/emoticons/wine.gif\" alt=\"wine\" />"); break; case 0xE512: //kddi bell buff.append("<img src=\"file:///android_asset/emoticons/bell.gif\" alt=\"bell\" />"); break; case 0xEB83: //kddi rock buff.append("<img src=\"file:///android_asset/emoticons/rock.gif\" alt=\"rock\" />"); break; case 0xE4D0: //kddi cake buff.append("<img src=\"file:///android_asset/emoticons/cake.gif\" alt=\"cake\" />"); break; case 0xE473: //kddi crying buff.append("<img src=\"file:///android_asset/emoticons/crying.gif\" alt=\"crying\" />"); break; case 0xE48C: //kddi rain buff.append("<img src=\"file:///android_asset/emoticons/rain.gif\" alt=\"rain\" />"); break; case 0xEAC2: //kddi bearing buff.append("<img src=\"file:///android_asset/emoticons/bearing.gif\" alt=\"bearing\" />"); break; case 0xE47E: //kddi nosmoking buff.append("<img src=\"file:///android_asset/emoticons/nosmoking.gif\" alt=\"nosmoking\" />"); break; case 0xEAC0: //kddi despair buff.append("<img src=\"file:///android_asset/emoticons/despair.gif\" alt=\"despair\" />"); break; case 0xE559: //kddi r-mark buff.append("<img src=\"file:///android_asset/emoticons/r-mark.gif\" alt=\"r-mark\" />"); break; case 0xEB2D: //kddi up buff.append("<img src=\"file:///android_asset/emoticons/up.gif\" alt=\"up\" />"); break; case 0xEA89: //kddi full buff.append("<img src=\"file:///android_asset/emoticons/full.gif\" alt=\"full\" />"); break; case 0xEAC9: //kddi gawk buff.append("<img src=\"file:///android_asset/emoticons/gawk.gif\" alt=\"gawk\" />"); break; case 0xEB79: //kddi recycle buff.append("<img src=\"file:///android_asset/emoticons/recycle.gif\" alt=\"recycle\" />"); break; case 0xE5AC: //kddi zero buff.append("<img src=\"file:///android_asset/emoticons/zero.gif\" alt=\"zero\" />"); break; case 0xEAAE: //kddi japanesetea buff.append("<img src=\"file:///android_asset/emoticons/japanesetea.gif\" alt=\"japanesetea\" />"); break; case 0xEB30: //kddi sign03 buff.append("<img src=\"file:///android_asset/emoticons/sign03.gif\" alt=\"sign03\" />"); break; case 0xE4B6: //kddi soccer buff.append("<img src=\"file:///android_asset/emoticons/soccer.gif\" alt=\"soccer\" />"); break; case 0xE556: //kddi downwardleft buff.append("<img src=\"file:///android_asset/emoticons/downwardleft.gif\" alt=\"downwardleft\" />"); break; case 0xE4BE: //kddi slate buff.append("<img src=\"file:///android_asset/emoticons/slate.gif\" alt=\"slate\" />"); break; case 0xE4A5: //kddi toilet buff.append("<img src=\"file:///android_asset/emoticons/toilet.gif\" alt=\"toilet\" />"); break; // Skipping kddi codepoint E523 two // It conflicts with an earlier definition from another carrier: // softbank chick case 0xE496: //kddi scorpius buff.append("<img src=\"file:///android_asset/emoticons/scorpius.gif\" alt=\"scorpius\" />"); break; case 0xE4C6: //kddi game buff.append("<img src=\"file:///android_asset/emoticons/game.gif\" alt=\"game\" />"); break; case 0xE5A0: //kddi birthday buff.append("<img src=\"file:///android_asset/emoticons/birthday.gif\" alt=\"birthday\" />"); break; case 0xE5B8: //kddi pc buff.append("<img src=\"file:///android_asset/emoticons/pc.gif\" alt=\"pc\" />"); break; case 0xE516: //kddi hairsalon buff.append("<img src=\"file:///android_asset/emoticons/hairsalon.gif\" alt=\"hairsalon\" />"); break; case 0xE475: //kddi sleepy buff.append("<img src=\"file:///android_asset/emoticons/sleepy.gif\" alt=\"sleepy\" />"); break; case 0xE4A3: //kddi atm buff.append("<img src=\"file:///android_asset/emoticons/atm.gif\" alt=\"atm\" />"); break; case 0xE59A: //kddi basketball buff.append("<img src=\"file:///android_asset/emoticons/basketball.gif\" alt=\"basketball\" />"); break; case 0xE497: //kddi sagittarius buff.append("<img src=\"file:///android_asset/emoticons/sagittarius.gif\" alt=\"sagittarius\" />"); break; case 0xEACD: //kddi delicious buff.append("<img src=\"file:///android_asset/emoticons/delicious.gif\" alt=\"delicious\" />"); break; case 0xE5A8: //kddi newmoon buff.append("<img src=\"file:///android_asset/emoticons/newmoon.gif\" alt=\"newmoon\" />"); break; case 0xE49E: //kddi ticket buff.append("<img src=\"file:///android_asset/emoticons/ticket.gif\" alt=\"ticket\" />"); break; case 0xE5AE: //kddi wobbly buff.append("<img src=\"file:///android_asset/emoticons/wobbly.gif\" alt=\"wobbly\" />"); break; case 0xE4E6: //kddi sweat02 buff.append("<img src=\"file:///android_asset/emoticons/sweat02.gif\" alt=\"sweat02\" />"); break; case 0xE59E: //kddi event buff.append("<img src=\"file:///android_asset/emoticons/event.gif\" alt=\"event\" />"); break; case 0xE4AB: //kddi house buff.append("<img src=\"file:///android_asset/emoticons/house.gif\" alt=\"house\" />"); break; case 0xE491: //kddi gemini buff.append("<img src=\"file:///android_asset/emoticons/gemini.gif\" alt=\"gemini\" />"); break; case 0xE4C9: //kddi xmas buff.append("<img src=\"file:///android_asset/emoticons/xmas.gif\" alt=\"xmas\" />"); break; case 0xE5BE: //kddi note buff.append("<img src=\"file:///android_asset/emoticons/note.gif\" alt=\"note\" />"); break; case 0xEB2F: //kddi sign02 buff.append("<img src=\"file:///android_asset/emoticons/sign02.gif\" alt=\"sign02\" />"); break; case 0xE508: //kddi music buff.append("<img src=\"file:///android_asset/emoticons/music.gif\" alt=\"music\" />"); break; case 0xE5DF: //kddi hospital buff.append("<img src=\"file:///android_asset/emoticons/hospital.gif\" alt=\"hospital\" />"); break; case 0xE5BC: //kddi subway buff.append("<img src=\"file:///android_asset/emoticons/subway.gif\" alt=\"subway\" />"); break; case 0xE5C9: //kddi crown buff.append("<img src=\"file:///android_asset/emoticons/crown.gif\" alt=\"crown\" />"); break; case 0xE4BC: //kddi spa buff.append("<img src=\"file:///android_asset/emoticons/spa.gif\" alt=\"spa\" />"); break; case 0xE514: //kddi ring buff.append("<img src=\"file:///android_asset/emoticons/ring.gif\" alt=\"ring\" />"); break; // Skipping kddi codepoint E502 tv // It conflicts with an earlier definition from another carrier: // softbank art case 0xE4AC: //kddi restaurant buff.append("<img src=\"file:///android_asset/emoticons/restaurant.gif\" alt=\"restaurant\" />"); break; case 0xE529: //kddi eight buff.append("<img src=\"file:///android_asset/emoticons/eight.gif\" alt=\"eight\" />"); break; case 0xE518: //kddi search buff.append("<img src=\"file:///android_asset/emoticons/search.gif\" alt=\"search\" />"); break; case 0xE505: //kddi notes buff.append("<img src=\"file:///android_asset/emoticons/notes.gif\" alt=\"notes\" />"); break; case 0xE498: //kddi capricornus buff.append("<img src=\"file:///android_asset/emoticons/capricornus.gif\" alt=\"capricornus\" />"); break; case 0xEB7E: //kddi snail buff.append("<img src=\"file:///android_asset/emoticons/snail.gif\" alt=\"snail\" />"); break; case 0xEA97: //kddi bottle buff.append("<img src=\"file:///android_asset/emoticons/bottle.gif\" alt=\"bottle\" />"); break; case 0xEB08: //kddi phoneto buff.append("<img src=\"file:///android_asset/emoticons/phoneto.gif\" alt=\"phoneto\" />"); break; case 0xE4D2: //kddi cherry buff.append("<img src=\"file:///android_asset/emoticons/cherry.gif\" alt=\"cherry\" />"); break; case 0xE54D: //kddi downwardright buff.append("<img src=\"file:///android_asset/emoticons/downwardright.gif\" alt=\"downwardright\" />"); break; case 0xE5C3: //kddi wink buff.append("<img src=\"file:///android_asset/emoticons/wink.gif\" alt=\"wink\" />"); break; case 0xEAAC: //kddi ski buff.append("<img src=\"file:///android_asset/emoticons/ski.gif\" alt=\"ski\" />"); break; case 0xE515: //kddi camera buff.append("<img src=\"file:///android_asset/emoticons/camera.gif\" alt=\"camera\" />"); break; case 0xE5B6: //kddi t-shirt buff.append("<img src=\"file:///android_asset/emoticons/t-shirt.gif\" alt=\"t-shirt\" />"); break; case 0xE5C4: //kddi lovely buff.append("<img src=\"file:///android_asset/emoticons/lovely.gif\" alt=\"lovely\" />"); break; case 0xE4AD: //kddi building buff.append("<img src=\"file:///android_asset/emoticons/building.gif\" alt=\"building\" />"); break; case 0xE4CE: //kddi maple buff.append("<img src=\"file:///android_asset/emoticons/maple.gif\" alt=\"maple\" />"); break; case 0xE5AA: //kddi moon2 buff.append("<img src=\"file:///android_asset/emoticons/moon2.gif\" alt=\"moon2\" />"); break; case 0xE5B4: //kddi noodle buff.append("<img src=\"file:///android_asset/emoticons/noodle.gif\" alt=\"noodle\" />"); break; case 0xE5A6: //kddi scissors buff.append("<img src=\"file:///android_asset/emoticons/scissors.gif\" alt=\"scissors\" />"); break; case 0xE4AA: //kddi bank buff.append("<img src=\"file:///android_asset/emoticons/bank.gif\" alt=\"bank\" />"); break; case 0xE4B5: //kddi train buff.append("<img src=\"file:///android_asset/emoticons/train.gif\" alt=\"train\" />"); break; case 0xE477: //kddi heart03 buff.append("<img src=\"file:///android_asset/emoticons/heart03.gif\" alt=\"heart03\" />"); break; case 0xE481: //kddi danger buff.append("<img src=\"file:///android_asset/emoticons/danger.gif\" alt=\"danger\" />"); break; case 0xE597: //kddi cafe buff.append("<img src=\"file:///android_asset/emoticons/cafe.gif\" alt=\"cafe\" />"); break; case 0xEB2B: //kddi shoe buff.append("<img src=\"file:///android_asset/emoticons/shoe.gif\" alt=\"shoe\" />"); break; case 0xEB7C: //kddi wave buff.append("<img src=\"file:///android_asset/emoticons/wave.gif\" alt=\"wave\" />"); break; case 0xE471: //kddi happy01 buff.append("<img src=\"file:///android_asset/emoticons/happy01.gif\" alt=\"happy01\" />"); break; case 0xE4CA: //kddi cherryblossom buff.append("<img src=\"file:///android_asset/emoticons/cherryblossom.gif\" alt=\"cherryblossom\" />"); break; case 0xE4D5: //kddi riceball buff.append("<img src=\"file:///android_asset/emoticons/riceball.gif\" alt=\"riceball\" />"); break; case 0xE587: //kddi wrench buff.append("<img src=\"file:///android_asset/emoticons/wrench.gif\" alt=\"wrench\" />"); break; case 0xEB2A: //kddi foot buff.append("<img src=\"file:///android_asset/emoticons/foot.gif\" alt=\"foot\" />"); break; case 0xE47D: //kddi smoking buff.append("<img src=\"file:///android_asset/emoticons/smoking.gif\" alt=\"smoking\" />"); break; case 0xE4DC: //kddi penguin buff.append("<img src=\"file:///android_asset/emoticons/penguin.gif\" alt=\"penguin\" />"); break; case 0xE4B3: //kddi airplane buff.append("<img src=\"file:///android_asset/emoticons/airplane.gif\" alt=\"airplane\" />"); break; case 0xE4DE: //kddi pig buff.append("<img src=\"file:///android_asset/emoticons/pig.gif\" alt=\"pig\" />"); break; case 0xE59B: //kddi pocketbell buff.append("<img src=\"file:///android_asset/emoticons/pocketbell.gif\" alt=\"pocketbell\" />"); break; case 0xE4AF: //kddi bus buff.append("<img src=\"file:///android_asset/emoticons/bus.gif\" alt=\"bus\" />"); break; case 0xE4A6: //kddi parking buff.append("<img src=\"file:///android_asset/emoticons/parking.gif\" alt=\"parking\" />"); break; case 0xE486: //kddi moon3 buff.append("<img src=\"file:///android_asset/emoticons/moon3.gif\" alt=\"moon3\" />"); break; case 0xE5A4: //kddi eye buff.append("<img src=\"file:///android_asset/emoticons/eye.gif\" alt=\"eye\" />"); break; case 0xE50C: //kddi cd buff.append("<img src=\"file:///android_asset/emoticons/cd.gif\" alt=\"cd\" />"); break; case 0xE54C: //kddi upwardleft buff.append("<img src=\"file:///android_asset/emoticons/upwardleft.gif\" alt=\"upwardleft\" />"); break; case 0xEA82: //kddi ship buff.append("<img src=\"file:///android_asset/emoticons/ship.gif\" alt=\"ship\" />"); break; case 0xE4B1: //kddi car buff.append("<img src=\"file:///android_asset/emoticons/car.gif\" alt=\"car\" />"); break; case 0xEB80: //kddi smile buff.append("<img src=\"file:///android_asset/emoticons/smile.gif\" alt=\"smile\" />"); break; case 0xE5B0: //kddi impact buff.append("<img src=\"file:///android_asset/emoticons/impact.gif\" alt=\"impact\" />"); break; case 0xE504: //kddi moneybag buff.append("<img src=\"file:///android_asset/emoticons/moneybag.gif\" alt=\"moneybag\" />"); break; case 0xE4B9: //kddi motorsports buff.append("<img src=\"file:///android_asset/emoticons/motorsports.gif\" alt=\"motorsports\" />"); break; case 0xE494: //kddi virgo buff.append("<img src=\"file:///android_asset/emoticons/virgo.gif\" alt=\"virgo\" />"); break; case 0xE595: //kddi heart01 buff.append("<img src=\"file:///android_asset/emoticons/heart01.gif\" alt=\"heart01\" />"); break; case 0xEB03: //kddi pen buff.append("<img src=\"file:///android_asset/emoticons/pen.gif\" alt=\"pen\" />"); break; case 0xE57D: //kddi yen buff.append("<img src=\"file:///android_asset/emoticons/yen.gif\" alt=\"yen\" />"); break; case 0xE598: //kddi mist buff.append("<img src=\"file:///android_asset/emoticons/mist.gif\" alt=\"mist\" />"); break; case 0xE5A2: //kddi diamond buff.append("<img src=\"file:///android_asset/emoticons/diamond.gif\" alt=\"diamond\" />"); break; case 0xE4A4: //kddi 24hours buff.append("<img src=\"file:///android_asset/emoticons/24hours.gif\" alt=\"24hours\" />"); break; case 0xE524: //kddi three buff.append("<img src=\"file:///android_asset/emoticons/three.gif\" alt=\"three\" />"); break; case 0xEB7B: //kddi updown buff.append("<img src=\"file:///android_asset/emoticons/updown.gif\" alt=\"updown\" />"); break; case 0xE5A1: //kddi spade buff.append("<img src=\"file:///android_asset/emoticons/spade.gif\" alt=\"spade\" />"); break; case 0xE495: //kddi libra buff.append("<img src=\"file:///android_asset/emoticons/libra.gif\" alt=\"libra\" />"); break; case 0xE588: //kddi mobilephone buff.append("<img src=\"file:///android_asset/emoticons/mobilephone.gif\" alt=\"mobilephone\" />"); break; case 0xE599: //kddi golf buff.append("<img src=\"file:///android_asset/emoticons/golf.gif\" alt=\"golf\" />"); break; case 0xE520: //kddi faxto buff.append("<img src=\"file:///android_asset/emoticons/faxto.gif\" alt=\"faxto\" />"); break; // Skipping kddi codepoint E503 karaoke // It conflicts with an earlier definition from another carrier: // softbank drama case 0xE4D6: //kddi fastfood buff.append("<img src=\"file:///android_asset/emoticons/fastfood.gif\" alt=\"fastfood\" />"); break; case 0xE4A1: //kddi pencil buff.append("<img src=\"file:///android_asset/emoticons/pencil.gif\" alt=\"pencil\" />"); break; case 0xE522: //kddi one buff.append("<img src=\"file:///android_asset/emoticons/one.gif\" alt=\"one\" />"); break; case 0xEB84: //kddi sharp buff.append("<img src=\"file:///android_asset/emoticons/sharp.gif\" alt=\"sharp\" />"); break; case 0xE476: //kddi flair buff.append("<img src=\"file:///android_asset/emoticons/flair.gif\" alt=\"flair\" />"); break; case 0xE46B: //kddi run buff.append("<img src=\"file:///android_asset/emoticons/run.gif\" alt=\"run\" />"); break; case 0xEAF5: //kddi drama buff.append("<img src=\"file:///android_asset/emoticons/drama.gif\" alt=\"drama\" />"); break; case 0xEAB9: //kddi apple buff.append("<img src=\"file:///android_asset/emoticons/apple.gif\" alt=\"apple\" />"); break; case 0xE4EB: //kddi kissmark buff.append("<img src=\"file:///android_asset/emoticons/kissmark.gif\" alt=\"kissmark\" />"); break; case 0xE55D: //kddi enter buff.append("<img src=\"file:///android_asset/emoticons/enter.gif\" alt=\"enter\" />"); break; case 0xE59F: //kddi ribbon buff.append("<img src=\"file:///android_asset/emoticons/ribbon.gif\" alt=\"ribbon\" />"); break; case 0xE526: //kddi five buff.append("<img src=\"file:///android_asset/emoticons/five.gif\" alt=\"five\" />"); break; case 0xE571: //kddi gasstation buff.append("<img src=\"file:///android_asset/emoticons/gasstation.gif\" alt=\"gasstation\" />"); break; case 0xE517: //kddi movie buff.append("<img src=\"file:///android_asset/emoticons/movie.gif\" alt=\"movie\" />"); break; case 0xE4B8: //kddi snowboard buff.append("<img src=\"file:///android_asset/emoticons/snowboard.gif\" alt=\"snowboard\" />"); break; case 0xEAE8: //kddi sprinkle buff.append("<img src=\"file:///android_asset/emoticons/sprinkle.gif\" alt=\"sprinkle\" />"); break; case 0xEA80: //kddi school buff.append("<img src=\"file:///android_asset/emoticons/school.gif\" alt=\"school\" />"); break; case 0xE47C: //kddi sandclock buff.append("<img src=\"file:///android_asset/emoticons/sandclock.gif\" alt=\"sandclock\" />"); break; case 0xEB31: //kddi sign05 buff.append("<img src=\"file:///android_asset/emoticons/sign05.gif\" alt=\"sign05\" />"); break; case 0xE5AB: //kddi clear buff.append("<img src=\"file:///android_asset/emoticons/clear.gif\" alt=\"clear\" />"); break; case 0xE5DE: //kddi postoffice buff.append("<img src=\"file:///android_asset/emoticons/postoffice.gif\" alt=\"postoffice\" />"); break; case 0xEB62: //kddi mailto buff.append("<img src=\"file:///android_asset/emoticons/mailto.gif\" alt=\"mailto\" />"); break; case 0xE528: //kddi seven buff.append("<img src=\"file:///android_asset/emoticons/seven.gif\" alt=\"seven\" />"); break; case 0xE4C2: //kddi bar buff.append("<img src=\"file:///android_asset/emoticons/bar.gif\" alt=\"bar\" />"); break; case 0xE487: //kddi thunder buff.append("<img src=\"file:///android_asset/emoticons/thunder.gif\" alt=\"thunder\" />"); break; case 0xE5A9: //kddi moon1 buff.append("<img src=\"file:///android_asset/emoticons/moon1.gif\" alt=\"moon1\" />"); break; case 0xEB7A: //kddi leftright buff.append("<img src=\"file:///android_asset/emoticons/leftright.gif\" alt=\"leftright\" />"); break; case 0xE513: //kddi clover buff.append("<img src=\"file:///android_asset/emoticons/clover.gif\" alt=\"clover\" />"); break; case 0xE492: //kddi cancer buff.append("<img src=\"file:///android_asset/emoticons/cancer.gif\" alt=\"cancer\" />"); break; case 0xEB78: //kddi loveletter buff.append("<img src=\"file:///android_asset/emoticons/loveletter.gif\" alt=\"loveletter\" />"); break; case 0xE4E0: //kddi chick buff.append("<img src=\"file:///android_asset/emoticons/chick.gif\" alt=\"chick\" />"); break; case 0xE4CF: //kddi present buff.append("<img src=\"file:///android_asset/emoticons/present.gif\" alt=\"present\" />"); break; case 0xE478: //kddi heart04 buff.append("<img src=\"file:///android_asset/emoticons/heart04.gif\" alt=\"heart04\" />"); break; case 0xEAC3: //kddi sad buff.append("<img src=\"file:///android_asset/emoticons/sad.gif\" alt=\"sad\" />"); break; case 0xE52A: //kddi nine buff.append("<img src=\"file:///android_asset/emoticons/nine.gif\" alt=\"nine\" />"); break; case 0xE482: //kddi sign01 buff.append("<img src=\"file:///android_asset/emoticons/sign01.gif\" alt=\"sign01\" />"); break; case 0xEABF: //kddi catface buff.append("<img src=\"file:///android_asset/emoticons/catface.gif\" alt=\"catface\" />"); break; case 0xE527: //kddi six buff.append("<img src=\"file:///android_asset/emoticons/six.gif\" alt=\"six\" />"); break; case 0xE52C: //kddi mobaq buff.append("<img src=\"file:///android_asset/emoticons/mobaq.gif\" alt=\"mobaq\" />"); break; case 0xE485: //kddi snow buff.append("<img src=\"file:///android_asset/emoticons/snow.gif\" alt=\"snow\" />"); break; case 0xE4B7: //kddi tennis buff.append("<img src=\"file:///android_asset/emoticons/tennis.gif\" alt=\"tennis\" />"); break; case 0xE5BD: //kddi fuji buff.append("<img src=\"file:///android_asset/emoticons/fuji.gif\" alt=\"fuji\" />"); break; case 0xE558: //kddi copyright buff.append("<img src=\"file:///android_asset/emoticons/copyright.gif\" alt=\"copyright\" />"); break; case 0xE4D8: //kddi horse buff.append("<img src=\"file:///android_asset/emoticons/horse.gif\" alt=\"horse\" />"); break; case 0xE4B0: //kddi bullettrain buff.append("<img src=\"file:///android_asset/emoticons/bullettrain.gif\" alt=\"bullettrain\" />"); break; case 0xE596: //kddi telephone buff.append("<img src=\"file:///android_asset/emoticons/telephone.gif\" alt=\"telephone\" />"); break; case 0xE48F: //kddi aries buff.append("<img src=\"file:///android_asset/emoticons/aries.gif\" alt=\"aries\" />"); break; case 0xE46A: //kddi signaler buff.append("<img src=\"file:///android_asset/emoticons/signaler.gif\" alt=\"signaler\" />"); break; case 0xE472: //kddi angry buff.append("<img src=\"file:///android_asset/emoticons/angry.gif\" alt=\"angry\" />"); break; case 0xE54E: //kddi tm buff.append("<img src=\"file:///android_asset/emoticons/tm.gif\" alt=\"tm\" />"); break; case 0xE51A: //kddi boutique buff.append("<img src=\"file:///android_asset/emoticons/boutique.gif\" alt=\"boutique\" />"); break; case 0xE493: //kddi leo buff.append("<img src=\"file:///android_asset/emoticons/leo.gif\" alt=\"leo\" />"); break; case 0xE5A3: //kddi club buff.append("<img src=\"file:///android_asset/emoticons/club.gif\" alt=\"club\" />"); break; case 0xE499: //kddi aquarius buff.append("<img src=\"file:///android_asset/emoticons/aquarius.gif\" alt=\"aquarius\" />"); break; case 0xE4AE: //kddi bicycle buff.append("<img src=\"file:///android_asset/emoticons/bicycle.gif\" alt=\"bicycle\" />"); break; case 0xE4E7: //kddi bleah buff.append("<img src=\"file:///android_asset/emoticons/bleah.gif\" alt=\"bleah\" />"); break; case 0xE49F: //kddi book buff.append("<img src=\"file:///android_asset/emoticons/book.gif\" alt=\"book\" />"); break; case 0xE5AD: //kddi ok buff.append("<img src=\"file:///android_asset/emoticons/ok.gif\" alt=\"ok\" />"); break; case 0xE5A7: //kddi paper buff.append("<img src=\"file:///android_asset/emoticons/paper.gif\" alt=\"paper\" />"); break; case 0xE4E5: //kddi annoy buff.append("<img src=\"file:///android_asset/emoticons/annoy.gif\" alt=\"annoy\" />"); break; case 0xE4A0: //kddi clip buff.append("<img src=\"file:///android_asset/emoticons/clip.gif\" alt=\"clip\" />"); break; case 0xE509: //kddi rouge buff.append("<img src=\"file:///android_asset/emoticons/rouge.gif\" alt=\"rouge\" />"); break; case 0xEAAF: //kddi bread buff.append("<img src=\"file:///android_asset/emoticons/bread.gif\" alt=\"bread\" />"); break; case 0xE519: //kddi key buff.append("<img src=\"file:///android_asset/emoticons/key.gif\" alt=\"key\" />"); break; case 0xE594: //kddi clock buff.append("<img src=\"file:///android_asset/emoticons/clock.gif\" alt=\"clock\" />"); break; case 0xEB7D: //kddi bud buff.append("<img src=\"file:///android_asset/emoticons/bud.gif\" alt=\"bud\" />"); break; case 0xEA8A: //kddi empty buff.append("<img src=\"file:///android_asset/emoticons/empty.gif\" alt=\"empty\" />"); break; case 0xE5B5: //kddi new buff.append("<img src=\"file:///android_asset/emoticons/new.gif\" alt=\"new\" />"); break; case 0xE47A: //kddi bomb buff.append("<img src=\"file:///android_asset/emoticons/bomb.gif\" alt=\"bomb\" />"); break; case 0xE5C6: //kddi coldsweats02 buff.append("<img src=\"file:///android_asset/emoticons/coldsweats02.gif\" alt=\"coldsweats02\" />"); break; case 0xE49A: //kddi pisces buff.append("<img src=\"file:///android_asset/emoticons/pisces.gif\" alt=\"pisces\" />"); break; case 0xE4F3: //kddi punch buff.append("<img src=\"file:///android_asset/emoticons/punch.gif\" alt=\"punch\" />"); break; case 0xEB5D: //kddi pout buff.append("<img src=\"file:///android_asset/emoticons/pout.gif\" alt=\"pout\" />"); break; case 0xE469: //kddi typhoon buff.append("<img src=\"file:///android_asset/emoticons/typhoon.gif\" alt=\"typhoon\" />"); break; case 0xE5B1: //kddi sweat01 buff.append("<img src=\"file:///android_asset/emoticons/sweat01.gif\" alt=\"sweat01\" />"); break; case 0xE4C7: //kddi dollar buff.append("<img src=\"file:///android_asset/emoticons/dollar.gif\" alt=\"dollar\" />"); break; case 0xE5C5: //kddi shock buff.append("<img src=\"file:///android_asset/emoticons/shock.gif\" alt=\"shock\" />"); break; case 0xE4F9: //kddi good buff.append("<img src=\"file:///android_asset/emoticons/good.gif\" alt=\"good\" />"); break; case 0xE4F1: //kddi secret buff.append("<img src=\"file:///android_asset/emoticons/secret.gif\" alt=\"secret\" />"); break; case 0xE4E4: //kddi tulip buff.append("<img src=\"file:///android_asset/emoticons/tulip.gif\" alt=\"tulip\" />"); break; case 0xEA81: //kddi hotel buff.append("<img src=\"file:///android_asset/emoticons/hotel.gif\" alt=\"hotel\" />"); break; case 0xE4FE: //kddi eyeglass buff.append("<img src=\"file:///android_asset/emoticons/eyeglass.gif\" alt=\"eyeglass\" />"); break; case 0xEAF1: //kddi night buff.append("<img src=\"file:///android_asset/emoticons/night.gif\" alt=\"night\" />"); break; case 0xE555: //kddi upwardright buff.append("<img src=\"file:///android_asset/emoticons/upwardright.gif\" alt=\"upwardright\" />"); break; case 0xEB2E: //kddi down buff.append("<img src=\"file:///android_asset/emoticons/down.gif\" alt=\"down\" />"); break; case 0xE4DB: //kddi cat buff.append("<img src=\"file:///android_asset/emoticons/cat.gif\" alt=\"cat\" />"); break; case 0xE59C: //kddi art buff.append("<img src=\"file:///android_asset/emoticons/art.gif\" alt=\"art\" />"); break; case 0xEB69: //kddi weep buff.append("<img src=\"file:///android_asset/emoticons/weep.gif\" alt=\"weep\" />"); break; case 0xE4F4: //kddi dash buff.append("<img src=\"file:///android_asset/emoticons/dash.gif\" alt=\"dash\" />"); break; case 0xE490: //kddi taurus buff.append("<img src=\"file:///android_asset/emoticons/taurus.gif\" alt=\"taurus\" />"); break; case 0xE57A: //kddi watch buff.append("<img src=\"file:///android_asset/emoticons/watch.gif\" alt=\"watch\" />"); break; case 0xEB2C: //kddi flag buff.append("<img src=\"file:///android_asset/emoticons/flag.gif\" alt=\"flag\" />"); break; case 0xEB77: //kddi denim buff.append("<img src=\"file:///android_asset/emoticons/denim.gif\" alt=\"denim\" />"); break; case 0xEAC5: //kddi confident buff.append("<img src=\"file:///android_asset/emoticons/confident.gif\" alt=\"confident\" />"); break; case 0xE4B4: //kddi yacht buff.append("<img src=\"file:///android_asset/emoticons/yacht.gif\" alt=\"yacht\" />"); break; case 0xE49C: //kddi bag buff.append("<img src=\"file:///android_asset/emoticons/bag.gif\" alt=\"bag\" />"); break; case 0xE5A5: //kddi ear buff.append("<img src=\"file:///android_asset/emoticons/ear.gif\" alt=\"ear\" />"); break; case 0xE4E1: //kddi dog buff.append("<img src=\"file:///android_asset/emoticons/dog.gif\" alt=\"dog\" />"); break; case 0xE521: //kddi mail buff.append("<img src=\"file:///android_asset/emoticons/mail.gif\" alt=\"mail\" />"); break; case 0xEB35: //kddi banana buff.append("<img src=\"file:///android_asset/emoticons/banana.gif\" alt=\"banana\" />"); break; case 0xEAA5: //kddi heart buff.append("<img src=\"file:///android_asset/emoticons/heart.gif\" alt=\"heart\" />"); break; case 0xE47F: //kddi wheelchair buff.append("<img src=\"file:///android_asset/emoticons/wheelchair.gif\" alt=\"wheelchair\" />"); break; case 0xEB75: //kddi heart02 buff.append("<img src=\"file:///android_asset/emoticons/heart02.gif\" alt=\"heart02\" />"); break; case 0xE48D: //kddi cloud buff.append("<img src=\"file:///android_asset/emoticons/cloud.gif\" alt=\"cloud\" />"); break; case 0xE4C3: //kddi beer buff.append("<img src=\"file:///android_asset/emoticons/beer.gif\" alt=\"beer\" />"); break; case 0xEAAB: //kddi shine buff.append("<img src=\"file:///android_asset/emoticons/shine.gif\" alt=\"shine\" />"); break; case 0xEA92: //kddi memo buff.append("<img src=\"file:///android_asset/emoticons/memo.gif\" alt=\"memo\" />"); break; default: buff.append((char)c); }//switch } } catch (IOException e) { //Should never happen Log.e(K9.LOG_TAG, null, e); } return buff.toString(); } @Override public boolean isInTopGroup() { return inTopGroup; } public void setInTopGroup(boolean inTopGroup) { this.inTopGroup = inTopGroup; } } public class LocalTextBody extends TextBody { private String mBodyForDisplay; public LocalTextBody(String body) { super(body); } public LocalTextBody(String body, String bodyForDisplay) throws MessagingException { super(body); this.mBodyForDisplay = bodyForDisplay; } public String getBodyForDisplay() { return mBodyForDisplay; } public void setBodyForDisplay(String mBodyForDisplay) { this.mBodyForDisplay = mBodyForDisplay; } }//LocalTextBody public class LocalMessage extends MimeMessage { private long mId; private int mAttachmentCount; private String mSubject; private String mPreview = ""; private boolean mHeadersLoaded = false; private boolean mMessageDirty = false; public LocalMessage() { } LocalMessage(String uid, Folder folder) throws MessagingException { this.mUid = uid; this.mFolder = folder; } private void populateFromGetMessageCursor(Cursor cursor) throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); for (String flag : flags) { try { this.setFlagInternal(Flag.valueOf(flag), true); } catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } } } this.mId = cursor.getLong(5); this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6))); this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7))); this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8))); this.setReplyTo(Address.unpack(cursor.getString(9))); this.mAttachmentCount = cursor.getInt(10); this.setInternalDate(new Date(cursor.getLong(11))); this.setMessageId(cursor.getString(12)); final String preview = cursor.getString(14); mPreview = (preview == null ? "" : preview); if (this.mFolder == null) { LocalFolder f = new LocalFolder(cursor.getInt(13)); f.open(LocalFolder.OpenMode.READ_WRITE); this.mFolder = f; } } /* Custom version of writeTo that updates the MIME message based on localMessage * changes. */ @Override public void writeTo(OutputStream out) throws IOException, MessagingException { if (mMessageDirty) buildMimeRepresentation(); super.writeTo(out); } private void buildMimeRepresentation() throws MessagingException { if (!mMessageDirty) { return; } super.setSubject(mSubject); if (this.mFrom != null && this.mFrom.length > 0) { super.setFrom(this.mFrom[0]); } super.setReplyTo(mReplyTo); super.setSentDate(this.getSentDate()); super.setRecipients(RecipientType.TO, mTo); super.setRecipients(RecipientType.CC, mCc); super.setRecipients(RecipientType.BCC, mBcc); if (mMessageId != null) super.setMessageId(mMessageId); mMessageDirty = false; } public String getPreview() { return mPreview; } @Override public String getSubject() { return mSubject; } @Override public void setSubject(String subject) throws MessagingException { mSubject = subject; mMessageDirty = true; } @Override public void setMessageId(String messageId) { mMessageId = messageId; mMessageDirty = true; } public int getAttachmentCount() { return mAttachmentCount; } @Override public void setFrom(Address from) throws MessagingException { this.mFrom = new Address[] { from }; mMessageDirty = true; } @Override public void setReplyTo(Address[] replyTo) throws MessagingException { if (replyTo == null || replyTo.length == 0) { mReplyTo = null; } else { mReplyTo = replyTo; } mMessageDirty = true; } /* * For performance reasons, we add headers instead of setting them (see super implementation) * which removes (expensive) them before adding them */ @Override public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException { if (type == RecipientType.TO) { if (addresses == null || addresses.length == 0) { this.mTo = null; } else { this.mTo = addresses; } } else if (type == RecipientType.CC) { if (addresses == null || addresses.length == 0) { this.mCc = null; } else { this.mCc = addresses; } } else if (type == RecipientType.BCC) { if (addresses == null || addresses.length == 0) { this.mBcc = null; } else { this.mBcc = addresses; } } else { throw new MessagingException("Unrecognized recipient type."); } mMessageDirty = true; } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } public long getId() { return mId; } @Override public void setFlag(final Flag flag, final boolean set) throws MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { if (flag == Flag.DELETED && set) { delete(); } updateFolderCountsOnFlag(flag, set); LocalMessage.super.setFlag(flag, set); } catch (MessagingException e) { throw new WrappedException(e); } /* * Set the flags on the message. */ db.execSQL("UPDATE messages " + "SET flags = ? " + " WHERE id = ?", new Object[] { Utility.combine(getFlags(), ',').toUpperCase(), mId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } /* * If a message is being marked as deleted we want to clear out it's content * and attachments as well. Delete will not actually remove the row since we need * to retain the uid for synchronization purposes. */ private void delete() throws MessagingException { /* * Delete all of the message's content to save space. */ try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { db.execSQL("UPDATE messages SET " + "deleted = 1," + "subject = NULL, " + "sender_list = NULL, " + "date = NULL, " + "to_list = NULL, " + "cc_list = NULL, " + "bcc_list = NULL, " + "preview = NULL, " + "html_content = NULL, " + "text_content = NULL, " + "reply_to_list = NULL " + "WHERE id = ?", new Object[] { mId }); /* * Delete all of the message's attachments to save space. * We do this explicit deletion here because we're not deleting the record * in messages, which means our ON DELETE trigger for messages won't cascade */ try { ((LocalFolder) mFolder).deleteAttachments(mId); } catch (MessagingException e) { throw new WrappedException(e); } db.execSQL("DELETE FROM attachments WHERE message_id = ?", new Object[] { mId }); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } ((LocalFolder)mFolder).deleteHeaders(mId); } /* * Completely remove a message from the local database */ @Override public void destroy() throws MessagingException { try { execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { ((LocalFolder) mFolder).deleteAttachments(mId); mDb.execSQL("DELETE FROM messages WHERE id = ?", new Object[] { mId }); updateFolderCountsOnFlag(Flag.X_DESTROYED, true); } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } } private void updateFolderCountsOnFlag(Flag flag, boolean set) throws MessagingException { /* * Update the unread count on the folder. */ try { LocalFolder folder = (LocalFolder)mFolder; if (flag == Flag.DELETED || flag == Flag.X_DESTROYED) { if (set != isSet(Flag.SEEN)) { folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? -1:1) ); } if (isSet(Flag.FLAGGED)) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? -1 : 1)); } } if ( !isSet(Flag.DELETED) ) { if ( flag == Flag.SEEN ) { if (set != isSet(Flag.SEEN)) { folder.setUnreadMessageCount(folder.getUnreadMessageCount() + ( set ? 1: -1) ); } } if ( flag == Flag.FLAGGED ) { folder.setFlaggedMessageCount(folder.getFlaggedMessageCount() + (set ? 1 : -1)); } } } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Unable to update LocalStore unread message count", me); throw new RuntimeException(me); } } private void loadHeaders() throws UnavailableStorageException { ArrayList<LocalMessage> messages = new ArrayList<LocalMessage>(); messages.add(this); mHeadersLoaded = true; // set true before calling populate headers to stop recursion ((LocalFolder) mFolder).populateHeaders(messages); } @Override public void addHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.addHeader(name, value); } @Override public void setHeader(String name, String value) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.setHeader(name, value); } @Override public String[] getHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeader(name); } @Override public void removeHeader(String name) throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); super.removeHeader(name); } @Override public Set<String> getHeaderNames() throws UnavailableStorageException { if (!mHeadersLoaded) loadHeaders(); return super.getHeaderNames(); } } public class LocalAttachmentBodyPart extends MimeBodyPart { private long mAttachmentId = -1; public LocalAttachmentBodyPart(Body body, long attachmentId) throws MessagingException { super(body); mAttachmentId = attachmentId; } /** * Returns the local attachment id of this body, or -1 if it is not stored. * @return */ public long getAttachmentId() { return mAttachmentId; } public void setAttachmentId(long attachmentId) { mAttachmentId = attachmentId; } @Override public String toString() { return "" + mAttachmentId; } } public static class LocalAttachmentBody implements Body { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Application mApplication; private Uri mUri; public LocalAttachmentBody(Uri uri, Application application) { mApplication = application; mUri = uri; } public InputStream getInputStream() throws MessagingException { try { return mApplication.getContentResolver().openInputStream(mUri); } catch (FileNotFoundException fnfe) { /* * Since it's completely normal for us to try to serve up attachments that * have been blown away, we just return an empty stream. */ return new ByteArrayInputStream(EMPTY_BYTE_ARRAY); } } public void writeTo(OutputStream out) throws IOException, MessagingException { InputStream in = getInputStream(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(in, base64Out); base64Out.close(); } public Uri getContentUri() { return mUri; } } }
Added method name logging on transaction logging, when debug is enabled
src/com/fsck/k9/mail/store/LocalStore.java
Added method name logging on transaction logging, when debug is enabled
<ide><path>rc/com/fsck/k9/mail/store/LocalStore.java <ide> mDb.endTransaction(); <ide> if (debug) <ide> { <del> Log.v(K9.LOG_TAG, "LocalStore: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms"); <add> Log.v(K9.LOG_TAG, "LocalStore: Transaction ended, took " + Long.toString(System.currentTimeMillis() - begin) + "ms / " + new Exception().getStackTrace()[1].toString()); <ide> } <ide> } <ide> }
Java
lgpl-2.1
de0cc73f405476a2cd3dd629d5a9e99664569fd7
0
retoo/pystructure,retoo/pystructure,retoo/pystructure,retoo/pystructure
/* * Copyright (C) 2007-2008 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package ch.hsr.ifs.pystructure.typeinference.visitors; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Map.Entry; import org.python.pydev.parser.jython.ast.Assign; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.For; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Global; import org.python.pydev.parser.jython.ast.If; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.jython.ast.NameTokType; import org.python.pydev.parser.jython.ast.TryExcept; import org.python.pydev.parser.jython.ast.TryFinally; import org.python.pydev.parser.jython.ast.Tuple; import org.python.pydev.parser.jython.ast.While; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.parser.jython.ast.argumentsType; import org.python.pydev.parser.jython.ast.excepthandlerType; import org.python.pydev.parser.jython.ast.exprType; import org.python.pydev.parser.jython.ast.stmtType; import org.python.pydev.parser.jython.ast.suiteType; import ch.hsr.ifs.pystructure.typeinference.model.base.NamePath; import ch.hsr.ifs.pystructure.typeinference.model.base.NodeUtils; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AttributeUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NameUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.TupleElement; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Use; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Value; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Block; import ch.hsr.ifs.pystructure.typeinference.model.scopes.BuiltInScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ModuleScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Scope; public class DefinitionVisitor extends StructuralVisitor { private final Module module; private ModuleScope moduleScope; private Stack<Block> blocks; private List<Use> uses; public DefinitionVisitor(Module module) { this.module = module; this.moduleScope = new ModuleScope(new BuiltInScope(), module); this.blocks = new Stack<Block>(); this.uses = module.getContainedUses(); } public void run() { try { super.run(module); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Object visitModule(org.python.pydev.parser.jython.ast.Module node) throws Exception { blocks.push(moduleScope); super.visitModule(node); visitChildren(module); blocks.pop(); moduleScope.connectGlobals(); module.getDefinitions().addAll(moduleScope.getCurrentBlockDefinitions()); return null; } @Override public Object visitClassDef(ClassDef node) throws Exception { Class klass = getDefinitionFor(node); if (isFirstVisit(klass)) { addDefinition(klass); } else { blocks.push(new Scope(getBlock(), klass)); super.visitClassDef(node); visitChildren(klass); blocks.pop(); } return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { Function function = getDefinitionFor(node); if (isFirstVisit(function)) { /* * TODO: What about this? * * global func * def func(): * print "I'm global" */ addDefinition(function); } else { Scope functionScope = new Scope(getBlock(), function); blocks.push(functionScope); addArgumentDefinitions(node.args, function); super.visitFunctionDef(node); visitChildren(function); blocks.pop(); } return null; } private void addArgumentDefinitions(argumentsType args, Function function) { int firstDefault = args.args.length - args.defaults.length; for (int position = 0; position < args.args.length; ++position) { exprType argument = args.args[position]; if (argument instanceof Name) { String name = ((Name) argument).id; exprType defaultValue = null; if (position >= firstDefault) { defaultValue = args.defaults[position - firstDefault]; } addDefinition(new Argument(module, name, argument, position, defaultValue, function)); } } } @Override public Object visitAssign(Assign node) throws Exception { node.value.accept(this); node.value.parent = node; for (exprType target : node.targets) { Map<String, Value> values = getValues(target, node.value); for (Entry<String, Value> entry : values.entrySet()) { String name = entry.getKey(); Definition d = new AssignDefinition(module, name, node, entry.getValue()); addDefinition(d); } target.accept(this); target.parent = node; } return null; } // TODO: Move this out of DefinitionVisitor private Map<String, Value> getValues(exprType target, exprType value) { Map<String, Value> values = new HashMap<String, Value>(); LinkedList<Integer> indexes = new LinkedList<Integer>(); getValues(values, indexes, target, value); return values; } private void getValues(Map<String, Value> values, LinkedList<Integer> indexes, exprType target, exprType value) { if (target instanceof Tuple) { Tuple tuple = (Tuple) target; for (int i = 0; i < tuple.elts.length; i++) { exprType element = tuple.elts[i]; indexes.addLast(i); getValues(values, indexes, element, value); indexes.removeLast(); } } else if (target instanceof Name) { String name = ((Name) target).id; Value v; if (indexes.size() == 0) { v = new Value(value); } else { v = new TupleElement(value, indexes); } values.put(name, v); } } @Override public Object visitName(Name node) throws Exception { NameUse use = new NameUse(node.id, node, module); addNameUse(use); super.visitName(node); return null; } @Override public Object visitNameTok(NameTok node) throws Exception { NameUse use = new NameUse(node.id, node, module); addNameUse(use); super.visitNameTok(node); return null; } @Override public Object visitAttribute(Attribute node) throws Exception { uses.add(new AttributeUse(node, module)); node.parent = stack.peek(); stack.push(node); // Don't visit node.attr, we don't want a NameUse for it. node.attr.parent = node; node.value.accept(this); stack.pop(); return null; } @Override public Object visitGlobal(Global node) throws Exception { for (NameTokType nameTok : node.names) { String name = NodeUtils.getId(nameTok); getScope().setGlobal(name); nameTok.accept(this); } return null; } @Override public Object visitIf(If node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitFor(For node) throws Exception { Block parent = getBlock(); node.iter.accept(this); Block bodyBlock = new Block(parent); // TODO: What about tuples? if (node.target instanceof Name) { String name = ((Name) node.target).id; Definition loopVariable = new LoopVariableDefinition(module, name, node); bodyBlock.setCurrentDefinition(loopVariable); parent.addToCurrentDefinitions(loopVariable); node.target.accept(this); } visitBlock(bodyBlock, node.body); Block orelseBlock = new Block(parent); // Definitions may flow from the body to the else block. orelseBlock.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitWhile(While node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); orelseBlock.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitTryExcept(TryExcept node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); for (excepthandlerType handler : node.handlers) { Block handlerBlock = new Block(parent); handlerBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); // TODO: What about tuples? if (handler.name instanceof Name) { String name = ((Name) handler.name).id; ExceptDefinition definition = new ExceptDefinition(module, name, handler); handlerBlock.setCurrentDefinition(definition); } visitBlock(handlerBlock, handler.body); parent.addToCurrentDefinitions(handlerBlock.getCurrentBlockDefinitions()); } orelseBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); visitBlock(orelseBlock, node.orelse); // We need to add all definitions of the block, because we don't know // where the exception was thrown, it could be between two definitions // of the same name. parent.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitTryFinally(TryFinally node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block finallyBlock = new Block(parent); visitBlock(bodyBlock, node.body); finallyBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); visitBlock(finallyBlock, node.finalbody); parent.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); // Overwrite the current definitions, because we don't know whether an // exception occurred or not. for (Definition definition : finallyBlock.getCurrentBlockDefinitions()) { parent.setCurrentDefinition(definition); } return null; } private void visitBlock(Block block, stmtType[] body) throws Exception { if (body == null) { return; } blocks.push(block); for (stmtType statement : body) { statement.accept(this); } blocks.pop(); } private void visitBlock(Block block, suiteType suite) throws Exception { if (suite != null) { visitBlock(block, suite.body); } } private void addDefinition(Definition definition) { if (getScope().isGlobal(definition.getName())) { moduleScope.addGlobalDefinition(definition); } else { getBlock().setCurrentDefinition(definition); } } private void addNameUse(NameUse use) { List<Definition> definitions = getBlock().getCurrentDefinitions(use.getName()); use.addDefinitions(definitions); if (getScope() == moduleScope || getScope().isGlobal(use.getName())) { moduleScope.addGlobalNameUse(use); } uses.add(use); } private Block getBlock() { return blocks.peek(); } private Scope getScope() { Block scope = getBlock(); while (!(scope instanceof Scope)) { scope = scope.getParent(); } return (Scope) scope; } public List<Use> getUses() { return uses; } /* import stuff */ /* * Examples: * * import pkg.module * import pkg.module as module * import pkg.module, pkg2.module2 * import pkg * * Doesn't work: * * import pkg.module.Class */ @Override public Object visitImport(Import node) throws Exception { for (aliasType entry : node.names) { ImportDefinition definition; if (entry.asname == null) { /* import package.module # package -> package */ NamePath fullPath = new NamePath(NodeUtils.getId(entry.name)); NamePath name = new NamePath(fullPath.getFirstPart()); definition = new ImportDefinition(module, node, name, null, name.toString()); } else { /* import package.module as alias # alias -> package.module */ String alias = NodeUtils.getId(entry.asname); NamePath path = new NamePath(NodeUtils.getId(entry.name)); definition = new ImportDefinition(module, node, path, null, alias); } addDefinition(definition); } return null; } /* * Examples: * * from pkg.module import Class * from pkg.module import Class as C1, ClassTwo as C2 * from pkg.module import * # grrr * from pkg import module * from pkg import * # doesn't import all modules, but everything in __init__.py * from .module import Class * from . import module * * TODO: Support wildcard imports */ @Override public Object visitImportFrom(ImportFrom node) throws Exception { NamePath path = new NamePath(NodeUtils.getId(node.module)); for (aliasType entry : node.names) { String element = NodeUtils.getId(entry.name); String alias = NodeUtils.getId(entry.asname == null ? entry.name : entry.asname); ImportDefinition definition = new ImportDefinition(module, node, path, element, alias, node.level); addDefinition(definition); if (entry.asname != null) { /* * In the following case, we have to add a name use for Class, * because otherwise it can't be found by reference finders: * * from module import Class as Alias */ NameUse use = new NameUse(element, entry.name, this.module); use.addDefinition(definition); uses.add(use); } } return null; } }
src/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java
/* * Copyright (C) 2007-2008 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package ch.hsr.ifs.pystructure.typeinference.visitors; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Map.Entry; import org.python.pydev.parser.jython.ast.Assign; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.For; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Global; import org.python.pydev.parser.jython.ast.If; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.jython.ast.NameTokType; import org.python.pydev.parser.jython.ast.TryExcept; import org.python.pydev.parser.jython.ast.TryFinally; import org.python.pydev.parser.jython.ast.Tuple; import org.python.pydev.parser.jython.ast.While; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.parser.jython.ast.argumentsType; import org.python.pydev.parser.jython.ast.excepthandlerType; import org.python.pydev.parser.jython.ast.exprType; import org.python.pydev.parser.jython.ast.stmtType; import org.python.pydev.parser.jython.ast.suiteType; import ch.hsr.ifs.pystructure.typeinference.model.base.NamePath; import ch.hsr.ifs.pystructure.typeinference.model.base.NodeUtils; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AttributeUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NameUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.TupleElement; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Use; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Value; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Block; import ch.hsr.ifs.pystructure.typeinference.model.scopes.BuiltInScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ModuleScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Scope; public class DefinitionVisitor extends StructuralVisitor { private final Module module; private ModuleScope moduleScope; private Stack<Block> blocks; private List<Use> uses; public DefinitionVisitor(Module module) { this.module = module; this.moduleScope = new ModuleScope(new BuiltInScope(), module); this.blocks = new Stack<Block>(); this.uses = module.getContainedUses(); } public void run() { try { super.run(module); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Object visitModule(org.python.pydev.parser.jython.ast.Module node) throws Exception { blocks.push(moduleScope); super.visitModule(node); visitChildren(module); blocks.pop(); moduleScope.connectGlobals(); module.getDefinitions().addAll(moduleScope.getCurrentBlockDefinitions()); return null; } @Override public Object visitClassDef(ClassDef node) throws Exception { Class klass = getDefinitionFor(node); if (isFirstVisit(klass)) { addDefinition(klass); } else { blocks.push(new Scope(getBlock(), klass)); super.visitClassDef(node); visitChildren(klass); blocks.pop(); } return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { Function function = getDefinitionFor(node); if (isFirstVisit(function)) { /* * TODO: What about this? * * global func * def func(): * print "I'm global" */ addDefinition(function); } else { Scope functionScope = new Scope(getBlock(), function); blocks.push(functionScope); addArgumentDefinitions(node.args, function); super.visitFunctionDef(node); visitChildren(function); blocks.pop(); } return null; } private void addArgumentDefinitions(argumentsType args, Function function) { int firstDefault = args.args.length - args.defaults.length; for (int position = 0; position < args.args.length; ++position) { exprType argument = args.args[position]; if (argument instanceof Name) { String name = ((Name) argument).id; exprType defaultValue = null; if (position >= firstDefault) { defaultValue = args.defaults[position - firstDefault]; } addDefinition(new Argument(module, name, argument, position, defaultValue, function)); } } } @Override public Object visitAssign(Assign node) throws Exception { node.value.accept(this); node.value.parent = node; for (exprType target : node.targets) { Map<String, Value> values = getValues(target, node.value); for (Entry<String, Value> entry : values.entrySet()) { String name = entry.getKey(); Definition d = new AssignDefinition(module, name, node, entry.getValue()); addDefinition(d); } target.accept(this); target.parent = node; } return null; } // TODO: Move this out of DefinitionVisitor private Map<String, Value> getValues(exprType target, exprType value) { Map<String, Value> values = new HashMap<String, Value>(); LinkedList<Integer> indexes = new LinkedList<Integer>(); getValues(values, indexes, target, value); return values; } private void getValues(Map<String, Value> values, LinkedList<Integer> indexes, exprType target, exprType value) { if (target instanceof Tuple) { Tuple tuple = (Tuple) target; for (int i = 0; i < tuple.elts.length; i++) { exprType element = tuple.elts[i]; indexes.addLast(i); getValues(values, indexes, element, value); indexes.removeLast(); } } else if (target instanceof Name) { String name = ((Name) target).id; Value v; if (indexes.size() == 0) { v = new Value(value); } else { v = new TupleElement(value, indexes); } values.put(name, v); } } @Override public Object visitName(Name node) throws Exception { NameUse use = new NameUse(node.id, node, module); addNameUse(use); super.visitName(node); return null; } @Override public Object visitNameTok(NameTok node) throws Exception { NameUse use = new NameUse(node.id, node, module); addNameUse(use); super.visitNameTok(node); return null; } @Override public Object visitAttribute(Attribute node) throws Exception { uses.add(new AttributeUse(node, module)); node.parent = stack.peek(); stack.push(node); // Don't visit node.attr, we don't want a NameUse for it. node.attr.parent = node; node.value.accept(this); stack.pop(); return null; } @Override public Object visitGlobal(Global node) throws Exception { for (NameTokType nameTok : node.names) { String name = NodeUtils.getId(nameTok); getScope().setGlobal(name); nameTok.accept(this); } return null; } @Override public Object visitIf(If node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitFor(For node) throws Exception { Block parent = getBlock(); node.iter.accept(this); Block bodyBlock = new Block(parent); // TODO: What about tuples? if (node.target instanceof Name) { String name = ((Name) node.target).id; Definition loopVariable = new LoopVariableDefinition(module, name, node); bodyBlock.setCurrentDefinition(loopVariable); parent.addToCurrentDefinitions(loopVariable); } node.target.accept(this); visitBlock(bodyBlock, node.body); Block orelseBlock = new Block(parent); // Definitions may flow from the body to the else block. orelseBlock.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitWhile(While node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); orelseBlock.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); visitBlock(orelseBlock, node.orelse); parent.addToCurrentDefinitions(bodyBlock.getCurrentBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitTryExcept(TryExcept node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); for (excepthandlerType handler : node.handlers) { Block handlerBlock = new Block(parent); handlerBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); // TODO: What about tuples? if (handler.name instanceof Name) { String name = ((Name) handler.name).id; ExceptDefinition definition = new ExceptDefinition(module, name, handler); handlerBlock.setCurrentDefinition(definition); } visitBlock(handlerBlock, handler.body); parent.addToCurrentDefinitions(handlerBlock.getCurrentBlockDefinitions()); } orelseBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); visitBlock(orelseBlock, node.orelse); // We need to add all definitions of the block, because we don't know // where the exception was thrown, it could be between two definitions // of the same name. parent.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); parent.addToCurrentDefinitions(orelseBlock.getCurrentBlockDefinitions()); return null; } @Override public Object visitTryFinally(TryFinally node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block finallyBlock = new Block(parent); visitBlock(bodyBlock, node.body); finallyBlock.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); visitBlock(finallyBlock, node.finalbody); parent.addToCurrentDefinitions(bodyBlock.getBlockDefinitions()); // Overwrite the current definitions, because we don't know whether an // exception occurred or not. for (Definition definition : finallyBlock.getCurrentBlockDefinitions()) { parent.setCurrentDefinition(definition); } return null; } private void visitBlock(Block block, stmtType[] body) throws Exception { if (body == null) { return; } blocks.push(block); for (stmtType statement : body) { statement.accept(this); } blocks.pop(); } private void visitBlock(Block block, suiteType suite) throws Exception { if (suite != null) { visitBlock(block, suite.body); } } private void addDefinition(Definition definition) { if (getScope().isGlobal(definition.getName())) { moduleScope.addGlobalDefinition(definition); } else { getBlock().setCurrentDefinition(definition); } } private void addNameUse(NameUse use) { List<Definition> definitions = getBlock().getCurrentDefinitions(use.getName()); use.addDefinitions(definitions); if (getScope() == moduleScope || getScope().isGlobal(use.getName())) { moduleScope.addGlobalNameUse(use); } uses.add(use); } private Block getBlock() { return blocks.peek(); } private Scope getScope() { Block scope = getBlock(); while (!(scope instanceof Scope)) { scope = scope.getParent(); } return (Scope) scope; } public List<Use> getUses() { return uses; } /* import stuff */ /* * Examples: * * import pkg.module * import pkg.module as module * import pkg.module, pkg2.module2 * import pkg * * Doesn't work: * * import pkg.module.Class */ @Override public Object visitImport(Import node) throws Exception { for (aliasType entry : node.names) { ImportDefinition definition; if (entry.asname == null) { /* import package.module # package -> package */ NamePath fullPath = new NamePath(NodeUtils.getId(entry.name)); NamePath name = new NamePath(fullPath.getFirstPart()); definition = new ImportDefinition(module, node, name, null, name.toString()); } else { /* import package.module as alias # alias -> package.module */ String alias = NodeUtils.getId(entry.asname); NamePath path = new NamePath(NodeUtils.getId(entry.name)); definition = new ImportDefinition(module, node, path, null, alias); } addDefinition(definition); } return null; } /* * Examples: * * from pkg.module import Class * from pkg.module import Class as C1, ClassTwo as C2 * from pkg.module import * # grrr * from pkg import module * from pkg import * # doesn't import all modules, but everything in __init__.py * from .module import Class * from . import module * * TODO: Support wildcard imports */ @Override public Object visitImportFrom(ImportFrom node) throws Exception { NamePath path = new NamePath(NodeUtils.getId(node.module)); for (aliasType entry : node.names) { String element = NodeUtils.getId(entry.name); String alias = NodeUtils.getId(entry.asname == null ? entry.name : entry.asname); ImportDefinition definition = new ImportDefinition(module, node, path, element, alias, node.level); addDefinition(definition); if (entry.asname != null) { /* * In the following case, we have to add a name use for Class, * because otherwise it can't be found by reference finders: * * from module import Class as Alias */ NameUse use = new NameUse(element, entry.name, this.module); use.addDefinition(definition); addNameUse(use); } } return null; } }
Removed unconnected NameUses.
src/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java
Removed unconnected NameUses.
<ide><path>rc/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java <ide> Definition loopVariable = new LoopVariableDefinition(module, name, node); <ide> bodyBlock.setCurrentDefinition(loopVariable); <ide> parent.addToCurrentDefinitions(loopVariable); <del> } <del> <del> node.target.accept(this); <add> <add> node.target.accept(this); <add> } <ide> <ide> visitBlock(bodyBlock, node.body); <ide> Block orelseBlock = new Block(parent); <ide> */ <ide> NameUse use = new NameUse(element, entry.name, this.module); <ide> use.addDefinition(definition); <del> addNameUse(use); <add> uses.add(use); <ide> } <ide> } <ide>
Java
apache-2.0
7d69065c7d31a493f861714108fee4c42d1ac4da
0
mechdome/Drinks,amasciul/Drinks,vbarthel-fr/Drinks,vbarthel-fr/Drinks,amasciul/Drinks,amasciul/Drinks,mechdome/Drinks
package fr.masciulli.drinks.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.TextView; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnItemClick; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import fr.masciulli.drinks.R; import fr.masciulli.drinks.activity.DrinkDetailActivity; import fr.masciulli.drinks.activity.MainActivity; import fr.masciulli.drinks.adapter.DrinksListAdapter; import fr.masciulli.drinks.data.DrinksProvider; import fr.masciulli.drinks.model.Drink; import fr.masciulli.drinks.view.ViewPagerScrollListener; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class DrinksListFragment extends Fragment implements Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener { private static final String STATE_LIST = "drinks_list"; @InjectView(R.id.list) ListView mListView; @InjectView(R.id.progressbar) ProgressBar mProgressBar; @InjectView(android.R.id.empty) View mEmptyView; private DrinksListAdapter mListAdapter; private boolean mLoadingError = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); final View root = inflater.inflate(R.layout.fragment_drinks_list, container, false); ButterKnife.inject(this, root); mListView.setEmptyView(mEmptyView); mListAdapter = new DrinksListAdapter(getActivity()); mListView.setAdapter(mListAdapter); if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_LIST)) { List<Drink> savedDrinks = savedInstanceState.getParcelableArrayList(STATE_LIST); mListAdapter.update(savedDrinks); } else { refresh(); } } else { refresh(); } return root; } @OnItemClick(R.id.list) public void openDrinkDetail(View view, int position) { Drink drink = mListAdapter.getItem(position); // Data needed for animations in sub activity int[] screenLocation = new int[2]; view.getLocationOnScreen(screenLocation); int orientation = getResources().getConfiguration().orientation; Intent intent = new Intent(getActivity(), DrinkDetailActivity.class); intent. putExtra("drink_name", drink.name). putExtra("drink_imageurl", drink.imageUrl). putExtra("drink_id", drink.id). putExtra("top", screenLocation[1]). putExtra("height", view.getHeight()). putExtra("orientation", orientation); startActivity(intent); if (!getResources().getBoolean(R.bool.dualpane)) { getActivity().overridePendingTransition(0, 0); } } @Override public void success(List<Drink> drinks, Response response) { mLoadingError = false; if (getActivity() == null) return; mListView.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); mListAdapter.update(drinks); } @Override public void failure(RetrofitError retrofitError) { mLoadingError = true; if (getActivity() == null) return; mProgressBar.setVisibility(View.GONE); mEmptyView.setVisibility(View.VISIBLE); ((MainActivity) getActivity()).setRefreshActionVisible(true); if (retrofitError.isNetworkError()) { Crouton.makeText(getActivity(), getString(R.string.network_error), Style.ALERT).show(); } else { Crouton.makeText(getActivity(), getString(R.string.list_loading_failed), Style.ALERT).show(); } } @Override public void onScroll(int position, float positionOffset, int positionOffsetPixels) { int first = mListView.getFirstVisiblePosition(); int last = mListView.getLastVisiblePosition(); for (int i = 0; i <= last - first; i++) { View itemRoot = mListView.getChildAt(i); if (itemRoot == null) continue; TextView nameView = (TextView) itemRoot.findViewById(R.id.name); // TODO get screenWidth somewhere else (always the same) int screenWidth = itemRoot.getWidth(); int textWidth = nameView.getWidth(); nameView.setRight(Math.round(screenWidth + positionOffset * textWidth)); nameView.setLeft(Math.round(screenWidth - textWidth + positionOffset * textWidth)); } } private void refresh() { mProgressBar.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.GONE); ((MainActivity) getActivity()).setRefreshActionVisible(false); DrinksProvider.getAllDrinks(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.drinks_list, menu); // SearchView configuration final MenuItem searchMenuItem = menu.findItem(R.id.search); if (mLoadingError) { ((MainActivity) getActivity()).setRefreshActionVisible(true); } SearchView searchView = (SearchView) searchMenuItem.getActionView(); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(this); } @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { if (mListView != null) { mListAdapter.getFilter().filter(s); } return true; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mListAdapter.getCount() > 0) { outState.putParcelableArrayList(STATE_LIST, mListAdapter.getDrinks()); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.retry: refresh(); return true; } return super.onOptionsItemSelected(item); } }
Drinks/src/main/java/fr/masciulli/drinks/fragment/DrinksListFragment.java
package fr.masciulli.drinks.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.TextView; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import fr.masciulli.drinks.R; import fr.masciulli.drinks.activity.DrinkDetailActivity; import fr.masciulli.drinks.activity.MainActivity; import fr.masciulli.drinks.adapter.DrinksListAdapter; import fr.masciulli.drinks.data.DrinksProvider; import fr.masciulli.drinks.model.Drink; import fr.masciulli.drinks.view.ViewPagerScrollListener; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class DrinksListFragment extends Fragment implements AdapterView.OnItemClickListener, Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener { private static final String STATE_LIST = "drinks_list"; @InjectView(R.id.list) ListView mListView; @InjectView(R.id.progressbar) ProgressBar mProgressBar; @InjectView(android.R.id.empty) View mEmptyView; private DrinksListAdapter mListAdapter; private boolean mLoadingError = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); final View root = inflater.inflate(R.layout.fragment_drinks_list, container, false); ButterKnife.inject(this, root); mListView.setEmptyView(mEmptyView); mListView.setOnItemClickListener(this); mListAdapter = new DrinksListAdapter(getActivity()); mListView.setAdapter(mListAdapter); if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_LIST)) { List<Drink> savedDrinks = savedInstanceState.getParcelableArrayList(STATE_LIST); mListAdapter.update(savedDrinks); } else { refresh(); } } else { refresh(); } return root; } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Drink drink = mListAdapter.getItem(i); // Data needed for animations in sub activity int[] screenLocation = new int[2]; view.getLocationOnScreen(screenLocation); int orientation = getResources().getConfiguration().orientation; Intent intent = new Intent(getActivity(), DrinkDetailActivity.class); intent. putExtra("drink_name", drink.name). putExtra("drink_imageurl", drink.imageUrl). putExtra("drink_id", drink.id). putExtra("top", screenLocation[1]). putExtra("height", view.getHeight()). putExtra("orientation", orientation); startActivity(intent); if (!getResources().getBoolean(R.bool.dualpane)) { getActivity().overridePendingTransition(0, 0); } } @Override public void success(List<Drink> drinks, Response response) { mLoadingError = false; if (getActivity() == null) return; mListView.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); mListAdapter.update(drinks); } @Override public void failure(RetrofitError retrofitError) { mLoadingError = true; if (getActivity() == null) return; mProgressBar.setVisibility(View.GONE); mEmptyView.setVisibility(View.VISIBLE); ((MainActivity) getActivity()).setRefreshActionVisible(true); if (retrofitError.isNetworkError()) { Crouton.makeText(getActivity(), getString(R.string.network_error), Style.ALERT).show(); } else { Crouton.makeText(getActivity(), getString(R.string.list_loading_failed), Style.ALERT).show(); } } @Override public void onScroll(int position, float positionOffset, int positionOffsetPixels) { int first = mListView.getFirstVisiblePosition(); int last = mListView.getLastVisiblePosition(); for (int i = 0; i <= last - first; i++) { View itemRoot = mListView.getChildAt(i); if (itemRoot == null) continue; TextView nameView = (TextView) itemRoot.findViewById(R.id.name); // TODO get screenWidth somewhere else (always the same) int screenWidth = itemRoot.getWidth(); int textWidth = nameView.getWidth(); nameView.setRight(Math.round(screenWidth + positionOffset * textWidth)); nameView.setLeft(Math.round(screenWidth - textWidth + positionOffset * textWidth)); } } private void refresh() { mProgressBar.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.GONE); ((MainActivity) getActivity()).setRefreshActionVisible(false); DrinksProvider.getAllDrinks(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.drinks_list, menu); // SearchView configuration final MenuItem searchMenuItem = menu.findItem(R.id.search); if (mLoadingError) { ((MainActivity) getActivity()).setRefreshActionVisible(true); } SearchView searchView = (SearchView) searchMenuItem.getActionView(); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(this); } @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { if (mListView != null) { mListAdapter.getFilter().filter(s); } return true; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mListAdapter.getCount() > 0) { outState.putParcelableArrayList(STATE_LIST, mListAdapter.getDrinks()); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.retry: refresh(); return true; } return super.onOptionsItemSelected(item); } }
Use ButterKnife interaction tool (Drinks list)
Drinks/src/main/java/fr/masciulli/drinks/fragment/DrinksListFragment.java
Use ButterKnife interaction tool (Drinks list)
<ide><path>rinks/src/main/java/fr/masciulli/drinks/fragment/DrinksListFragment.java <ide> import android.view.MenuItem; <ide> import android.view.View; <ide> import android.view.ViewGroup; <del>import android.widget.AdapterView; <ide> import android.widget.ListView; <ide> import android.widget.ProgressBar; <ide> import android.widget.SearchView; <ide> <ide> import butterknife.ButterKnife; <ide> import butterknife.InjectView; <add>import butterknife.OnItemClick; <ide> import de.keyboardsurfer.android.widget.crouton.Crouton; <ide> import de.keyboardsurfer.android.widget.crouton.Style; <ide> import fr.masciulli.drinks.R; <ide> import retrofit.RetrofitError; <ide> import retrofit.client.Response; <ide> <del>public class DrinksListFragment extends Fragment implements AdapterView.OnItemClickListener, Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener { <add>public class DrinksListFragment extends Fragment implements Callback<List<Drink>>, ViewPagerScrollListener, SearchView.OnQueryTextListener { <ide> private static final String STATE_LIST = "drinks_list"; <ide> <ide> @InjectView(R.id.list) ListView mListView; <ide> ButterKnife.inject(this, root); <ide> <ide> mListView.setEmptyView(mEmptyView); <del> mListView.setOnItemClickListener(this); <ide> mListAdapter = new DrinksListAdapter(getActivity()); <ide> mListView.setAdapter(mListAdapter); <ide> <ide> return root; <ide> } <ide> <del> @Override <del> public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { <del> Drink drink = mListAdapter.getItem(i); <add> @OnItemClick(R.id.list) <add> public void openDrinkDetail(View view, int position) { <add> Drink drink = mListAdapter.getItem(position); <ide> <ide> // Data needed for animations in sub activity <ide> int[] screenLocation = new int[2];
Java
apache-2.0
503bdf356079d42bbd15ffedbd75d03fce7f4d98
0
uPhyca/idobata4j
/* * Copyright (C) 2014 uPhyca Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uphyca.idobata.transform; /** * Indicate that conversion was unable to complete successfully. * * @author Sosuke Masui ([email protected]) */ public class ConversionException extends Exception { public ConversionException() { } public ConversionException(String message) { super(message); } public ConversionException(String message, Throwable cause) { super(message, cause); } public ConversionException(Throwable cause) { super(cause); } }
idobata4j-core/src/main/java/com/uphyca/idobata/transform/ConversionException.java
/* * Copyright (C) 2014 uPhyca Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uphyca.idobata.transform; /** * Indicate that conversion was unable to complete successfully. * * @author Sosuke Masui ([email protected]) */ public class ConversionException extends Exception { public ConversionException() { } public ConversionException(String message) { super(message); } public ConversionException(String message, Throwable cause) { super(message, cause); } public ConversionException(Throwable cause) { super(cause); } public ConversionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
Fixed compile issue on jdk6: Caused by: idobata4j-core/src/main/java/com/uphyca/idobata/transform/ConversionException.java:42: cannot find symbol :idobata4j-core:compileJavabol : constructor Exception(java.lang.String,java.lang.Throwable,boolean,boolean)
idobata4j-core/src/main/java/com/uphyca/idobata/transform/ConversionException.java
Fixed compile issue on jdk6: Caused by: idobata4j-core/src/main/java/com/uphyca/idobata/transform/ConversionException.java:42: cannot find symbol :idobata4j-core:compileJavabol : constructor Exception(java.lang.String,java.lang.Throwable,boolean,boolean)
<ide><path>dobata4j-core/src/main/java/com/uphyca/idobata/transform/ConversionException.java <ide> public ConversionException(Throwable cause) { <ide> super(cause); <ide> } <del> <del> public ConversionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { <del> super(message, cause, enableSuppression, writableStackTrace); <del> } <ide> }
Java
apache-2.0
7b1ae51739adaba7c06a1275a9fe878739a3c017
0
hsjawanda/gae-objectify-utils
/** * */ package com.hsjawanda.gaeobjectify.util; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.defaultString; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.leftPad; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.trimToEmpty; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import lombok.Builder; /** * @author Harshdeep S Jawanda <[email protected]> * */ @Builder public class Messages { private static Logger LOG; private static final String NL = System.lineSeparator(); private static DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("dd MMM yyy HH:mm:ss.SSS") .withZone(Constants.IST_TZ_ID); @Builder.Default private int initialCapacity = 200; private final List<String> messages = new ArrayList<>(); private boolean serialNumbers; private boolean timestamps; @SuppressWarnings("unused") private static Logger log() { if (null == LOG) { LOG = Logger.getLogger(Messages.class.getName()); } return LOG; } public Messages add(String message) { this.messages.add(addTimestampIfNeeded(message)); return this; } public Messages add(String formatSpecifier, Object... args) { this.messages.add(addTimestampIfNeeded(String.format(formatSpecifier, args))); return this; } public String printable(String prefix) { StringBuilder message = new StringBuilder(this.initialCapacity).append(NL).append(trimToEmpty(prefix)); int counter = 0, padding = -1; for (String mesg : this.messages) { message.append(NL); if (this.serialNumbers) { if (padding == -1) { padding = ((int) Math.log10(this.messages.size())) + 1; } message.append(leftPad(Integer.toString(++counter), padding)).append(". "); } message.append(mesg); } return message.toString(); } private String addTimestampIfNeeded(String mainMesg) { return this.timestamps ? new StringBuilder(100).append(TIMESTAMP.format(Instant.now())).append(": ") .append(mainMesg).toString() : defaultString(mainMesg, "null"); } }
src/main/java/com/hsjawanda/gaeobjectify/util/Messages.java
/** * */ package com.hsjawanda.gaeobjectify.util; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.defaultString; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.leftPad; import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.trimToEmpty; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import lombok.Builder; /** * @author Harshdeep S Jawanda <[email protected]> * */ @Builder public class Messages { private static Logger LOG; private static final String NL = System.lineSeparator(); private static DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("dd MMM yyy HH:mm:ss.SSS") .withZone(Constants.IST_TZ_ID); @Builder.Default private int initialCapacity = 200; private final List<String> messages = new ArrayList<>(); private boolean serialNumbers; private boolean timestamps; @SuppressWarnings("unused") private static Logger log() { if (null == LOG) { LOG = Logger.getLogger(Messages.class.getName()); } return LOG; } public Messages add(String message) { this.messages.add(addTimestampIfNeeded(message)); return this; } public Messages add(String formatSpecifier, Object... args) { this.messages.add(addTimestampIfNeeded(String.format(formatSpecifier, args))); return this; } public String printable(String prefix) { StringBuilder message = new StringBuilder(this.initialCapacity).append(trimToEmpty(prefix)).append(NL); int counter = 0, padding = -1; for (String mesg : this.messages) { message.append(NL); if (this.serialNumbers) { if (padding == -1) { padding = ((int) Math.log10(this.messages.size())) + 1; } message.append(leftPad(Integer.toString(++counter), padding)).append(". "); } message.append(mesg); } return message.toString(); } private String addTimestampIfNeeded(String mainMesg) { return this.timestamps ? new StringBuilder(100).append(TIMESTAMP.format(Instant.now())).append(": ") .append(mainMesg).toString() : defaultString(mainMesg, "null"); } }
Minor formatting update.
src/main/java/com/hsjawanda/gaeobjectify/util/Messages.java
Minor formatting update.
<ide><path>rc/main/java/com/hsjawanda/gaeobjectify/util/Messages.java <ide> } <ide> <ide> public String printable(String prefix) { <del> StringBuilder message = new StringBuilder(this.initialCapacity).append(trimToEmpty(prefix)).append(NL); <add> StringBuilder message = new StringBuilder(this.initialCapacity).append(NL).append(trimToEmpty(prefix)); <ide> int counter = 0, padding = -1; <ide> for (String mesg : this.messages) { <ide> message.append(NL);
Java
apache-2.0
8c740891caadef796c6bbcc8bb2c342eea85318d
0
nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/wfswarm-example-arjuna-old,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch
import java.io.*; import java.util.*; public class Intcode { public static final String DELIMITER = ","; public static final String INITIALISED_MEMORY = "0"; /* * This implementation is stateless other than being placed * into debug mode where it will output whatever action it * takes. */ public Intcode (Vector<String> values, int input, boolean debug) { _debug = debug; _instructionPointer = 0; _currentState = new Vector<String>(); _memory = new Vector<String>(values); _initialInput = input; _status = Status.CREATED; _relativeBase = 0; } public final boolean hasHalted () { return (_status == Status.HALTED); } public final Vector<String> currentState () { return _currentState; } public final int status () { return _status; } /** * Execute the commands given. * * @param initialInput1 initial input param 1 * @param initialInput2 initial input param 2 * @param output any output that may be generated before termination. * @return true if the program code has completed, false otherwise. */ // maybe move the initial parameter to the constructor? Or change this to a Vector/array for multiple states? public Vector<String> executeProgram () { if (hasHalted()) { if (_debug) System.out.println("Intocde computer has halted!"); return _currentState; } if (_debug) System.out.println("Intcode input <"+_initialInput+"> and instruction pointer: "+_instructionPointer); // change to a while loop on _instructionPointer while (!hasHalted()) { System.out.println("**instruction pointer "+_instructionPointer); String str = getOpcode(_memory.elementAt(_instructionPointer)); int opcode = Integer.valueOf(str); int[] modes = ParameterMode.getModes(_memory.elementAt(_instructionPointer)); if (_debug) { System.out.println("\nWorking on element "+_instructionPointer+" which is command "+Instructions.commandToString(opcode)+ " with parameter modes ..."); ParameterMode.printModes(modes); } /* * Now factor in the parameter modes. */ switch (opcode) { case Instructions.ADD: { /* * Opcode 1 adds together numbers read from two positions * and stores the result in a third position. The three integers * immediately after the opcode tell you these three positions - the * first two indicate the positions from which you should read the * input values, and the third indicates the position at which * the output should be stored. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Integer.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } if (_debug) System.out.println("Adding "+param1+" and "+param2); long sum = param1+param2; if (_debug) System.out.println("Storing "+sum+" at position "+param3); System.out.println("**have "+param1+" "+param2+" "+param3); setValue(param3, String.valueOf(sum)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.MULTIPLY: { /* * Opcode 2 works exactly like opcode 1, except it multiplies the * two inputs instead of adding them. Again, the three integers after * the opcode indicate where the inputs and outputs are, not their values. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } if (_debug) System.out.println("Multiplying "+param1+" and "+param2); long product = Long.valueOf(param1)*Long.valueOf(param2); if (_debug) System.out.println("Storing "+product+" at position "+param3); System.out.println("**have "+param1+" "+param2+" "+param3); setValue(param3, String.valueOf(product)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.INPUT_AND_STORE: { /* * Opcode 3 takes a single integer as input and saves it to * the position given by its only parameter. */ int param1 = Integer.valueOf(getValue(_instructionPointer+1)); System.out.println("**have "+param1); if (_debug) System.out.println("Storing "+_initialInput+" at position "+param1); setValue(param1, String.valueOf(_initialInput)); _instructionPointer += 2; // move the pointer on. System.out.println("**after store the pointer is "+_instructionPointer); } break; case Instructions.OUTPUT: { /* * Opcode 4 outputs the value of its only parameter. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); if (modes[0] == ParameterMode.IMMEDIATE_MODE) _currentState.add(new String(getValue(_instructionPointer+1))); else { if (modes[0] == ParameterMode.RELATIVE_MODE) _currentState.add(new String(getValue((int) param1 + _relativeBase))); else _currentState.add(new String(getValue((int) param1))); } System.out.println("**have "+param1); if (_debug) System.out.println("Addomg value "+_currentState+" from entry "+param1+" to output state (memory)."); _instructionPointer += 2; // move the pointer on. _status = Status.PAUSED; return _currentState; } // break; case Instructions.JUMP_IF_TRUE: { /* * If the first parameter is non-zero, it sets the instruction pointer to * the value from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) System.out.println("Checking "+param1+" != 0 and might jump to "+param2); if (param1 != 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.JUMP_IF_FALSE: { /* * If the first parameter is zero, it sets the instruction pointer to the value * from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) System.out.println("Checking "+param1+" == 0 and might jump to "+param2); if (param1 == 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.LESS_THAN: { /* * If the first parameter is less than the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) { System.out.println("Checking whether "+param1+" < "+param2); System.out.print("Storing "); } if (param1 < param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); _instructionPointer += 4; // move the pointer on. } break; case Instructions.EQUALS: { /* * If the first parameter is equal to the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) { System.out.println("Checking whether "+param1+" is equal to "+param2); System.out.print("Storing "); } if (param1 == param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); _instructionPointer += 4; // move the pointer on. } break; case Instructions.RELATIVE_BASE: { /* * The relative base increases (or decreases, if the value is negative) * by the value of the parameter. */ _relativeBase += Integer.valueOf(getValue(_instructionPointer+1)); // assume integer for array size System.out.println("**have "+getValue(_instructionPointer+1)); if (_debug) System.out.println("Relative base now "+_relativeBase); _instructionPointer += 2; } break; case Instructions.HALT: { /* * Means that the program is finished and should immediately halt. */ if (_debug) System.out.println("Halting execution."); System.out.println("**have 99"); _instructionPointer = _memory.size(); _status = Status.HALTED; return _currentState; } default: { System.out.println("Unknown opcode "+str+" encountered"); _instructionPointer = _memory.size(); // stop any further execution. _status = Status.HALTED; } } _status = Status.RUNNING; } return _currentState; } // these methods ensure capacity is available private final String getValue (int i) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); String str = _memory.elementAt(i); if (str == null) { str = INITIALISED_MEMORY; _memory.set(i, str); } return str; } private final void setValue (int i, String str) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); _memory.set(i, str); } private String getOpcode (String digits) { String opcode = null; if ((digits != null) && (digits.length() > 2)) opcode = digits.substring(digits.length()-2); else opcode = digits; return opcode; } private boolean _debug; private int _instructionPointer; private Vector<String> _currentState; private Vector<String> _memory; private int _initialInput; private int _status; private int _relativeBase; private static final int EXPANSION_FACTOR = 10; // if we need to increase memory, add a bit more to reduce multiple back-to-back expansions }
AdventOfCode/2019/day9/Intcode.java
import java.io.*; import java.util.*; public class Intcode { public static final String DELIMITER = ","; public static final String INITIALISED_MEMORY = "0"; /* * This implementation is stateless other than being placed * into debug mode where it will output whatever action it * takes. */ public Intcode (Vector<String> values, int input, boolean debug) { _debug = debug; _instructionPointer = 0; _currentState = new Vector<String>(); _memory = new Vector<String>(values); _initialInput = input; _status = Status.CREATED; _relativeBase = 0; } public final boolean hasHalted () { return (_status == Status.HALTED); } public final Vector<String> currentState () { return _currentState; } public final int status () { return _status; } /** * Execute the commands given. * * @param initialInput1 initial input param 1 * @param initialInput2 initial input param 2 * @param output any output that may be generated before termination. * @return true if the program code has completed, false otherwise. */ // maybe move the initial parameter to the constructor? Or change this to a Vector/array for multiple states? public Vector<String> executeProgram () { if (hasHalted()) { if (_debug) System.out.println("Intocde computer has halted!"); return _currentState; } if (_debug) System.out.println("Intcode input <"+_initialInput+"> and instruction pointer: "+_instructionPointer); // change to a while loop on _instructionPointer while (!hasHalted()) { System.out.println("**instruction pointer "+_instructionPointer); String str = getOpcode(_memory.elementAt(_instructionPointer)); int opcode = Integer.valueOf(str); int[] modes = ParameterMode.getModes(_memory.elementAt(_instructionPointer)); if (_debug) { System.out.println("\nWorking on element "+_instructionPointer+" which is command "+Instructions.commandToString(opcode)+ " with parameter modes ..."); ParameterMode.printModes(modes); } /* * Now factor in the parameter modes. */ switch (opcode) { case Instructions.ADD: { /* * Opcode 1 adds together numbers read from two positions * and stores the result in a third position. The three integers * immediately after the opcode tell you these three positions - the * first two indicate the positions from which you should read the * input values, and the third indicates the position at which * the output should be stored. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Integer.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } if (_debug) System.out.println("Adding "+param1+" and "+param2); long sum = param1+param2; if (_debug) System.out.println("Storing "+sum+" at position "+param3); System.out.println("**have "+param1+" "+param2+" "+param3); setValue(param3, String.valueOf(sum)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.MULTIPLY: { /* * Opcode 2 works exactly like opcode 1, except it multiplies the * two inputs instead of adding them. Again, the three integers after * the opcode indicate where the inputs and outputs are, not their values. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } if (_debug) System.out.println("Multiplying "+param1+" and "+param2); long product = Long.valueOf(param1)*Long.valueOf(param2); if (_debug) System.out.println("Storing "+product+" at position "+param3); System.out.println("**have "+param1+" "+param2+" "+param3); setValue(param3, String.valueOf(product)); _instructionPointer += 4; // move the pointer on. } break; case Instructions.INPUT_AND_STORE: { /* * Opcode 3 takes a single integer as input and saves it to * the position given by its only parameter. */ int param1 = Integer.valueOf(getValue(_instructionPointer+1)); System.out.println("**have "+param1); if (_debug) System.out.println("Storing "+_initialInput+" at position "+param1); setValue(param1, String.valueOf(_initialInput)); _instructionPointer += 2; // move the pointer on. System.out.println("**after store the pointer is "+_instructionPointer); } break; case Instructions.OUTPUT: { /* * Opcode 4 outputs the value of its only parameter. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); if (modes[0] == ParameterMode.IMMEDIATE_MODE) _currentState.add(new String(getValue(_instructionPointer+1))); else { if (modes[0] == ParameterMode.RELATIVE_MODE) _currentState.add(new String(getValue((int) param1 + _relativeBase))); else _currentState.add(new String(getValue((int) param1))); } System.out.println("**have "+param1); if (_debug) System.out.println("Addomg value "+_currentState+" from entry "+param1+" to output state (memory)."); _instructionPointer += 2; // move the pointer on. _status = Status.PAUSED; return _currentState; } // break; case Instructions.JUMP_IF_TRUE: { /* * If the first parameter is non-zero, it sets the instruction pointer to * the value from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) System.out.println("Checking "+param1+" != 0 and might jump to "+param2); if (param1 != 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.JUMP_IF_FALSE: { /* * If the first parameter is zero, it sets the instruction pointer to the value * from the second parameter. Otherwise, it does nothing. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) System.out.println("Checking "+param1+" == 0 and might jump to "+param2); if (param1 == 0) { _instructionPointer = (int) param2; if (_debug) System.out.println("Will jump to "+param2); } else _instructionPointer += 3; } break; case Instructions.LESS_THAN: { /* * If the first parameter is less than the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ long param1 = Long.valueOf(getValue(_instructionPointer+1)); long param2 = Long.valueOf(getValue(_instructionPointer+2)); int param3 = Integer.valueOf(getValue(_instructionPointer+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) { System.out.println("Checking whether "+param1+" < "+param2); System.out.print("Storing "); } if (param1 < param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); i = i+3; // move the pointer on. } break; case Instructions.EQUALS: { /* * If the first parameter is equal to the second parameter, it stores 1 * in the position given by the third parameter. Otherwise, it stores 0. */ long param1 = Long.valueOf(getValue(i+1)); long param2 = Long.valueOf(getValue(i+2)); int param3 = Integer.valueOf(getValue(i+3)); if (modes[0] == ParameterMode.POSITION_MODE) param1 = Long.valueOf(getValue((int) param1)); else { if (modes[0] == ParameterMode.RELATIVE_MODE) param1 = Long.valueOf(getValue((int) param1 + _relativeBase)); } if (modes[1] == ParameterMode.POSITION_MODE) param2 = Long.valueOf(getValue((int) param2)); else { if (modes[1] == ParameterMode.RELATIVE_MODE) param2 = Long.valueOf(getValue((int) param2 + _relativeBase)); } System.out.println("**have "+param1+" "+param2); if (_debug) { System.out.println("Checking whether "+param1+" is equal to "+param2); System.out.print("Storing "); } if (param1 == param2) { if (_debug) System.out.print("1"); setValue(param3, "1"); } else { if (_debug) System.out.print("0"); setValue(param3, "0"); } if (_debug) System.out.println(" at location "+param3); i = i+3; // move the pointer on. } break; case Instructions.RELATIVE_BASE: { /* * The relative base increases (or decreases, if the value is negative) * by the value of the parameter. */ _relativeBase += Integer.valueOf(getValue(i+1)); // assume integer for array size System.out.println("**have "+getValue(i+1)); if (_debug) System.out.println("Relative base now "+_relativeBase); i = i +1; } break; case Instructions.HALT: { /* * Means that the program is finished and should immediately halt. */ if (_debug) System.out.println("Halting execution."); System.out.println("**have 99"); _instructionPointer = _memory.size(); _status = Status.HALTED; return _currentState; } default: { System.out.println("Unknown opcode "+str+" encountered"); _instructionPointer = _memory.size(); // stop any further execution. _status = Status.HALTED; } } _status = Status.RUNNING; } return _currentState; } // these methods ensure capacity is available private final String getValue (int i) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); String str = _memory.elementAt(i); if (str == null) { str = INITIALISED_MEMORY; _memory.set(i, str); } return str; } private final void setValue (int i, String str) { if (_memory.size() <= i) _memory.setSize(i+EXPANSION_FACTOR); _memory.set(i, str); } private String getOpcode (String digits) { String opcode = null; if ((digits != null) && (digits.length() > 2)) opcode = digits.substring(digits.length()-2); else opcode = digits; return opcode; } private boolean _debug; private int _instructionPointer; private Vector<String> _currentState; private Vector<String> _memory; private int _initialInput; private int _status; private int _relativeBase; private static final int EXPANSION_FACTOR = 10; // if we need to increase memory, add a bit more to reduce multiple back-to-back expansions }
Update Intcode.java
AdventOfCode/2019/day9/Intcode.java
Update Intcode.java
<ide><path>dventOfCode/2019/day9/Intcode.java <ide> if (_debug) <ide> System.out.println(" at location "+param3); <ide> <del> i = i+3; // move the pointer on. <add> _instructionPointer += 4; // move the pointer on. <ide> } <ide> break; <ide> case Instructions.EQUALS: <ide> * in the position given by the third parameter. Otherwise, it stores 0. <ide> */ <ide> <del> long param1 = Long.valueOf(getValue(i+1)); <del> long param2 = Long.valueOf(getValue(i+2)); <del> int param3 = Integer.valueOf(getValue(i+3)); <add> long param1 = Long.valueOf(getValue(_instructionPointer+1)); <add> long param2 = Long.valueOf(getValue(_instructionPointer+2)); <add> int param3 = Integer.valueOf(getValue(_instructionPointer+3)); <ide> <ide> if (modes[0] == ParameterMode.POSITION_MODE) <ide> param1 = Long.valueOf(getValue((int) param1)); <ide> if (_debug) <ide> System.out.println(" at location "+param3); <ide> <del> i = i+3; // move the pointer on. <add> _instructionPointer += 4; // move the pointer on. <ide> } <ide> break; <ide> case Instructions.RELATIVE_BASE: <ide> * by the value of the parameter. <ide> */ <ide> <del> _relativeBase += Integer.valueOf(getValue(i+1)); // assume integer for array size <del> <del> System.out.println("**have "+getValue(i+1)); <add> _relativeBase += Integer.valueOf(getValue(_instructionPointer+1)); // assume integer for array size <add> <add> System.out.println("**have "+getValue(_instructionPointer+1)); <ide> <ide> if (_debug) <ide> System.out.println("Relative base now "+_relativeBase); <ide> <del> i = i +1; <add> _instructionPointer += 2; <ide> } <ide> break; <ide> case Instructions.HALT:
Java
apache-2.0
bab6c3aee1d28730d77ef8d2bd3d082c8054f4bc
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.service.impl; import java.util.ArrayList; import java.util.List; import javax.validation.Validator; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.Sample; import ca.corefacility.bioinformatics.irida.model.SequenceFile; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin; import ca.corefacility.bioinformatics.irida.model.joins.impl.SampleSequenceFileJoin; import ca.corefacility.bioinformatics.irida.repositories.CRUDRepository; import ca.corefacility.bioinformatics.irida.repositories.SampleRepository; import ca.corefacility.bioinformatics.irida.repositories.SequenceFileRepository; import ca.corefacility.bioinformatics.irida.service.SampleService; /** * Service class for managing {@link Sample}. * * @author Franklin Bristow <[email protected]> */ public class SampleServiceImpl extends CRUDServiceImpl<Long, Sample> implements SampleService { /** * Reference to {@link CRUDRepository} for managing {@link Sample}. */ private SampleRepository sampleRepository; /** * Reference to {@link SequenceFileRepository} for managing * {@link SequenceFile}. */ private SequenceFileRepository sequenceFileRepository; /** * Constructor. * * @param sampleRepository * the sample repository. * @param validator * validator. */ public SampleServiceImpl(SampleRepository sampleRepository, SequenceFileRepository sequenceFileRepository, Validator validator) { super(sampleRepository, validator, Sample.class); this.sampleRepository = sampleRepository; this.sequenceFileRepository = sequenceFileRepository; } /** * {@inheritDoc} */ @Override @PreAuthorize("hasRole('ROLE_USER')") public Sample create(Sample s) { return super.create(s); } /** * {@inheritDoc} */ @Override @Transactional public SampleSequenceFileJoin addSequenceFileToSample(Sample sample, SequenceFile sampleFile) { // confirm that both the sample and sequence file exist already, fail // fast if either don't exist if (!sampleRepository.exists(sample.getId())) { throw new IllegalArgumentException("Sample must be persisted before adding a sequence file."); } if (!sequenceFileRepository.exists(sampleFile.getId())) { throw new IllegalArgumentException("Sequence file must be persisted before adding to sample."); } // call the relationship repository to create the relationship between // the two entities. SampleSequenceFileJoin addFileToSample = sequenceFileRepository.addFileToSample(sample, sampleFile); return addFileToSample; } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public Sample getSampleForProject(Project project, Long identifier) throws EntityNotFoundException { Sample s = null; // confirm that the link between project and this identifier exists List<ProjectSampleJoin> samplesForProject = sampleRepository.getSamplesForProject(project); for (ProjectSampleJoin join : samplesForProject) { if (join.getObject().getId().equals(identifier)) { // load the sample from the database s = read(identifier); } } if (s == null) { throw new EntityNotFoundException("Join between the project and this identifier doesn't exist"); } // return sample to the caller return s; } /** * {@inheritDoc} */ @Override @Transactional public void removeSequenceFileFromSample(Sample sample, SequenceFile sequenceFile) { sequenceFileRepository.removeFileFromSample(sample, sequenceFile); } /** * {@inheritDoc} */ @Transactional(readOnly = true) public List<Join<Project, Sample>> getSamplesForProject(Project p) { return new ArrayList<Join<Project, Sample>>(sampleRepository.getSamplesForProject(p)); } }
src/main/java/ca/corefacility/bioinformatics/irida/service/impl/SampleServiceImpl.java
package ca.corefacility.bioinformatics.irida.service.impl; import java.util.ArrayList; import java.util.List; import javax.validation.Validator; import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; import ca.corefacility.bioinformatics.irida.model.Project; import ca.corefacility.bioinformatics.irida.model.Sample; import ca.corefacility.bioinformatics.irida.model.SequenceFile; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin; import ca.corefacility.bioinformatics.irida.model.joins.impl.SampleSequenceFileJoin; import ca.corefacility.bioinformatics.irida.repositories.CRUDRepository; import ca.corefacility.bioinformatics.irida.repositories.SampleRepository; import ca.corefacility.bioinformatics.irida.repositories.SequenceFileRepository; import ca.corefacility.bioinformatics.irida.service.SampleService; /** * Service class for managing {@link Sample}. * * @author Franklin Bristow <[email protected]> */ public class SampleServiceImpl extends CRUDServiceImpl<Long, Sample> implements SampleService { /** * Reference to {@link CRUDRepository} for managing {@link Sample}. */ private SampleRepository sampleRepository; /** * Reference to {@link SequenceFileRepository} for managing {@link SequenceFile}. */ private SequenceFileRepository sequenceFileRepository; /** * Constructor. * * @param sampleRepository the sample repository. * @param validator validator. */ public SampleServiceImpl(SampleRepository sampleRepository, SequenceFileRepository sequenceFileRepository, Validator validator) { super(sampleRepository, validator, Sample.class); this.sampleRepository = sampleRepository; this.sequenceFileRepository = sequenceFileRepository; } /** * {@inheritDoc} */ @Override public SampleSequenceFileJoin addSequenceFileToSample(Sample sample, SequenceFile sampleFile) { // confirm that both the sample and sequence file exist already, fail fast if either don't exist if (!sampleRepository.exists(sample.getId())) { throw new IllegalArgumentException("Sample must be persisted before adding a sequence file."); } if (!sequenceFileRepository.exists(sampleFile.getId())) { throw new IllegalArgumentException("Sequence file must be persisted before adding to sample."); } // call the relationship repository to create the relationship between the two entities. SampleSequenceFileJoin addFileToSample = sequenceFileRepository.addFileToSample(sample, sampleFile); return addFileToSample; } /** * {@inheritDoc} */ @Override public Sample getSampleForProject(Project project, Long identifier) throws EntityNotFoundException { Sample s = null; // confirm that the link between project and this identifier exists List<ProjectSampleJoin> samplesForProject = sampleRepository.getSamplesForProject(project); for(ProjectSampleJoin join : samplesForProject){ if(join.getObject().getId().equals(identifier)){ // load the sample from the database s=read(identifier); } } if(s == null){ throw new EntityNotFoundException("Join between the project and this identifier doesn't exist"); } // return sample to the caller return s; } /** * {@inheritDoc} */ @Override public void removeSequenceFileFromSample(Sample sample, SequenceFile sequenceFile) { sequenceFileRepository.removeFileFromSample(sample, sequenceFile); } /** * {@inheritDoc} */ public List<Join<Project, Sample>> getSamplesForProject(Project p) { return new ArrayList<Join<Project, Sample>>(sampleRepository.getSamplesForProject(p)); } }
Basic role-based permissions for samples.
src/main/java/ca/corefacility/bioinformatics/irida/service/impl/SampleServiceImpl.java
Basic role-based permissions for samples.
<ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/service/impl/SampleServiceImpl.java <ide> import java.util.List; <ide> <ide> import javax.validation.Validator; <add> <add>import org.springframework.security.access.prepost.PreAuthorize; <add>import org.springframework.transaction.annotation.Transactional; <ide> <ide> import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException; <ide> import ca.corefacility.bioinformatics.irida.model.Project; <ide> <ide> /** <ide> * Service class for managing {@link Sample}. <del> * <add> * <ide> * @author Franklin Bristow <[email protected]> <ide> */ <ide> public class SampleServiceImpl extends CRUDServiceImpl<Long, Sample> implements SampleService { <del> <del> /** <del> * Reference to {@link CRUDRepository} for managing {@link Sample}. <del> */ <del> private SampleRepository sampleRepository; <del> /** <del> * Reference to {@link SequenceFileRepository} for managing {@link SequenceFile}. <del> */ <del> private SequenceFileRepository sequenceFileRepository; <del> <del> /** <del> * Constructor. <del> * <del> * @param sampleRepository the sample repository. <del> * @param validator validator. <del> */ <del> public SampleServiceImpl(SampleRepository sampleRepository, <del> SequenceFileRepository sequenceFileRepository, Validator validator) { <del> super(sampleRepository, validator, Sample.class); <del> this.sampleRepository = sampleRepository; <del> this.sequenceFileRepository = sequenceFileRepository; <del> } <ide> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public SampleSequenceFileJoin addSequenceFileToSample(Sample sample, SequenceFile sampleFile) { <del> // confirm that both the sample and sequence file exist already, fail fast if either don't exist <del> if (!sampleRepository.exists(sample.getId())) { <del> throw new IllegalArgumentException("Sample must be persisted before adding a sequence file."); <del> } <add> /** <add> * Reference to {@link CRUDRepository} for managing {@link Sample}. <add> */ <add> private SampleRepository sampleRepository; <add> /** <add> * Reference to {@link SequenceFileRepository} for managing <add> * {@link SequenceFile}. <add> */ <add> private SequenceFileRepository sequenceFileRepository; <ide> <del> if (!sequenceFileRepository.exists(sampleFile.getId())) { <del> throw new IllegalArgumentException("Sequence file must be persisted before adding to sample."); <del> } <add> /** <add> * Constructor. <add> * <add> * @param sampleRepository <add> * the sample repository. <add> * @param validator <add> * validator. <add> */ <add> public SampleServiceImpl(SampleRepository sampleRepository, SequenceFileRepository sequenceFileRepository, <add> Validator validator) { <add> super(sampleRepository, validator, Sample.class); <add> this.sampleRepository = sampleRepository; <add> this.sequenceFileRepository = sequenceFileRepository; <add> } <ide> <del> // call the relationship repository to create the relationship between the two entities. <del> SampleSequenceFileJoin addFileToSample = sequenceFileRepository.addFileToSample(sample, sampleFile); <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> @PreAuthorize("hasRole('ROLE_USER')") <add> public Sample create(Sample s) { <add> return super.create(s); <add> } <ide> <del> return addFileToSample; <del> } <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> @Transactional <add> public SampleSequenceFileJoin addSequenceFileToSample(Sample sample, SequenceFile sampleFile) { <add> // confirm that both the sample and sequence file exist already, fail <add> // fast if either don't exist <add> if (!sampleRepository.exists(sample.getId())) { <add> throw new IllegalArgumentException("Sample must be persisted before adding a sequence file."); <add> } <ide> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public Sample getSampleForProject(Project project, Long identifier) throws EntityNotFoundException { <add> if (!sequenceFileRepository.exists(sampleFile.getId())) { <add> throw new IllegalArgumentException("Sequence file must be persisted before adding to sample."); <add> } <ide> <del> Sample s = null; <del> <del> // confirm that the link between project and this identifier exists <del> List<ProjectSampleJoin> samplesForProject = sampleRepository.getSamplesForProject(project); <del> for(ProjectSampleJoin join : samplesForProject){ <del> if(join.getObject().getId().equals(identifier)){ <del> // load the sample from the database <del> s=read(identifier); <del> } <del> } <del> <del> if(s == null){ <del> throw new EntityNotFoundException("Join between the project and this identifier doesn't exist"); <del> } <add> // call the relationship repository to create the relationship between <add> // the two entities. <add> SampleSequenceFileJoin addFileToSample = sequenceFileRepository.addFileToSample(sample, sampleFile); <ide> <del> // return sample to the caller <del> return s; <del> } <add> return addFileToSample; <add> } <ide> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public void removeSequenceFileFromSample(Sample sample, SequenceFile sequenceFile) { <del> sequenceFileRepository.removeFileFromSample(sample, sequenceFile); <del> } <del> /** <del> * {@inheritDoc} <del> */ <del> public List<Join<Project, Sample>> getSamplesForProject(Project p) { <del> return new ArrayList<Join<Project, Sample>>(sampleRepository.getSamplesForProject(p)); <del> } <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> @Transactional(readOnly = true) <add> public Sample getSampleForProject(Project project, Long identifier) throws EntityNotFoundException { <add> <add> Sample s = null; <add> <add> // confirm that the link between project and this identifier exists <add> List<ProjectSampleJoin> samplesForProject = sampleRepository.getSamplesForProject(project); <add> for (ProjectSampleJoin join : samplesForProject) { <add> if (join.getObject().getId().equals(identifier)) { <add> // load the sample from the database <add> s = read(identifier); <add> } <add> } <add> <add> if (s == null) { <add> throw new EntityNotFoundException("Join between the project and this identifier doesn't exist"); <add> } <add> <add> // return sample to the caller <add> return s; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> @Transactional <add> public void removeSequenceFileFromSample(Sample sample, SequenceFile sequenceFile) { <add> sequenceFileRepository.removeFileFromSample(sample, sequenceFile); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Transactional(readOnly = true) <add> public List<Join<Project, Sample>> getSamplesForProject(Project p) { <add> return new ArrayList<Join<Project, Sample>>(sampleRepository.getSamplesForProject(p)); <add> } <ide> }
Java
mit
5d8127335f775601fe865ea735cf6ef5f8799921
0
InternationalMixMob/CSCI-E-71_IMM_Slacker_Client_Android,InternationalMixMob/CSCI-E-71_IMM_Slacker_Client_Android
package edu.cscie71.imm.app.slacker.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class SlackerClient implements ISlackerClient { private static final String MESSAGE = "/api/chat.postMessage"; private static final String USER_DATA = "/api/users.info"; private static final String OATH_TOKEN = "/api/oauth.access"; private final String BASE_URL; public SlackerClient() { BASE_URL = "https://slack.com"; } protected SlackerClient(String baseURL) { BASE_URL = baseURL; } /** * @inheritDoc */ public String postMessage(String token, String channel, String message) { String queryString = "?token=" + URLEncoder.encode(token) + "&channel=" + URLEncoder.encode(channel) + "&text=" + URLEncoder.encode(message) + "&as_user=" + "true"; return makeRestTransaction(BASE_URL + MESSAGE + queryString, "POST"); } /** * @inheritDoc */ public String getUserInfo(String token, String user) { String queryString = "?token=" + URLEncoder.encode(token) + "&user=" + URLEncoder.encode(user); return makeRestTransaction(BASE_URL + USER_DATA + queryString, "GET"); } /** * @inheritDoc */ public String getOAuthToken(String clientId, String clientSecret, String code, String redirectUri) { String queryString = "?client_id=" + URLEncoder.encode(clientId) + "&client_secret=" + URLEncoder.encode(clientSecret) + "&code=" + URLEncoder.encode(code) + "&redirect_uri=" + URLEncoder.encode(redirectUri); return makeRestTransaction(BASE_URL + OATH_TOKEN + queryString, "GET"); } private String makeRestTransaction(String url, String method) { try { URL getURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) getURL.openConnection(); connection.setRequestMethod(method); BufferedReader response = new BufferedReader( new InputStreamReader(connection.getInputStream()) ); StringBuilder sb = new StringBuilder(); String nextLine = ""; while ((nextLine = response.readLine()) != null) { sb.append(nextLine); } return sb.toString(); } catch (MalformedURLException e) { return "{\"ok\":false,\"error\":\"malformed_url: " + e.getMessage() + "\"}"; } catch (IOException e) { return "{\"ok\":false,\"error\":\"io_exception: " + e.getMessage() + "\"}"; } } }
src/main/java/edu/cscie71/imm/app/slacker/client/SlackerClient.java
package edu.cscie71.imm.app.slacker.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class SlackerClient implements ISlackerClient { private static final String MESSAGE = "/api/chat.postMessage"; private static final String USER_DATA = "/api/users.info"; private static final String OATH_TOKEN = "/api/oauth.access"; private final String BASE_URL; public SlackerClient() { BASE_URL = "https://slack.com"; } protected SlackerClient(String baseURL) { BASE_URL = baseURL; } /** * @inheritDoc */ public String postMessage(String token, String channel, String message) { String queryString = "?token=" + URLEncoder.encode(token) + "&channel=" + URLEncoder.encode(channel) + "&text=" + URLEncoder.encode(message) + "&as_user=" + "true"; return makeRestTransaction(BASE_URL + MESSAGE + queryString, "POST"); } /** * @inheritDoc */ public String getUserInfo(String token, String user) { String queryString = "?token=" + URLEncoder.encode(token) + "&user=" + URLEncoder.encode(user); return makeRestTransaction(BASE_URL + USER_DATA + queryString, "GET"); } /** * @inheritDoc */ public String getOAuthToken(String clientId, String clientSecret, String code, String redirectUri) { String queryString = "?client_id=".concat(URLEncoder.encode(clientId)) .concat("&client_secret=").concat(URLEncoder.encode(clientSecret)) .concat("&code=").concat(URLEncoder.encode(code)) .concat("&redirect_uri=").concat(URLEncoder.encode(redirectUri)); return makeRestTransaction(BASE_URL.concat(OATH_TOKEN).concat(queryString), "GET"); } private String makeRestTransaction(String url, String method) { try { URL getURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) getURL.openConnection(); connection.setRequestMethod(method); BufferedReader response = new BufferedReader( new InputStreamReader(connection.getInputStream()) ); StringBuilder sb = new StringBuilder(); String nextLine = ""; while ((nextLine = response.readLine()) != null) { sb.append(nextLine); } return sb.toString(); } catch (MalformedURLException e) { return "{\"ok\":false,\"error\":\"malformed_url: " + e.getMessage() + "\"}"; } catch (IOException e) { return "{\"ok\":false,\"error\":\"io_exception: " + e.getMessage() + "\"}"; } } }
[SKCP-97] Cleaned up.
src/main/java/edu/cscie71/imm/app/slacker/client/SlackerClient.java
[SKCP-97] Cleaned up.
<ide><path>rc/main/java/edu/cscie71/imm/app/slacker/client/SlackerClient.java <ide> * @inheritDoc <ide> */ <ide> public String getOAuthToken(String clientId, String clientSecret, String code, String redirectUri) { <del> String queryString = "?client_id=".concat(URLEncoder.encode(clientId)) <del> .concat("&client_secret=").concat(URLEncoder.encode(clientSecret)) <del> .concat("&code=").concat(URLEncoder.encode(code)) <del> .concat("&redirect_uri=").concat(URLEncoder.encode(redirectUri)); <del> return makeRestTransaction(BASE_URL.concat(OATH_TOKEN).concat(queryString), "GET"); <add> String queryString = "?client_id=" + URLEncoder.encode(clientId) <add> + "&client_secret=" + URLEncoder.encode(clientSecret) <add> + "&code=" + URLEncoder.encode(code) <add> + "&redirect_uri=" + URLEncoder.encode(redirectUri); <add> return makeRestTransaction(BASE_URL + OATH_TOKEN + queryString, "GET"); <ide> } <ide> <ide> private String makeRestTransaction(String url, String method) {
Java
apache-2.0
d5fd967f7ccfcc664f2b8d6f2825304637e24c4e
0
GaneshSPatil/gocd,ind9/gocd,marques-work/gocd,jyotisingh/gocd,Skarlso/gocd,naveenbhaskar/gocd,bdpiparva/gocd,tomzo/gocd,jyotisingh/gocd,ibnc/gocd,kierarad/gocd,bdpiparva/gocd,arvindsv/gocd,naveenbhaskar/gocd,arvindsv/gocd,ibnc/gocd,tomzo/gocd,bdpiparva/gocd,ibnc/gocd,jyotisingh/gocd,gocd/gocd,kierarad/gocd,ketan/gocd,naveenbhaskar/gocd,ind9/gocd,naveenbhaskar/gocd,ketan/gocd,varshavaradarajan/gocd,varshavaradarajan/gocd,marques-work/gocd,varshavaradarajan/gocd,ketan/gocd,bdpiparva/gocd,ketan/gocd,GaneshSPatil/gocd,Skarlso/gocd,varshavaradarajan/gocd,marques-work/gocd,bdpiparva/gocd,arvindsv/gocd,gocd/gocd,tomzo/gocd,ind9/gocd,bdpiparva/gocd,GaneshSPatil/gocd,Skarlso/gocd,gocd/gocd,naveenbhaskar/gocd,jyotisingh/gocd,arvindsv/gocd,kierarad/gocd,tomzo/gocd,GaneshSPatil/gocd,tomzo/gocd,gocd/gocd,ibnc/gocd,GaneshSPatil/gocd,Skarlso/gocd,kierarad/gocd,varshavaradarajan/gocd,ketan/gocd,jyotisingh/gocd,gocd/gocd,arvindsv/gocd,ketan/gocd,jyotisingh/gocd,marques-work/gocd,tomzo/gocd,ibnc/gocd,ind9/gocd,varshavaradarajan/gocd,marques-work/gocd,Skarlso/gocd,Skarlso/gocd,GaneshSPatil/gocd,naveenbhaskar/gocd,ibnc/gocd,kierarad/gocd,kierarad/gocd,ind9/gocd,arvindsv/gocd,gocd/gocd,marques-work/gocd
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.controller; import com.thoughtworks.go.domain.ConsoleConsumer; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException; import com.thoughtworks.go.server.cache.ZipArtifactCache; import com.thoughtworks.go.server.dao.JobInstanceDao; import com.thoughtworks.go.server.security.HeaderConstraint; import com.thoughtworks.go.server.service.ArtifactsService; import com.thoughtworks.go.server.service.ConsoleActivityMonitor; import com.thoughtworks.go.server.service.ConsoleService; import com.thoughtworks.go.server.service.RestfulService; import com.thoughtworks.go.server.util.ErrorHandler; import com.thoughtworks.go.server.view.artifacts.ArtifactsView; import com.thoughtworks.go.server.view.artifacts.LocalArtifactsView; import com.thoughtworks.go.server.web.ArtifactFolderViewFactory; import com.thoughtworks.go.server.web.FileModelAndView; import com.thoughtworks.go.server.web.ResponseCodeView; import com.thoughtworks.go.util.ArtifactLogUtil; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.go.server.web.ZipArtifactFolderViewFactory.zipViewFactory; import static com.thoughtworks.go.util.ArtifactLogUtil.isConsoleOutput; import static com.thoughtworks.go.util.GoConstants.*; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; @Controller public class ArtifactsController { private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactsController.class); private final JobInstanceDao jobInstanceDao; private final ConsoleActivityMonitor consoleActivityMonitor; private final ArtifactFolderViewFactory folderViewFactory; private final ArtifactFolderViewFactory jsonViewFactory; private final ArtifactFolderViewFactory zipViewFactory; private final Charset consoleLogCharset; private ArtifactsService artifactsService; private RestfulService restfulService; private ConsoleService consoleService; private HeaderConstraint headerConstraint; @Autowired ArtifactsController(ArtifactsService artifactsService, RestfulService restfulService, ZipArtifactCache zipArtifactCache, JobInstanceDao jobInstanceDao, ConsoleActivityMonitor consoleActivityMonitor, ConsoleService consoleService, SystemEnvironment systemEnvironment) { this.artifactsService = artifactsService; this.restfulService = restfulService; this.jobInstanceDao = jobInstanceDao; this.consoleActivityMonitor = consoleActivityMonitor; this.consoleService = consoleService; this.folderViewFactory = FileModelAndView.htmlViewFactory(); this.jsonViewFactory = FileModelAndView.jsonViewfactory(); this.zipViewFactory = zipViewFactory(zipArtifactCache); this.headerConstraint = new HeaderConstraint(systemEnvironment); this.consoleLogCharset = systemEnvironment.consoleLogCharsetAsCharset(); } /* RESTful URLs */ @RequestMapping(value = "/repository/restful/artifact/GET/html", method = RequestMethod.GET) public ModelAndView getArtifactAsHtml(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha, @RequestParam(value = "serverAlias", required = false) String serverAlias) throws Exception { return getArtifact(filePath, folderViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, serverAlias); } @RequestMapping(value = "/repository/restful/artifact/GET/json", method = RequestMethod.GET) public ModelAndView getArtifactAsJson(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha ) throws Exception { return getArtifact(filePath, jsonViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, null); } @RequestMapping(value = "/repository/restful/artifact/GET/zip", method = RequestMethod.GET) public ModelAndView getArtifactAsZip(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha ) throws Exception { if (filePath.equals(".zip")) { filePath = "./.zip"; } return getArtifact(filePath, zipViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, null); } @RequestMapping(value = "/repository/restful/artifact/GET/*", method = RequestMethod.GET) public void fetch(HttpServletRequest request, HttpServletResponse response) throws Exception { request.getRequestDispatcher("/repository/restful/artifact/GET/html").forward(request, response); } @RequestMapping(value = "/repository/restful/artifact/POST/*", method = RequestMethod.POST) public ModelAndView postArtifact(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam(value = "buildId", required = false) Long buildId, @RequestParam("filePath") String filePath, @RequestParam(value = "attempt", required = false) Integer attempt, MultipartHttpServletRequest request) throws Exception { JobIdentifier jobIdentifier; if (!headerConstraint.isSatisfied(request)) { return ResponseCodeView.create(HttpServletResponse.SC_BAD_REQUEST, "Missing required header 'Confirm'"); } try { jobIdentifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName, buildId); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } int convertedAttempt = attempt == null ? 1 : attempt; try { File artifact = artifactsService.findArtifact(jobIdentifier, filePath); if (artifact.exists() && artifact.isFile()) { return FileModelAndView.fileAlreadyExists(filePath); } MultipartFile multipartFile = multipartFile(request); if (multipartFile == null) { return FileModelAndView.invalidUploadRequest(); } boolean success = saveFile(convertedAttempt, artifact, multipartFile, shouldUnzipStream(multipartFile)); if (!success) { return FileModelAndView.errorSavingFile(filePath); } success = updateChecksumFile(request, jobIdentifier, filePath); if (!success) { return FileModelAndView.errorSavingChecksumFile(filePath); } return FileModelAndView.fileCreated(filePath); } catch (IllegalArtifactLocationException e) { return FileModelAndView.forbiddenUrl(filePath); } } private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier, String filePath) throws IOException, IllegalArtifactLocationException { MultipartFile checksumMultipartFile = getChecksumFile(request); if (checksumMultipartFile != null) { String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier), ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME); File checksumFile = artifactsService.getArtifactLocation(checksumFilePath); synchronized (checksumFilePath.intern()) { return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream()); } } else { LOGGER.warn("[Artifacts Upload] Checksum file not uploaded for artifact at path '{}'", filePath); } return true; } private boolean saveFile(int convertedAttempt, File artifact, MultipartFile multipartFile, boolean shouldUnzip) throws IOException { InputStream inputStream = null; boolean success; try { inputStream = multipartFile.getInputStream(); success = artifactsService.saveFile(artifact, inputStream, shouldUnzip, convertedAttempt); } finally { IOUtils.closeQuietly(inputStream); } return success; } @RequestMapping(value = "/repository/restful/artifact/PUT/*", method = RequestMethod.PUT) public ModelAndView putArtifact(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam(value = "buildId", required = false) Long buildId, @RequestParam("filePath") String filePath, @RequestParam(value = "agentId", required = false) String agentId, HttpServletRequest request ) throws Exception { if (filePath.contains("..")) { return FileModelAndView.forbiddenUrl(filePath); } JobIdentifier jobIdentifier; try { jobIdentifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName, buildId); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } if (isConsoleOutput(filePath)) { return putConsoleOutput(jobIdentifier, request.getInputStream()); } else { return putArtifact(jobIdentifier, filePath, request.getInputStream()); } } /* Other URLs */ @RequestMapping(value = "/**/consoleout.json", method = RequestMethod.GET) public ModelAndView consoleout(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam("buildName") String buildName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam(value = "startLineNumber", required = false) Long start ) { start = start == null ? 0L : start; try { JobIdentifier identifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName); if (jobInstanceDao.isJobCompleted(identifier) && !consoleService.doesLogExist(identifier)) { return logsNotFound(identifier); } ConsoleConsumer streamer = consoleService.getStreamer(start, identifier); return new ModelAndView(new ConsoleOutView(streamer, consoleLogCharset)); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } } @ErrorHandler public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response, Exception e) { LOGGER.error("Error loading artifacts: ", e); Map model = new HashMap(); model.put(ERROR_FOR_PAGE, "Artifact does not exist."); return new ModelAndView("exceptions_page", model); } ModelAndView getArtifact(String filePath, ArtifactFolderViewFactory folderViewFactory, String pipelineName, String counterOrLabel, String stageName, String stageCounter, String buildName, String sha, String serverAlias) throws Exception { LOGGER.info("[Artifact Download] Trying to resolve '{}' for '{}/{}/{}/{}/{}'", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName); long before = System.currentTimeMillis(); ArtifactsView view; //Work out the job that we are trying to retrieve JobIdentifier translatedId; try { translatedId = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } if (filePath.contains("..")) { return FileModelAndView.forbiddenUrl(filePath); } view = new LocalArtifactsView(folderViewFactory, artifactsService, translatedId, consoleService); ModelAndView createdView = view.createView(filePath, sha); LOGGER.info("[Artifact Download] Successfully resolved '{}' for '{}/{}/{}/{}/{}'. It took: {}ms", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName, System.currentTimeMillis() - before); return createdView; } private boolean shouldUnzipStream(MultipartFile multipartFile) { return multipartFile.getName().equals(ZIP_MULTIPART_FILENAME); } private MultipartFile multipartFile(MultipartHttpServletRequest request) { MultipartFile multipartFile = request.getFile(REGULAR_MULTIPART_FILENAME); if (multipartFile == null) { multipartFile = request.getFile(ZIP_MULTIPART_FILENAME); } return multipartFile; } private MultipartFile getChecksumFile(MultipartHttpServletRequest request) { return request.getFile(CHECKSUM_MULTIPART_FILENAME); } private ModelAndView putConsoleOutput(final JobIdentifier jobIdentifier, final InputStream inputStream) throws Exception { File consoleLogFile = consoleService.consoleLogFile(jobIdentifier); boolean updated = consoleService.updateConsoleLog(consoleLogFile, inputStream); if (updated) { consoleActivityMonitor.consoleUpdatedFor(jobIdentifier); return FileModelAndView.fileAppended(consoleLogFile.getPath()); } else { return FileModelAndView.errorSavingFile(consoleLogFile.getPath()); } } private ModelAndView putArtifact(JobIdentifier jobIdentifier, String filePath, InputStream inputStream) throws Exception { File artifact = artifactsService.findArtifact(jobIdentifier, filePath); if (artifactsService.saveOrAppendFile(artifact, inputStream)) { return FileModelAndView.fileAppended(filePath); } else { return FileModelAndView.errorSavingFile(filePath); } } private ModelAndView buildNotFound(String pipelineName, String counterOrLabel, String stageName, String stageCounter, String buildName) { return ResponseCodeView.create(SC_NOT_FOUND, String.format("Job %s/%s/%s/%s/%s not found.", pipelineName, counterOrLabel, stageName, stageCounter, buildName)); } private ModelAndView logsNotFound(JobIdentifier identifier) { String notFound = String.format("Console log for %s is unavailable as it may have been purged by Go or deleted externally.", identifier.toFullString()); return ResponseCodeView.create(SC_NOT_FOUND, notFound); } }
server/src/main/java/com/thoughtworks/go/server/controller/ArtifactsController.java
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.controller; import com.thoughtworks.go.domain.ConsoleConsumer; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException; import com.thoughtworks.go.server.cache.ZipArtifactCache; import com.thoughtworks.go.server.dao.JobInstanceDao; import com.thoughtworks.go.server.security.HeaderConstraint; import com.thoughtworks.go.server.service.ArtifactsService; import com.thoughtworks.go.server.service.ConsoleActivityMonitor; import com.thoughtworks.go.server.service.ConsoleService; import com.thoughtworks.go.server.service.RestfulService; import com.thoughtworks.go.server.util.ErrorHandler; import com.thoughtworks.go.server.view.artifacts.ArtifactsView; import com.thoughtworks.go.server.view.artifacts.LocalArtifactsView; import com.thoughtworks.go.server.web.ArtifactFolderViewFactory; import com.thoughtworks.go.server.web.FileModelAndView; import com.thoughtworks.go.server.web.ResponseCodeView; import com.thoughtworks.go.util.ArtifactLogUtil; import com.thoughtworks.go.util.SystemEnvironment; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.go.server.web.ZipArtifactFolderViewFactory.zipViewFactory; import static com.thoughtworks.go.util.ArtifactLogUtil.isConsoleOutput; import static com.thoughtworks.go.util.GoConstants.*; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; @Controller public class ArtifactsController { private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactsController.class); private final JobInstanceDao jobInstanceDao; private final ConsoleActivityMonitor consoleActivityMonitor; private final ArtifactFolderViewFactory folderViewFactory; private final ArtifactFolderViewFactory jsonViewFactory; private final ArtifactFolderViewFactory zipViewFactory; private final Charset consoleLogCharset; private ArtifactsService artifactsService; private RestfulService restfulService; private ConsoleService consoleService; private HeaderConstraint headerConstraint; @Autowired ArtifactsController(ArtifactsService artifactsService, RestfulService restfulService, ZipArtifactCache zipArtifactCache, JobInstanceDao jobInstanceDao, ConsoleActivityMonitor consoleActivityMonitor, ConsoleService consoleService, SystemEnvironment systemEnvironment) { this.artifactsService = artifactsService; this.restfulService = restfulService; this.jobInstanceDao = jobInstanceDao; this.consoleActivityMonitor = consoleActivityMonitor; this.consoleService = consoleService; this.folderViewFactory = FileModelAndView.htmlViewFactory(); this.jsonViewFactory = FileModelAndView.jsonViewfactory(); this.zipViewFactory = zipViewFactory(zipArtifactCache); this.headerConstraint = new HeaderConstraint(systemEnvironment); this.consoleLogCharset = systemEnvironment.consoleLogCharsetAsCharset(); } /* RESTful URLs */ @RequestMapping(value = "/repository/restful/artifact/GET/html", method = RequestMethod.GET) public ModelAndView getArtifactAsHtml(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha, @RequestParam(value = "serverAlias", required = false) String serverAlias) throws Exception { return getArtifact(filePath, folderViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, serverAlias); } @RequestMapping(value = "/repository/restful/artifact/GET/json", method = RequestMethod.GET) public ModelAndView getArtifactAsJson(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha ) throws Exception { return getArtifact(filePath, jsonViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, null); } @RequestMapping(value = "/repository/restful/artifact/GET/zip", method = RequestMethod.GET) public ModelAndView getArtifactAsZip(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam("filePath") String filePath, @RequestParam(value = "sha1", required = false) String sha ) throws Exception { return getArtifact(filePath, zipViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, null); } @RequestMapping(value = "/repository/restful/artifact/GET/*", method = RequestMethod.GET) public void fetch(HttpServletRequest request, HttpServletResponse response) throws Exception { request.getRequestDispatcher("/repository/restful/artifact/GET/html").forward(request, response); } @RequestMapping(value = "/repository/restful/artifact/POST/*", method = RequestMethod.POST) public ModelAndView postArtifact(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam(value = "buildId", required = false) Long buildId, @RequestParam("filePath") String filePath, @RequestParam(value = "attempt", required = false) Integer attempt, MultipartHttpServletRequest request) throws Exception { JobIdentifier jobIdentifier; if (!headerConstraint.isSatisfied(request)) { return ResponseCodeView.create(HttpServletResponse.SC_BAD_REQUEST, "Missing required header 'Confirm'"); } try { jobIdentifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName, buildId); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } int convertedAttempt = attempt == null ? 1 : attempt; try { File artifact = artifactsService.findArtifact(jobIdentifier, filePath); if (artifact.exists() && artifact.isFile()) { return FileModelAndView.fileAlreadyExists(filePath); } MultipartFile multipartFile = multipartFile(request); if (multipartFile == null) { return FileModelAndView.invalidUploadRequest(); } boolean success = saveFile(convertedAttempt, artifact, multipartFile, shouldUnzipStream(multipartFile)); if (!success) { return FileModelAndView.errorSavingFile(filePath); } success = updateChecksumFile(request, jobIdentifier, filePath); if (!success) { return FileModelAndView.errorSavingChecksumFile(filePath); } return FileModelAndView.fileCreated(filePath); } catch (IllegalArtifactLocationException e) { return FileModelAndView.forbiddenUrl(filePath); } } private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier, String filePath) throws IOException, IllegalArtifactLocationException { MultipartFile checksumMultipartFile = getChecksumFile(request); if (checksumMultipartFile != null) { String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier), ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME); File checksumFile = artifactsService.getArtifactLocation(checksumFilePath); synchronized (checksumFilePath.intern()) { return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream()); } } else { LOGGER.warn("[Artifacts Upload] Checksum file not uploaded for artifact at path '{}'", filePath); } return true; } private boolean saveFile(int convertedAttempt, File artifact, MultipartFile multipartFile, boolean shouldUnzip) throws IOException { InputStream inputStream = null; boolean success; try { inputStream = multipartFile.getInputStream(); success = artifactsService.saveFile(artifact, inputStream, shouldUnzip, convertedAttempt); } finally { IOUtils.closeQuietly(inputStream); } return success; } @RequestMapping(value = "/repository/restful/artifact/PUT/*", method = RequestMethod.PUT) public ModelAndView putArtifact(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam("buildName") String buildName, @RequestParam(value = "buildId", required = false) Long buildId, @RequestParam("filePath") String filePath, @RequestParam(value = "agentId", required = false) String agentId, HttpServletRequest request ) throws Exception { if (filePath.contains("..")) { return FileModelAndView.forbiddenUrl(filePath); } JobIdentifier jobIdentifier; try { jobIdentifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName, buildId); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } if (isConsoleOutput(filePath)) { return putConsoleOutput(jobIdentifier, request.getInputStream()); } else { return putArtifact(jobIdentifier, filePath, request.getInputStream()); } } /* Other URLs */ @RequestMapping(value = "/**/consoleout.json", method = RequestMethod.GET) public ModelAndView consoleout(@RequestParam("pipelineName") String pipelineName, @RequestParam("pipelineLabel") String counterOrLabel, @RequestParam("stageName") String stageName, @RequestParam("buildName") String buildName, @RequestParam(value = "stageCounter", required = false) String stageCounter, @RequestParam(value = "startLineNumber", required = false) Long start ) { start = start == null ? 0L : start; try { JobIdentifier identifier = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName); if (jobInstanceDao.isJobCompleted(identifier) && !consoleService.doesLogExist(identifier)) { return logsNotFound(identifier); } ConsoleConsumer streamer = consoleService.getStreamer(start, identifier); return new ModelAndView(new ConsoleOutView(streamer, consoleLogCharset)); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } } @ErrorHandler public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response, Exception e) { LOGGER.error("Error loading artifacts: ", e); Map model = new HashMap(); model.put(ERROR_FOR_PAGE, "Artifact does not exist."); return new ModelAndView("exceptions_page", model); } ModelAndView getArtifact(String filePath, ArtifactFolderViewFactory folderViewFactory, String pipelineName, String counterOrLabel, String stageName, String stageCounter, String buildName, String sha, String serverAlias) throws Exception { LOGGER.info("[Artifact Download] Trying to resolve '{}' for '{}/{}/{}/{}/{}'", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName); long before = System.currentTimeMillis(); ArtifactsView view; //Work out the job that we are trying to retrieve JobIdentifier translatedId; try { translatedId = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } catch (Exception e) { return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName); } if (filePath.contains("..")) { return FileModelAndView.forbiddenUrl(filePath); } view = new LocalArtifactsView(folderViewFactory, artifactsService, translatedId, consoleService); ModelAndView createdView = view.createView(filePath, sha); LOGGER.info("[Artifact Download] Successfully resolved '{}' for '{}/{}/{}/{}/{}'. It took: {}ms", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName, System.currentTimeMillis() - before); return createdView; } private boolean shouldUnzipStream(MultipartFile multipartFile) { return multipartFile.getName().equals(ZIP_MULTIPART_FILENAME); } private MultipartFile multipartFile(MultipartHttpServletRequest request) { MultipartFile multipartFile = request.getFile(REGULAR_MULTIPART_FILENAME); if (multipartFile == null) { multipartFile = request.getFile(ZIP_MULTIPART_FILENAME); } return multipartFile; } private MultipartFile getChecksumFile(MultipartHttpServletRequest request) { return request.getFile(CHECKSUM_MULTIPART_FILENAME); } private ModelAndView putConsoleOutput(final JobIdentifier jobIdentifier, final InputStream inputStream) throws Exception { File consoleLogFile = consoleService.consoleLogFile(jobIdentifier); boolean updated = consoleService.updateConsoleLog(consoleLogFile, inputStream); if (updated) { consoleActivityMonitor.consoleUpdatedFor(jobIdentifier); return FileModelAndView.fileAppended(consoleLogFile.getPath()); } else { return FileModelAndView.errorSavingFile(consoleLogFile.getPath()); } } private ModelAndView putArtifact(JobIdentifier jobIdentifier, String filePath, InputStream inputStream) throws Exception { File artifact = artifactsService.findArtifact(jobIdentifier, filePath); if (artifactsService.saveOrAppendFile(artifact, inputStream)) { return FileModelAndView.fileAppended(filePath); } else { return FileModelAndView.errorSavingFile(filePath); } } private ModelAndView buildNotFound(String pipelineName, String counterOrLabel, String stageName, String stageCounter, String buildName) { return ResponseCodeView.create(SC_NOT_FOUND, String.format("Job %s/%s/%s/%s/%s not found.", pipelineName, counterOrLabel, stageName, stageCounter, buildName)); } private ModelAndView logsNotFound(JobIdentifier identifier) { String notFound = String.format("Console log for %s is unavailable as it may have been purged by Go or deleted externally.", identifier.toFullString()); return ResponseCodeView.create(SC_NOT_FOUND, notFound); } }
Add a workaround for #4810 Older versions of gocd would set the filepath to `./.zip` when requesting directory `./`. After a spring upgrade, and some path normalization, the filePath is now `.zip`. This is currently a temporary workaround while we sort out a better way to do this correctly.
server/src/main/java/com/thoughtworks/go/server/controller/ArtifactsController.java
Add a workaround for #4810
<ide><path>erver/src/main/java/com/thoughtworks/go/server/controller/ArtifactsController.java <ide> @RequestParam("filePath") String filePath, <ide> @RequestParam(value = "sha1", required = false) String sha <ide> ) throws Exception { <add> if (filePath.equals(".zip")) { <add> filePath = "./.zip"; <add> } <ide> return getArtifact(filePath, zipViewFactory, pipelineName, counterOrLabel, stageName, stageCounter, buildName, sha, null); <ide> } <ide>