"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1>$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" a ",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="
",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" a ",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" a ",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
4 | },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();ca ",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
5 |
--------------------------------------------------------------------------------
/doc/js/page_effects.js:
--------------------------------------------------------------------------------
1 | function visibleInParent(element) {
2 | var position = $(element).position().top
3 | return position > -50 && position < ($(element).offsetParent().height() - 50)
4 | }
5 |
6 | function hasFragment(link, fragment) {
7 | return $(link).attr("href").indexOf("#" + fragment) != -1
8 | }
9 |
10 | function findLinkByFragment(elements, fragment) {
11 | return $(elements).filter(function(i, e) { return hasFragment(e, fragment)}).first()
12 | }
13 |
14 | function scrollToCurrentVarLink(elements) {
15 | var elements = $(elements);
16 | var parent = elements.offsetParent();
17 |
18 | if (elements.length == 0) return;
19 |
20 | var top = elements.first().position().top;
21 | var bottom = elements.last().position().top + elements.last().height();
22 |
23 | if (top >= 0 && bottom <= parent.height()) return;
24 |
25 | if (top < 0) {
26 | parent.scrollTop(parent.scrollTop() + top);
27 | }
28 | else if (bottom > parent.height()) {
29 | parent.scrollTop(parent.scrollTop() + bottom - parent.height());
30 | }
31 | }
32 |
33 | function setCurrentVarLink() {
34 | $('#vars a').parent().removeClass('current')
35 | $('.anchor').
36 | filter(function(index) { return visibleInParent(this) }).
37 | each(function(index, element) {
38 | findLinkByFragment("#vars a", element.id).
39 | parent().
40 | addClass('current')
41 | });
42 | scrollToCurrentVarLink('#vars .current');
43 | }
44 |
45 | var hasStorage = (function() { try { return localStorage.getItem } catch(e) {} }())
46 |
47 | function scrollPositionId(element) {
48 | var directory = window.location.href.replace(/[^\/]+\.html$/, '')
49 | return 'scroll::' + $(element).attr('id') + '::' + directory
50 | }
51 |
52 | function storeScrollPosition(element) {
53 | if (!hasStorage) return;
54 | localStorage.setItem(scrollPositionId(element) + "::x", $(element).scrollLeft())
55 | localStorage.setItem(scrollPositionId(element) + "::y", $(element).scrollTop())
56 | }
57 |
58 | function recallScrollPosition(element) {
59 | if (!hasStorage) return;
60 | $(element).scrollLeft(localStorage.getItem(scrollPositionId(element) + "::x"))
61 | $(element).scrollTop(localStorage.getItem(scrollPositionId(element) + "::y"))
62 | }
63 |
64 | function persistScrollPosition(element) {
65 | recallScrollPosition(element)
66 | $(element).scroll(function() { storeScrollPosition(element) })
67 | }
68 |
69 | function sidebarContentWidth(element) {
70 | var widths = $(element).find('.inner').map(function() { return $(this).innerWidth() })
71 | return Math.max.apply(Math, widths)
72 | }
73 |
74 | function resizeSidebars() {
75 | var nsWidth = sidebarContentWidth('#namespaces') + 30
76 | var varWidth = 0
77 |
78 | if ($('#vars').length != 0) {
79 | varWidth = sidebarContentWidth('#vars') + 30
80 | }
81 |
82 | // snap to grid
83 | var snap = 30;
84 | nsWidth = Math.ceil(nsWidth / snap) * snap;
85 | varWidth = Math.ceil(varWidth / snap) * snap;
86 |
87 | $('#namespaces').css('width', nsWidth)
88 | $('#vars').css('width', varWidth)
89 | $('#vars, .namespace-index').css('left', nsWidth + 1)
90 | $('.namespace-docs').css('left', nsWidth + varWidth + 2)
91 | }
92 |
93 | $(window).ready(resizeSidebars)
94 | $(window).ready(setCurrentVarLink)
95 | $(window).ready(function() { persistScrollPosition('#namespaces')})
96 | $(window).ready(function() {
97 | $('#content').scroll(setCurrentVarLink)
98 | $(window).resize(setCurrentVarLink)
99 | })
100 |
--------------------------------------------------------------------------------
/project.clj:
--------------------------------------------------------------------------------
1 | (defproject clj-kafka/clj-kafka "0.3.4"
2 | :min-lein-version "2.0.0"
3 | :url "https://github.com/pingles/clj-kafka"
4 | :license {:name "Eclipse Public License"
5 | :url "http://www.eclipse.org/legal/epl-v10.html"}
6 | :dependencies [[org.clojure/clojure "1.5.1"]
7 | [org.clojure/data.json "0.2.2"]
8 | [org.clojure/tools.logging "0.3.1"]
9 | [org.apache.kafka/kafka_2.10 "0.8.2.1"]
10 | [org.apache.kafka/kafka-clients "0.8.2.1"]
11 | [zookeeper-clj "0.9.3"]]
12 | :exclusions [javax.mail/mail
13 | javax.jms/jms
14 | com.sun.jdmk/jmxtools
15 | com.sun.jmx/jmxri
16 | jline/jline]
17 | :plugins [[lein-expectations "0.0.8"]
18 | [codox "0.8.12"]]
19 | :codox {:src-dir-uri "http://github.com/pingles/clj-kafka/blob/master/"
20 | :src-linenum-anchor-prefix "L"
21 | :defaults {:doc/format :markdown}}
22 | :profiles {:dev {:resource-paths ["dev-resources"]
23 | :dependencies [[commons-io/commons-io "2.4"]
24 | [expectations "1.4.45"]]}}
25 | :description "Clojure wrapper for Kafka's Java API")
26 |
--------------------------------------------------------------------------------
/src/clj_kafka/admin.clj:
--------------------------------------------------------------------------------
1 | (ns ^{:doc "Administration operations."}
2 | clj-kafka.admin
3 | (:require [clj-kafka.core :refer [as-properties]])
4 | (:import [kafka.admin AdminUtils]
5 | [kafka.utils ZKStringSerializer$]
6 | [org.I0Itec.zkclient ZkClient]))
7 |
8 | (defn- zk-string-serializer [] (ZKStringSerializer$/MODULE$))
9 |
10 | (defn zk-client
11 | "Create a `ZkClient` for use with the functions in this namespace.
12 | Servers is a Zookeeper connection string."
13 | ([servers]
14 | (zk-client servers nil))
15 | ([servers {:keys [session-timeout-ms connection-timeout-ms] :as opts
16 | :or {session-timeout-ms 10000
17 | connection-timeout-ms 10000}}]
18 | (ZkClient. servers session-timeout-ms connection-timeout-ms (zk-string-serializer))))
19 |
20 | (defn topic-exists?
21 | [zk topic]
22 | (AdminUtils/topicExists zk topic))
23 |
24 | (defn create-topic
25 | ([zk topic]
26 | (create-topic zk topic nil))
27 | ([zk topic {:keys [partitions replication-factor config]
28 | :or {partitions 1
29 | replication-factor 1
30 | config nil}}]
31 | (AdminUtils/createTopic zk topic (int partitions) (int replication-factor) (as-properties config))))
32 |
33 | (defn delete-topic
34 | [zk topic]
35 | (AdminUtils/deleteTopic zk topic))
36 |
37 | (defn topic-config
38 | [zk topic]
39 | (AdminUtils/fetchTopicConfig zk topic))
40 |
41 | (defn change-topic-config
42 | [zk topic config]
43 | (AdminUtils/changeTopicConfig zk topic (as-properties config)))
44 |
--------------------------------------------------------------------------------
/src/clj_kafka/consumer/simple.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.consumer.simple
2 | (:use [clj-kafka.core :only (to-clojure)])
3 | (:import [kafka.javaapi.consumer SimpleConsumer]
4 | [kafka.api FetchRequest FetchRequestBuilder PartitionOffsetRequestInfo]
5 | [kafka.javaapi OffsetRequest TopicMetadataRequest FetchResponse]
6 | [kafka.common TopicAndPartition]))
7 |
8 | (defn consumer
9 | "Create a consumer to connect to host and port. Port will
10 | normally be 9092."
11 | [host ^Long port client-id & {:keys [^Long timeout ^Long buffer-size] :or {timeout 100000 buffer-size 10000}}]
12 | (SimpleConsumer. host
13 | (Integer/valueOf port)
14 | (Integer/valueOf timeout)
15 | (Integer/valueOf buffer-size)
16 | client-id))
17 |
18 | (defn fetch-request
19 | [client-id topic ^Long partition offset fetch-size & {:keys [max-wait min-bytes]}]
20 | (.build (doto (FetchRequestBuilder. )
21 | (.clientId client-id)
22 | (.addFetch topic (Integer/valueOf partition) offset fetch-size)
23 | (#(when max-wait (.maxWait % max-wait)))
24 | (#(when min-bytes (.minBytes % min-bytes))))))
25 |
26 | (defn messages
27 | [^SimpleConsumer consumer client-id topic partition offset fetch-size & more]
28 | (let [fetch (apply fetch-request client-id topic partition offset fetch-size more)]
29 | (map to-clojure (iterator-seq (.iterator (.messageSet ^FetchResponse (.fetch consumer ^FetchRequest fetch)
30 | topic
31 | partition))))))
32 |
33 | (defn topic-meta-data [consumer topics]
34 | (to-clojure (.send consumer (TopicMetadataRequest. topics))))
35 |
36 | (defn topic-offset [consumer topic partition offset-position]
37 | (let [op {:latest -1 :earliest -2}
38 | tp (TopicAndPartition. topic partition)
39 | pori (PartitionOffsetRequestInfo. (offset-position op) 1)
40 | hm (java.util.HashMap. {tp pori})]
41 | (let [response (.getOffsetsBefore consumer (OffsetRequest. hm (kafka.api.OffsetRequest/CurrentVersion) "clj-kafka-id"))]
42 | (first (.offsets response topic partition)))))
43 |
44 | (defn latest-topic-offset [consumer topic partition]
45 | (topic-offset consumer topic partition :latest))
46 |
--------------------------------------------------------------------------------
/src/clj_kafka/consumer/zk.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.consumer.zk
2 | (:import [kafka.consumer ConsumerConfig Consumer KafkaStream]
3 | [kafka.javaapi.consumer ConsumerConnector]
4 | [kafka.serializer DefaultDecoder])
5 | (:use [clj-kafka.core :only (as-properties to-clojure with-resource)])
6 | (:require [zookeeper :as zk]))
7 |
8 | (defn consumer
9 | "Uses information in Zookeeper to connect to Kafka. More info on settings
10 | is available here: https://kafka.apache.org/08/configuration.html
11 |
12 | Recommended for using with with-resource:
13 | (with-resource [c (consumer m)]
14 | shutdown
15 | (take 5 (messages c \"test\")))
16 |
17 | Keys:
18 | zookeeper.connect : host:port for Zookeeper. e.g: 127.0.0.1:2181
19 | group.id : consumer group. e.g. group1
20 | auto.offset.reset : what to do if an offset is out of range, e.g. smallest, largest
21 | auto.commit.interval.ms : the frequency that the consumed offsets are committed to zookeeper.
22 | auto.commit.enable : if set to true, the consumer periodically commits to zookeeper the latest consumed offset of each partition"
23 | [m]
24 | (let [config (ConsumerConfig. (as-properties m))]
25 | (Consumer/createJavaConsumerConnector config)))
26 |
27 | (defn shutdown
28 | "Closes the connection to Zookeeper and stops consuming messages."
29 | [^ConsumerConnector consumer]
30 | (.shutdown consumer))
31 |
32 | (defn- lazy-iterate
33 | [^java.util.Iterator it]
34 | (lazy-seq
35 | (when (.hasNext it)
36 | (cons (.next it) (lazy-iterate it)))))
37 |
38 | (defn default-decoder
39 | "Creates the default decoder that reads message keys and values as byte arrays."
40 | []
41 | (DefaultDecoder. nil))
42 |
43 | (defn- vals->ints
44 | [m]
45 | (reduce-kv (fn [res k v] (assoc res k (int v))) {} m))
46 |
47 | (defn create-message-streams
48 | "Creates multiple message streams for consuming multiple topics, or
49 | a single topic cusing multiple threads. topic-count-map is a map
50 | from a topic name to the number of streams desired for that topic."
51 | ([^ConsumerConnector consumer topic-count-map]
52 | (.createMessageStreams consumer (vals->ints topic-count-map)))
53 | ([^ConsumerConnector consumer topic-count-map key-decoder value-decoder]
54 | (.createMessageStreams consumer (vals->ints topic-count-map) key-decoder value-decoder)))
55 |
56 | (defn create-message-stream
57 | "Creates a single message stream for given topic."
58 | ([^ConsumerConnector consumer topic]
59 | (let [topic-streams (.createMessageStreams consumer {topic (int 1)})]
60 | (first (get topic-streams topic))))
61 | ([^ConsumerConnector consumer topic key-decoder value-decoder]
62 | (let [topic-streams (.createMessageStreams consumer {topic (int 1)} key-decoder value-decoder)]
63 | (first (get topic-streams topic)))))
64 |
65 | (defn stream-seq
66 | "Returns a lazy sequence of KafkaMessage messages from the stream."
67 | [^KafkaStream stream]
68 | (map to-clojure
69 | (lazy-iterate (.iterator ^KafkaStream stream))))
70 |
71 | (defn messages
72 | "Provides an easy way to consume a sequence of KafkaMessage messages from the
73 | named topic. Consumes on a single thread and returns a lazy sequence."
74 | [^ConsumerConnector consumer topic & {:keys [key-decoder
75 | value-decoder]
76 | :or {key-decoder (default-decoder)
77 | value-decoder (default-decoder)}}]
78 | (stream-seq (create-message-stream consumer topic key-decoder value-decoder)))
79 |
--------------------------------------------------------------------------------
/src/clj_kafka/core.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.core
2 | (:import [java.nio ByteBuffer]
3 | [java.util Properties]
4 | [kafka.message MessageAndMetadata MessageAndOffset]
5 | [kafka.javaapi PartitionMetadata TopicMetadata TopicMetadataResponse ConsumerMetadataResponse OffsetFetchResponse OffsetCommitResponse]
6 | [kafka.cluster Broker]
7 | ))
8 |
9 | (defrecord KafkaMessage [topic offset partition key value])
10 |
11 | (defn as-properties
12 | [m]
13 | (let [props (Properties. )]
14 | (doseq [[n v] m] (.setProperty props n v))
15 | props))
16 |
17 | (defmacro with-resource
18 | [binding close-fn & body]
19 | `(let ~binding
20 | (try
21 | (do ~@body)
22 | (finally
23 | (~close-fn ~(binding 0))))))
24 |
25 | (defprotocol ToClojure
26 | (to-clojure [x] "Converts type to Clojure structure"))
27 |
28 | (extend-protocol ToClojure
29 | nil
30 | (to-clojure [x] nil)
31 |
32 | MessageAndMetadata
33 | (to-clojure [x] (KafkaMessage. (.topic x) (.offset x) (.partition x) (.key x) (.message x)))
34 |
35 | MessageAndOffset
36 | (to-clojure [x]
37 | (letfn [(byte-buffer-bytes [^ByteBuffer bb] (let [b (byte-array (.remaining bb))]
38 | (.get bb b)
39 | b))]
40 | (let [offset (.offset x)
41 | msg (.message x)]
42 | (KafkaMessage. nil offset nil (.key msg) (byte-buffer-bytes (.payload msg))))))
43 |
44 | Broker
45 | (to-clojure [x]
46 | {:connect (.connectionString x)
47 | :host (.host x)
48 | :port (.port x)
49 | :broker-id (.id x)})
50 |
51 | PartitionMetadata
52 | (to-clojure [x]
53 | {:partition-id (.partitionId x)
54 | :leader (to-clojure (.leader x))
55 | :replicas (map to-clojure (.replicas x))
56 | :in-sync-replicas (map to-clojure (.isr x))
57 | :error-code (.errorCode x)})
58 |
59 | TopicMetadata
60 | (to-clojure [x]
61 | {:topic (.topic x)
62 | :partition-metadata (map to-clojure (.partitionsMetadata x))})
63 |
64 | TopicMetadataResponse
65 | (to-clojure [x]
66 | (map to-clojure (.topicsMetadata x)))
67 |
68 | OffsetFetchResponse
69 | (to-clojure [x]
70 | (into {} (for [[k v] (.offsets x)] [(str (.topic k) ":" (.partition k)) v])))
71 |
72 | OffsetCommitResponse
73 | (to-clojure [x]
74 | (if (.hasError x)
75 | {:has-error true
76 | :errors (into {} (for [[k v] (.errors x)] [(str (.topic k) ":" (.partition k)) v]))}
77 | {:has-error false}))
78 |
79 | ConsumerMetadataResponse
80 | (to-clojure [x]
81 | {:error-code (.errorCode x)
82 | :coordinator (.coordinator x)
83 | }))
84 |
--------------------------------------------------------------------------------
/src/clj_kafka/new/producer.clj:
--------------------------------------------------------------------------------
1 | (ns ^{:doc "Clojure interface to the \"new\" Kafka Producer API. For
2 | complete JavaDocs, see:
3 | http://kafka.apache.org/082/javadoc/org/apache/kafka/clients/producer/package-summary.html"}
4 | clj-kafka.new.producer
5 | (:refer-clojure :exclude [send])
6 | (:import [java.util.concurrent Future TimeUnit TimeoutException]
7 | [org.apache.kafka.clients.producer Callback KafkaProducer ProducerRecord RecordMetadata]
8 | [org.apache.kafka.common.serialization Serializer ByteArraySerializer StringSerializer]))
9 |
10 | (defn string-serializer [] (StringSerializer.))
11 | (defn byte-array-serializer [] (ByteArraySerializer.))
12 |
13 | (defn producer
14 | "Return a `KafkaProducer` for publishing records to Kafka.
15 | `KafkaProducer` instances are thread-safe and should generally be
16 | shared for best performance.
17 |
18 | Implements `Closeable`, so suitable for use with `with-open`.
19 |
20 | For available config options, see:
21 | http://kafka.apache.org/documentation.html#newproducerconfigs "
22 | ([^java.util.Map config]
23 | (KafkaProducer. config))
24 | ([^java.util.Map config ^Serializer key-serializer ^Serializer value-serializer]
25 | (KafkaProducer. config key-serializer value-serializer)))
26 |
27 | (defn record
28 | "Return a record that can be published to Kafka using [[send]]."
29 | ([topic value]
30 | (ProducerRecord. topic value))
31 | ([topic key value]
32 | (ProducerRecord. topic key value))
33 | ([topic partition key value]
34 | (ProducerRecord. topic partition key value)))
35 |
36 | (defn- record-metadata->map
37 | [^RecordMetadata m]
38 | {:topic (.topic m)
39 | :partition (.partition m)
40 | :offset (.offset m)})
41 |
42 | (defn- map-future-val
43 | [^Future fut f]
44 | (reify
45 | java.util.concurrent.Future
46 | (cancel [_ interrupt?] (.cancel fut interrupt?))
47 | (get [_] (f (.get fut)))
48 | (get [_ timeout unit] (f (.get fut timeout unit)))
49 | (isCancelled [_] (.isCancelled fut))
50 | (isDone [_] (.isDone fut))))
51 |
52 | (defn send
53 | "Asynchronously send a record to Kafka. Returns a `Future` of a map
54 | with `:topic`, `:partition` and `:offset` keys. Optionally provide
55 | a callback fn that will be called when the operation completes.
56 | Callback should be a fn of two arguments, a map as above, and an
57 | exception. Exception will be nil if operation succeeded.
58 |
59 | For details on behaviour, see http://kafka.apache.org/082/javadoc/org/apache/kafka/clients/producer/KafkaProducer.html#send(org.apache.kafka.clients.producer.ProducerRecord,org.apache.kafka.clients.producer.Callback)"
60 | ([^KafkaProducer producer record]
61 | (let [fut (.send producer record)]
62 | (map-future-val fut record-metadata->map)))
63 | ([^KafkaProducer producer record callback]
64 | (let [fut (.send producer record (reify Callback
65 | (onCompletion [_ metadata exception]
66 | (callback (and metadata (record-metadata->map metadata)) exception))))]
67 | (map-future-val fut record-metadata->map))))
68 |
--------------------------------------------------------------------------------
/src/clj_kafka/offset.clj:
--------------------------------------------------------------------------------
1 | (ns ^{:doc "Offset operations."}
2 | clj-kafka.offset
3 | (:require [clojure.tools.logging :as log]
4 | [clj-kafka.core :refer [as-properties to-clojure]]
5 | [clj-kafka.consumer.simple :refer [topic-offset consumer]]
6 | [clj-kafka.zk :refer [partitions]])
7 | (:import [kafka.common TopicAndPartition OffsetAndMetadata]
8 | [kafka.javaapi OffsetFetchResponse ConsumerMetadataResponse OffsetCommitResponse]
9 | (kafka.network BlockingChannel)
10 | (kafka.api RequestOrResponse ConsumerMetadataRequest OffsetFetchRequest OffsetCommitRequest TopicMetadataRequest)
11 | (scala.collection JavaConversions)
12 | (scala.collection.mutable ArrayBuffer)))
13 |
14 | (def DEFAULT_CLIENT_ID "clj-kafka-id")
15 |
16 | (defn- parse-int [s]
17 | (Integer. (re-find #"\d+" s )))
18 |
19 | (defn- get-first-broker-config [broker-config]
20 | (let [first-broker (nth (.split broker-config ",") 0)]
21 | (.split first-broker ":" 2)))
22 |
23 | (defn- blocking-channel
24 | "Create a new blocking channel to the Kafka cluster.
25 | host is the broker server name or IP
26 | port is the broker server port"
27 | ([broker-config]
28 | (let [host-port-pair (get-first-broker-config broker-config)]
29 | (blocking-channel (nth host-port-pair 0) (nth host-port-pair 1))))
30 |
31 | ([host port]
32 | (blocking-channel host port nil))
33 |
34 | ([host port {:keys [read-buf-size write-buf-size read-timeout-ms] :as opts
35 | :or {read-buf-size (BlockingChannel/UseDefaultBufferSize)
36 | write-buf-size (BlockingChannel/UseDefaultBufferSize)
37 | read-timeout-ms 10000}}]
38 | (let [channel (BlockingChannel. host port read-buf-size write-buf-size read-timeout-ms)]
39 | (.connect channel)
40 | channel)))
41 |
42 | (defn- send-channel-message
43 | [^BlockingChannel channel ^RequestOrResponse message]
44 | (log/debug "Sending channel msg --> " message)
45 | (.send channel message))
46 |
47 | (defn- find-topic-partition-count [zk-config topic]
48 | (let [topic-partitions (partitions zk-config topic)]
49 | (.count topic-partitions)))
50 |
51 | (defn- topic-metadata-request
52 | ([topic] (topic-metadata-request topic 1 DEFAULT_CLIENT_ID))
53 | ([topic client-id] (topic-metadata-request topic 1 client-id))
54 | ([topic correlation-id client-id] (TopicMetadataRequest. (TopicMetadataRequest/CurrentVersion) correlation-id client-id (ArrayBuffer. topic))))
55 |
56 | (defn- consumer-metadata-request
57 | ([group-id] (consumer-metadata-request group-id 1 DEFAULT_CLIENT_ID))
58 | ([group-id client-id] (consumer-metadata-request group-id 1 client-id))
59 | ([group-id correlation-id client-id] (ConsumerMetadataRequest. group-id (ConsumerMetadataRequest/CurrentVersion) correlation-id client-id)))
60 |
61 | (defn- offset-fetch-request
62 | ([group-id topic max-partition] (offset-fetch-request group-id topic max-partition DEFAULT_CLIENT_ID))
63 | ([group-id topic max-partition client-id]
64 | (let [offset-request-version 1
65 | correlation-id 1
66 | topic-partition-java (map (fn [i] (TopicAndPartition. topic i)) (range 0 max-partition))
67 | topic-partition-scala (.toSeq (JavaConversions/asScalaBuffer topic-partition-java))]
68 | (OffsetFetchRequest. group-id topic-partition-scala offset-request-version correlation-id client-id))))
69 |
70 | (defn- offset-commit-request [group-id client-id topic new-offsets]
71 | (let [commit-request-version 1
72 | correlation-id 1
73 | now (System/currentTimeMillis)
74 | topic-partition-java (map (fn [i] (TopicAndPartition. topic i)) (range 0 (count new-offsets)))
75 | topic-partition-offsets (java.util.HashMap. (into {} (for [tp topic-partition-java] [tp (OffsetAndMetadata. (nth new-offsets (.partition tp)) "" now)])))
76 | emptyMap (JavaConversions/mapAsScalaMap topic-partition-offsets)
77 | topic-partition-offsets-scala (.$plus$plus (scala.collection.immutable.HashMap.) emptyMap)
78 | ]
79 | (OffsetCommitRequest. group-id topic-partition-offsets-scala commit-request-version correlation-id client-id -1 "")))
80 |
81 | (defn- try-fecth-topic-offset [single-broker-config topic partition new-offset-type]
82 | (let [bk-host-port-pair (get-first-broker-config single-broker-config)
83 | bk-host (nth bk-host-port-pair 0)
84 | bk-port (parse-int (nth bk-host-port-pair 1))
85 | consumer (consumer bk-host bk-port DEFAULT_CLIENT_ID)]
86 | (topic-offset consumer topic partition new-offset-type)))
87 |
88 | (defn- fecth-topic-offset [broker-config topic partition new-offset-type]
89 | (let [brokers (.split broker-config ",")
90 | potential-offsets (map (fn [single-broker] (try-fecth-topic-offset single-broker topic partition new-offset-type)) brokers)]
91 | (first (filter #(not (nil? %)) potential-offsets))
92 | ))
93 |
94 | (defn- find-offset-manager
95 | ([broker-config group-id] (find-offset-manager broker-config group-id DEFAULT_CLIENT_ID))
96 | ([broker-config group-id client-id]
97 | (let [host-port-pair (get-first-broker-config broker-config)
98 | host (nth host-port-pair 0)
99 | port (parse-int (nth host-port-pair 1))
100 | channel-attempt (blocking-channel host port)
101 | metadata-req (consumer-metadata-request group-id client-id)]
102 | (send-channel-message channel-attempt metadata-req)
103 | (let [meta-response (to-clojure (ConsumerMetadataResponse/readFrom (.buffer (.receive channel-attempt))))]
104 | (if-let [no-error (= (kafka.common.ErrorMapping/NoError) (:error-code meta-response))]
105 | (if-let [same-channel (and (= host (.host (:coordinator meta-response))) (= port (.port (:coordinator meta-response))))]
106 | channel-attempt
107 | (let [coordinator (:coordinator meta-response)
108 | new-host (.host coordinator) new-port (.port coordinator)]
109 | (.disconnect channel-attempt)
110 | (blocking-channel new-host new-port)))
111 | (throw (RuntimeException. (str meta-response))))
112 | ))))
113 |
114 |
115 | (defn fetch-consumer-offsets
116 | "Fetches the current offsets for a topic and a given consumer group.
117 |
118 | Parameters:
119 | broker-config - a comma separated list of host:port pairs
120 | zk-config - a map that has at least one entry \"zookeeper.connect\" \"host:port\"
121 | topic - the topic name
122 | group-id - consumer group id
123 |
124 | Return:
125 | { offset, .... }
126 | "
127 |
128 | [broker-config zk-config topic group-id]
129 | (let [offset-manager (find-offset-manager broker-config group-id)
130 | partition-count (find-topic-partition-count zk-config topic)
131 | offset-fetch-req (offset-fetch-request group-id topic partition-count DEFAULT_CLIENT_ID)
132 | ]
133 | (send-channel-message offset-manager offset-fetch-req)
134 | (let [offset-fetch-resp (to-clojure (OffsetFetchResponse/readFrom (.buffer (.receive offset-manager))))]
135 | (log/debug "fetch-consumer-offsets-response: " offset-fetch-resp)
136 | (.disconnect offset-manager)
137 | offset-fetch-resp)
138 | ))
139 |
140 | (defn reset-consumer-offsets
141 | "Resets the current offsets for a topic and a given consumer group.
142 |
143 | Parameters:
144 | broker-config - a comma separated list of \"host:port\" pairs
145 | zk-config - a map that has at least one entry \"zookeeper.connect\" \"host:port\"
146 | topic - the topic name
147 | group-id - consumer group id
148 | offset-position - supported values are :earliest|:latest
149 |
150 | Return:
151 | {:has-error true|false, :errors { error_code, .... } }"
152 | [broker-config zk-config topic group-id offset-position]
153 | (let [offset-manager (find-offset-manager broker-config group-id)
154 | partition-count (find-topic-partition-count zk-config topic)
155 | new-offsets (map (fn [i] (fecth-topic-offset broker-config topic i offset-position)) (range 0 partition-count))
156 | offset-commit-req (offset-commit-request group-id DEFAULT_CLIENT_ID topic new-offsets)
157 | ]
158 | (send-channel-message offset-manager offset-commit-req)
159 | (let [offset-commit-resp (to-clojure (OffsetCommitResponse/readFrom (.buffer (.receive offset-manager))))]
160 | (log/debug "reset-consumer-offsets-response: " offset-commit-resp)
161 | (.disconnect offset-manager)
162 | offset-commit-resp)))
--------------------------------------------------------------------------------
/src/clj_kafka/producer.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.producer
2 | (:import [kafka.javaapi.producer Producer]
3 | [kafka.producer ProducerConfig KeyedMessage]
4 | [java.util List])
5 | (:use [clj-kafka.core :only (as-properties)]))
6 |
7 | (defn producer
8 | "Creates a Producer. m is the configuration
9 | metadata.broker.list : \"server:port,server:port\""
10 | [m]
11 | (Producer. (ProducerConfig. (as-properties m))))
12 |
13 | (defn message
14 | ([topic value] (message topic nil value))
15 | ([topic key value] (KeyedMessage. topic key value)))
16 |
17 | (defn send-message
18 | [^Producer producer ^KeyedMessage message]
19 | (.send producer message))
20 |
21 | (defn send-messages
22 | [^Producer producer ^List messages]
23 | (.send producer messages))
24 |
--------------------------------------------------------------------------------
/src/clj_kafka/zk.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.zk
2 | (:use [clojure.data.json :only (read-str)]
3 | [clj-kafka.core :only (with-resource)])
4 | (:require [zookeeper :as zk]
5 | [clojure.string :as s])
6 | (:import [org.apache.zookeeper KeeperException$NoNodeException]))
7 |
8 | (defn brokers
9 | "Get brokers from zookeeper"
10 | [m]
11 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
12 | zk/close
13 | (if-let [broker-ids (zk/children z "/brokers/ids")]
14 | (doall (map (comp #(read-str % :key-fn keyword)
15 | #(String. ^bytes %)
16 | :data
17 | #(zk/data z (str "/brokers/ids/" %)))
18 | broker-ids))
19 | '())))
20 |
21 | (defn broker-list
22 | "Returns a comma separated list of Kafka brokers, as returned from clj-kafka.zk/brokers.
23 | e.g.: (broker-list (brokers {\"zookeeper.connect\" \"127.0.0.1:2181\"})) "
24 | [brokers]
25 | (when (seq brokers)
26 | (s/join "," (map (fn [{:keys [host port]}] (str host ":" port)) brokers))))
27 |
28 | (defn- controller-broker-id
29 | [^String zk-data]
30 | (get (read-str zk-data) "brokerid"))
31 |
32 | (defn controller
33 | "Get leader node"
34 | [m]
35 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
36 | zk/close
37 | (-> (zk/data z "/controller")
38 | :data
39 | String.
40 | controller-broker-id)))
41 |
42 | (defn topics
43 | "Get topics"
44 | [m]
45 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
46 | zk/close
47 | (zk/children z "/brokers/topics")))
48 |
49 | (defn partitions
50 | "Returns a map of partitions and replica ids. e.g. {\"1\" [0], \"0\" [0]}"
51 | [m topic]
52 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
53 | zk/close
54 | (-> (zk/data z (str "/brokers/topics/" topic))
55 | :data
56 | String.
57 | read-str
58 | (get "partitions"))))
59 |
60 | (defn offset-path
61 | [consumer-group topic partition]
62 | (str "/consumers/" consumer-group "/offsets/" topic "/" partition))
63 |
64 | (defn committed-offset
65 | [m consumer-group topic partition]
66 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
67 | zk/close
68 | (try (-> (zk/data z (offset-path consumer-group topic partition))
69 | :data
70 | (String. )
71 | (Long/valueOf))
72 | (catch KeeperException$NoNodeException e
73 | nil))))
74 |
75 | (defn set-offset!
76 | [m consumer-group topic partition offset]
77 | {:pre [(or (nil? offset) (number? offset))]}
78 | (let [path (offset-path consumer-group topic partition)]
79 | (with-resource [z (zk/connect (get m "zookeeper.connect"))]
80 | zk/close
81 | (if (nil? offset)
82 | (zk/delete z path)
83 | (if-let [{:keys [version] :as m} (zk/exists z path)]
84 | (zk/set-data z path (.getBytes (str offset)) version)
85 | (zk/create-all z path :persistent? true :data (.getBytes (str offset))))))))
86 |
--------------------------------------------------------------------------------
/test/clj_kafka/test/consumer/simple.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.consumer.simple
2 | (:use clj-kafka.consumer.simple
3 | expectations
4 | [clj-kafka.test.utils :only (with-test-broker)]))
5 |
6 | (def test-broker-config {:zookeeper-port 2182
7 | :kafka-port 9999
8 | :topic "test"})
9 |
10 | (given (with-test-broker test-broker-config
11 | (let [c (consumer "127.0.0.1" 9999 "simple-consumer")]
12 | (topic-meta-data c ["test"])))
13 | (expect count 1
14 | first {:topic "test",
15 | :partition-metadata [{:partition-id 0,
16 | :leader {:connect "localhost:9999",
17 | :host "localhost",
18 | :port 9999
19 | :broker-id 0},
20 | :replicas [{:connect "localhost:9999",
21 | :host "localhost",
22 | :port 9999
23 | :broker-id 0}],
24 | :in-sync-replicas [{:connect "localhost:9999",
25 | :host "localhost",
26 | :port 9999
27 | :broker-id 0}],
28 | :error-code 0}]}))
29 |
30 | (given (with-test-broker test-broker-config
31 | (let [c (consumer "127.0.0.1" 9999 "simple-consumer")]
32 | (latest-topic-offset c "test" 0)))
33 | (expect identity 0))
34 |
--------------------------------------------------------------------------------
/test/clj_kafka/test/consumer/zk.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.consumer.zk
2 | (:use [expectations]
3 | [clj-kafka.core :only (with-resource to-clojure)]
4 | [clj-kafka.producer :only (producer send-messages message)]
5 | [clj-kafka.test.utils :only (with-test-broker)])
6 | (:require [clj-kafka.consumer.zk :as zk]))
7 |
8 | (def producer-config {"metadata.broker.list" "localhost:9999"
9 | "serializer.class" "kafka.serializer.DefaultEncoder"
10 | "partitioner.class" "kafka.producer.DefaultPartitioner"})
11 |
12 | (def test-broker-config {:zookeeper-port 2182
13 | :kafka-port 9999
14 | :topic "test"})
15 |
16 | (def consumer-config {"zookeeper.connect" "localhost:2182"
17 | "group.id" "clj-kafka.test.consumer"
18 | "auto.offset.reset" "smallest"
19 | "auto.commit.enable" "false"})
20 |
21 | (defn string-value
22 | [k]
23 | (fn [m]
24 | (String. (k m) "UTF-8")))
25 |
26 | (defn test-message
27 | []
28 | (message "test" (.getBytes "Hello, world")))
29 |
30 | (defn send-and-receive
31 | [messages]
32 | (with-test-broker test-broker-config
33 | (with-resource [c (zk/consumer consumer-config)]
34 | zk/shutdown
35 | (let [p (producer producer-config)]
36 | (send-messages p messages)
37 | (first (zk/messages c "test"))))))
38 |
39 | (given (send-and-receive [(test-message)])
40 | (expect :topic "test"
41 | :offset 0
42 | :partition 0
43 | (string-value :value) "Hello, world"))
44 |
--------------------------------------------------------------------------------
/test/clj_kafka/test/offset.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.offset
2 | (:use [expectations]
3 | [clj-kafka.core :only (with-resource)]
4 | [clj-kafka.producer :only (producer send-messages message)]
5 | [clj-kafka.test.utils :only (with-test-broker)]
6 | [clj-kafka.offset :only (fetch-consumer-offsets reset-consumer-offsets)])
7 | (:require [clj-kafka.consumer.zk :as zk]))
8 |
9 | (def producer-config {"metadata.broker.list" "localhost:9999"
10 | "serializer.class" "kafka.serializer.DefaultEncoder"
11 | "partitioner.class" "kafka.producer.DefaultPartitioner"})
12 |
13 | (def test-broker-config {:zookeeper-port 2182
14 | :kafka-port 9999
15 | :topic "test"})
16 |
17 | (def consumer-config {"zookeeper.connect" "localhost:2182"
18 | "group.id" "clj-kafka.test.consumer"
19 | "auto.offset.reset" "smallest"
20 | "offsets.storage" "kafka"
21 | "auto.commit.interval.ms" "100"
22 | "auto.commit.enable" "true"})
23 |
24 | (defn test-message
25 | [body]
26 | (message "test" (.getBytes body)))
27 |
28 | (defn send-consume-fetch
29 | [messages]
30 | (with-test-broker test-broker-config
31 | (with-resource [c (zk/consumer consumer-config)]
32 | zk/shutdown
33 | (let [p (producer producer-config)]
34 | (send-messages p messages)
35 |
36 | (let [msgs (take 3 (zk/messages c "test"))]
37 | (str "Received msgs: " msgs))
38 | (zk/shutdown c)
39 | (Thread/sleep 100)
40 |
41 | (let [offset-response (fetch-consumer-offsets "localhost:9999,localhost:9999" consumer-config "test" "clj-kafka.test.consumer")
42 | ignore (str offset-response)
43 | offset (.offset (get offset-response "test:0"))]
44 | offset)))))
45 |
46 | (given (send-consume-fetch [(test-message "msg 1") (test-message "msg 2") (test-message "msg 3")])
47 | (expect identity 3))
48 |
49 | (defn send-consume-reset-fetch
50 | [messages]
51 | (with-test-broker test-broker-config
52 | (with-resource [c (zk/consumer consumer-config)]
53 | zk/shutdown
54 | (let [p (producer producer-config)]
55 | (send-messages p messages)
56 |
57 | (let [msgs (take 2 (zk/messages c "test"))]
58 | (str "Received msgs: " msgs))
59 | (zk/shutdown c)
60 | (Thread/sleep 100)
61 |
62 | (let [offset-reset-response (reset-consumer-offsets "localhost:9999,localhost:9999" consumer-config "test" "clj-kafka.test.consumer", :earliest)
63 | ignore (str offset-reset-response)]
64 | offset-reset-response)
65 | (Thread/sleep 100)
66 |
67 | (let [offset-response (fetch-consumer-offsets "localhost:9999,localhost:9999" consumer-config "test" "clj-kafka.test.consumer")
68 | ignore (str offset-response)
69 | offset (.offset (get offset-response "test:0"))]
70 | offset)))))
71 |
72 | (given (send-consume-reset-fetch [(test-message "msg 1") (test-message "msg 2")])
73 | (expect identity 0))
--------------------------------------------------------------------------------
/test/clj_kafka/test/producer.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.producer
2 | (:use [expectations]
3 | [clj-kafka.producer])
4 | (:import [kafka.producer KeyedMessage]))
5 |
6 | (expect KeyedMessage (message "topic" "value"))
7 |
8 |
9 |
--------------------------------------------------------------------------------
/test/clj_kafka/test/utils.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.utils
2 | (:import
3 | [kafka.admin AdminUtils]
4 | [kafka.server KafkaConfig KafkaServer]
5 | [java.net InetSocketAddress]
6 | [org.apache.zookeeper.server ZooKeeperServer NIOServerCnxnFactory]
7 | [org.apache.commons.io FileUtils]
8 | [org.I0Itec.zkclient ZkClient]
9 | [org.I0Itec.zkclient.serialize ZkSerializer]
10 | [kafka.utils Time]
11 | [java.util Properties])
12 | (:require [clj-kafka.admin :as admin])
13 | (:use [clojure.java.io :only (file)]
14 | [clj-kafka.core :only (as-properties)]))
15 |
16 | (defn tmp-dir
17 | [& parts]
18 | (.getPath (apply file (System/getProperty "java.io.tmpdir") "clj-kafka" parts)))
19 |
20 | (def system-time (proxy [Time] []
21 | (milliseconds [] (System/currentTimeMillis))
22 | (nanoseconds [] (System/nanoTime))
23 | (sleep [ms] (Thread/sleep ms))))
24 |
25 | ;; enable.zookeeper doesn't seem to be used- check it actually has an effect
26 | (defn create-broker
27 | [{:keys [kafka-port zookeeper-port]}]
28 | (let [base-config {"broker.id" "0"
29 | "port" "9999"
30 | "host.name" "localhost"
31 | "zookeeper.connect" (str "127.0.0.1:" zookeeper-port)
32 | ;"enable.zookeeper" "true"
33 | "log.flush.interval.messages" "1"
34 | "auto.create.topics.enable" "true"
35 | "log.dir" (.getAbsolutePath (file (tmp-dir "kafka-log")))}]
36 | (KafkaServer. (KafkaConfig. (as-properties (assoc base-config "port" (str kafka-port))))
37 | system-time)))
38 |
39 | (defn create-zookeeper
40 | [{:keys [zookeeper-port]}]
41 | (let [tick-time 500
42 | zk (ZooKeeperServer. (file (tmp-dir "zookeeper-snapshot")) (file (tmp-dir "zookeeper-log")) tick-time)]
43 | (doto (NIOServerCnxnFactory.)
44 | (.configure (InetSocketAddress. "127.0.0.1" zookeeper-port) 100)
45 | (.startup zk))))
46 |
47 | (defn wait-until-initialised
48 | [^KafkaServer kafka-server topic]
49 | (let [cache (.. kafka-server apis metadataCache)
50 | topics (scala.collection.JavaConversions/asScalaSet #{topic})]
51 | (while (< (.. cache (getTopicMetadata topics) size) 1)
52 | (Thread/sleep 500))))
53 |
54 |
55 | (defmacro with-test-broker
56 | "Creates an in-process broker that can be used to test against"
57 | [config & body]
58 | `(do (FileUtils/deleteDirectory (file (tmp-dir)))
59 | (let [zk# (create-zookeeper ~config)
60 | kafka# (create-broker ~config)
61 | topic# (:topic ~config)]
62 | (try
63 | (.startup kafka#)
64 | (let [zk-client# (admin/zk-client (str "127.0.0.1:" (:zookeeper-port ~config))
65 | {:session-timeout-ms 500
66 | :connection-timeout-ms 500})]
67 | (admin/create-topic zk-client# topic#)
68 | (wait-until-initialised kafka# topic#)
69 | ~@body)
70 | (finally (do (.shutdown kafka#)
71 | (.awaitShutdown kafka#)
72 | (.shutdown zk#)
73 | (FileUtils/deleteDirectory (file (tmp-dir)))))))))
74 |
--------------------------------------------------------------------------------
/test/clj_kafka/test/zk.clj:
--------------------------------------------------------------------------------
1 | (ns clj-kafka.test.zk
2 | (:use expectations
3 | clj-kafka.zk
4 | [clj-kafka.test.utils :only (with-test-broker)]))
5 |
6 | (def config {:zookeeper-port 2182
7 | :kafka-port 9999
8 | :topic "test"})
9 |
10 | (def zk-connect {"zookeeper.connect" "127.0.0.1:2182"})
11 |
12 | (given (with-test-broker config
13 | (brokers zk-connect))
14 | (expect count 1))
15 |
16 | (expect nil (broker-list []))
17 | (expect "localhost:2181" (broker-list [{:host "localhost" :port "2181"}]))
18 |
19 | (given (with-test-broker config
20 | (first (brokers zk-connect)))
21 | (expect :host "localhost"
22 | :jmx_port -1
23 | :port 9999
24 | :version 1))
25 |
26 | (given (with-test-broker config
27 | (controller zk-connect))
28 | (expect identity 0))
29 |
30 | (given (with-test-broker config
31 | (topics zk-connect))
32 | (expect count 1
33 | first (:topic config)))
34 |
--------------------------------------------------------------------------------
/update-docs.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | git subtree push --prefix doc origin gh-pages
4 |
--------------------------------------------------------------------------------