稍显诡异的MongoDB Collection

今天给同事演示的时候露怯了,直接飞出个异常。

对一个不存在的collection,find,count之类的操作都没问题,但是直接mapReduce就完蛋了,告诉我“ns doesn’t exist”。

解决办法有两个:

  1. 查询db的system.namespaces,这样最可靠
  2. 直接count,如果是0,可以当作没有来处理;不过这个要看业务逻辑,因为collection里面没有数据的时候也会返回0

有人提了新加几个接口的需求,不知道什么时候会做进去:http://jira.mongodb.org/browse/SERVER-1938

Lift的i18n

基本上是转帖:http://www.assembla.com/wiki/show/liftweb/Internationalization

但是还上要说一下,设计得太爽了。没怎么用过其他的web框架,不过Lift提供的真是好用。尤其是最后一点,template也可以直接国际化:index_en_US.html,index_zh_CN.html。不是所有都可以直接通过resource bundle来进行翻译,所以直接对template也就是页面本身来搞,真是很爽。

Lift里进行MongoDB的MapReduce

其实说Lift里不够准确,Lift对MapReduce没做什么封装,基本上就是直接调用mongo-java-driver的API。

举例说明,计算所有URL的点击次数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    def countClicks = {
      MongoDB.useCollection(shortenedUrl.collectionName) {
        x => {
          val map = """function() { emit("totalClickCount", this.%s); }""" format ShortenedUrl.clickCount.name
          val reduce = """function(key, values) { return Array.sum(values); }"""
          val results = x.mapReduce(map, reduce, null, null).results
 
          /**
           * all numbers returned by mongodb is Double since this is how number defined by javascript
           */
          if (results.hasNext) results.next.get("value").asInstanceOf[Number].intValue.toString else "0"
        }
      }
    }

map的时候把this.clickCount的值塞给”totalClickCount”这个key,reduce把所有这些值加起来,MongoDB会生成一个临时的collection,从里面选择“value”这个字段就可以了。

需要注意的是所有返回的数值类型都是Double,虽然BSON里对各种类型都有定义,但是目前为止MongoDB只支持返回Double。对js了解的人可能会比较清楚,但我就惨了。调了很长时间,一个bit一个bit的看,甚至还去MongoDB的JIRA上问:http://jira.mongodb.org/browse/SERVER-2688。土死了……

Lift, MongoDB以及分页

说来惭愧,从来没写过分页的代码,知道是怎么回事儿,但没干过总归差了这么一点儿。

MongoDB和传统的数据库类似,提供了skip和limit,前者用来跳过一批记录,后者用来选择多少条。怎么用这里有很详细的解释:http://www.mongodb.org/display/DOCS/Advanced+Queries,就不多说了。重点讨论Lift里面怎么用。

分页通常有这么几个条件:排序字段、排序方式(升序还是降序)、每页显示条数、当前页面。这些参数可以通过URL传递,譬如:sort-by=linkId&sort-order=-1&perpage=3&page=2,然后HTTP GET发送。

对于这种per request的参数,当然可以用的时候直接从著名的“S”里面取,也可以用RequestVar:

1
2
3
4
5
object page extends RequestVar[Int](S.param("page").openOr("1").toInt)
object perpage extends RequestVar[Int](S.param("perpage").openOr("10").toInt)
object offset extends RequestVar[Int]((page - 1) * perpage)
object sortBy extends RequestVar[String](S.param("sort-by").openOr(ShortenedUrl.linkId.name))
object sortOrder extends RequestVar[Int](S.param("sort-order").openOr("-1").toInt)

这其中offset表示当前页的起始条目,-1表示降序,默认排序字段为linkId。

只有这些还不过瘾,我们再加上搜索条件:

  1. 关键字
  2. 点击次数
1
2
3
4
object search extends RequestVar[String](S.param("search").openOr(""))
object searchIn extends RequestVar[String](S.param("search-in").openOr(ShortenedUrl.originUrl.name))
object clickFilter extends RequestVar[String](S.param("click-filter").openOr("gte"))
object clickLimit extends RequestVar[String](S.param("click-limit").openOr(""))

默认搜索originUrl,点击次数大于等于某个值。

有过数据库搜索设计经验的人一般都会这么干:

1
select * from table where 1=1

然后在后面拼搜索条件:

1
and originUrl like '%google%' and clickCount >= 10 sort by linkId skip 2 limit 10

我们如法炮制,不过稍微改变一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
object clickObject extends RequestVar[JObject](
    if (clickLimit.isEmpty) JObject(Nil)
    else (ShortenedUrl.clickCount.name -> (("$" + clickFilter) -> clickLimit.is.toInt))
)
 
object searchObject extends RequestVar[JObject](
  if (search.isEmpty) JObject(Nil)
  else ("$where" -> ("this." + searchIn + ".indexOf('" + search + "') != -1"))
)
 
object findOptions extends RequestVar[List[FindOption]](
  List(Skip(offset), Limit(perpage))
)
 
shortenedUrl.findAll(clickObject.is ~ searchObject.is,
    (sortBy.is -> sortOrder.is), findOptions: _*)

如果没有搜索条件,返回Nil表示空的List;否则(x -> y)构建一个JObject(这里是Scala的语法糖衣,背后发生了很多);$where那里纯粹是MongoDB特有的,根本就是js;Skip和Limit跟SQL的含义完全相同。这样对最后一个statement的解读也就很自然了。

数据的事情搞定了,剩下就是页面处理,Lift再次表示了自己的牛逼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    def generateNav: NodeSeq = {
      def generateHref(page: Int) = "/?search=" + search + "&sort-by=" + sortBy + "&sort-order=" + sortOrder +
              "&search-in=" + searchIn + "&click-filter=" + clickFilter + "&click-limit=" + clickLimit +
              "&perpage=" + perpage + "&page=" + page
 
      val left = if (page.is != 1) <a title="{&quot;«" href="{generateHref(page">«</a>
      else Nil
 
      val pages = (1 to totalPages).toList.map {
        x =>
          if (x == page.is)
            <strong>
              {"[" + x + "]"}
            </strong>
          else
            <a title="{&quot;Page" href="{generateHref(x)}">
              {x}
            </a>
      }
 
      val right = if (page.is != totalPages) <a title="{&quot;Go" href="{generateHref(page.is">»</a>
      else Nil
 
      left ++ pages ++ right
    }

我写得比较烂,也就这么几行。效果就是这样:

 

Mac里面的JDK的源码和javadoc

在Apple还没完全转到OpenJDK之前,他自家的东西还是得用着。不过默认JDK源码和javadoc是不会装的。

到这里下:https://connect.apple.com/,右边找Dowloads->Java。

需要ADC,没有的话自己注册一个,也不花钱。

10.6 update 2之前是叫Developer Document,update 3之后就叫Developer Package了。找需要的下。装好之后在这里:/Library/Java/JavaVirtualMachines/<version>/Contents/Home。同样是src.jar和docs.jar,另外还有苹果自己的一个appledocs.jar。

Lift与MongoDB

越来越多的公司和组织掺和到NoSQL运动里来,我也跟风玩玩儿MongoDB。

Lift对MongoDB已经有了很好的支持:http://www.assembla.com/wiki/show/liftweb/MongoDB

下面这段例子是一个非常简单的model设计:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ShortenedUrl extends MongoRecord[ShortenedUrl] with MongoId[ShortenedUrl] {
  def meta = ShortenedUrl
 
  object linkId extends StringField(this, 10)
 
  object originUrl extends StringField(this, 500)
 
  object shortUrl extends StringField(this, 100)
 
  object date extends DateField(this)
 
  object ip extends StringField(this, 15)
 
  object clickCount extends IntField(this)
}
 
object ShortenedUrl extends ShortenedUrl with MongoMetaRecord[ShortenedUrl]
 
class NextId extends MongoRecord[NextId] with MongoId[NextId] {
  def meta = NextId
 
  object next extends StringField(this, 10)
}
 
object NextId extends NextId with MongoMetaRecord[NextId]

这个东西是我仿照yourls做的数据模型。很简单,两个collection,一个记录缩短域名的所有信息,一个记录下一个URL的id是什么。

查找:

1
ShortenedUrl.find(ShortenedUrl.linkId.name -> id)

存储:

1
2
currentShortenedUrl.linkId(linkId).shortUrl(Props.get("site").open_! + "/" + linkId).
                ip(containerRequest.open_!.remoteAddress).clickCount(0).save

根本不用描述,太简单了。

关于Lift的CSS Binding

具体怎么回事儿,这里写得很清楚,就不啰嗦了:http://www.assembla.com/wiki/show/liftweb/Binding_via_CSS_Selectors

有一点需要特别说明一下:为了彻底把页面设计和后台代码分离,我希望所有和页面布局展示的地方都用静态html实现,然后在snippet里面作binding。这时候就需要TemplateFinder了。

看下面这段:

1
2
3
4
5
6
7
8
9
10
TemplateFinder.findAnyTemplate(List(TemplatesHidden, "edit")) map {
  "#real-content ^^")#> "true" andThen
    "#real-conent [id]" #> (EditPrefix + shortenedUrl.linkId.value) &
    "#edit-url [name]" #> urlId &
    "#edit-url [value]" #> shortenedUrl.originUrl.value &
    "#edit-url [id]" #>; urlId &
    "#save-button [onclick]" #&gt; js.toJsCmd &
    "#save-button [id]" #> (EditPrefix + "submit-" + shortenedUrl.linkId.value) &
    "#cancel-button [onclick]" #> ("hide_edit('" + shortenedUrl.linkId.value + "')") &
    "#cancel-button [id]" #> (EditPrefix + "close-" + shortenedUrl.linkId.value)

edit.html是一个完整的静态html,用来显示一个table,上面代码做的事情就是选中id为real-content的这个节点,然后对它做CSS的binding以实现动态页面。

如何输出完整的菜单系统

Lift默认不会输出整个菜单系统,只有top level,点击包含子项的菜单才会输出下面的层次。这样带来的问题是,如果使用superfish之类的js来控制和渲染就不行了。这个问题相当容易解决:

1
<span class="lift:Menu.builder?expandAll"></span>

加上expandAll就行了。

关于Lift的一些事情

最近在试着用Lift写一个缩URL的东西,由于这个东西相对来说比之前做的小玩意儿复杂一些,写几篇东西作为记录,省得总是要解决之前早就已经解决过的问题。

How to Make Embedded Tomcat Support Hot Deploy

If you search “embedded tomcat” in google, you will get a bunch of instructions how to do this, but non of them mentioned how to enable hot deploy.

1
2
3
4
5
6
Embedded embedded = new Embedded();
 
// create engine, host, connector, context
...
 
embedded.start();

The above code will not enable hot deploy by default. So what we need to do is adding a LifeCycleListener to the host we create.

1
2
3
4
5
6
7
8
9
10
11
12
Embedded embedded = new Embedded();
 
...
 
StandardHost host = (StandardHost) embedded.createHost("localhost",
        getHome() + "/webapps");
host.setAutoDeploy(true);
host.setDeployOnStartup(true);
host.addLifecycleListener(new HostConfig());
 
...
embedded.start();

And the following things are the same as the stand alone Tomcat: define “.xml” and put war files or directory to “/webapps”.

One more thing about how to deploy the default web app:

  • use ROOT.xml, and ROOT.war
  • or use ROOT.xml and define “docBase” pointing to the war file or directory which should not be under “appBase”, and you can name the war or directory anything you like; if symbolic link is used and the original war file or directory get modified, your web app will also be redeployed