记录下一个简单的scala sql DSL

2011-12-22 16:55:01.0

记录下一个简单的scala sql DSL

一个日本人写的DSL 原网址:https://github.com/yuroyoro/Squire

总共两个类,基于twitter的querulous框架

package com.yuroyoro.squire
import java.sql.ResultSet
import scala.collection.mutable.ArrayBuffer
import com.twitter.querulous.evaluator.QueryEvaluator
trait SqlCommand {
val head:Option[SqlCommand]
val command:String
def arg:String
val pms = new ArrayBuffer[Any]
def constract = command format arg
def query:String = head match {
case None => constract
case Some(cmd) => cmd.query + " " + constract
}
def params:ArrayBuffer[Any] = head match{
case None => pms
case Some(cmd) => cmd.params ++ pms
}
override def toString = query
}
trait Selectable extends SqlCommand{
def apply[A](f: ResultSet => A)( implicit qe:QueryEvaluator ):Seq[A] = select( f )( qe )
def select[A](f: ResultSet => A)( implicit qe:QueryEvaluator ): Seq[A] =
qe.select( query , params: _* )(f)
def selectOne[A](f: ResultSet => A)( implicit qe:QueryEvaluator ): Option[A] =
qe.selectOne( query , params: _* )(f)
def count( implicit qe:QueryEvaluator ): Int =
qe.count( query , params: _* )
}
trait Executable extends SqlCommand{
def apply( implicit qe:QueryEvaluator ): Int = execute( qe )
def execute( implicit qe:QueryEvaluator ): Int = qe.execute( query ,  params: _* )
}
trait SelectConditionale extends Selectable {
def where( cond:Condition ) = new Where( this , cond ) with Selectable with Groupable with Sortable
}
trait ExecuteConditionale extends Executable {
def where( cond:Condition ) = new Where( this , cond ) with Executable
}
trait Groupable extends Selectable{
def group( cond:String ) = new Group( this, cond ) with Sortable
}
trait Sortable extends Selectable {
def order( cond:String ) = new Order( this, cond ) with Selectable
}
case class By( columns:String ) {
def asc = columns + " ASC"
def desc = columns + " DESC"
}
class Select ( val arg:String ) extends SqlCommand {
val head = None
val command = "SELECT %s"
def from( table:String ) = new From( this , table ) with SelectConditionale
}
class From( val h:SqlCommand, val arg:String ) extends SqlCommand {
val head = Some(h)
val command = "FROM %s"
}
class Where( val h:SqlCommand, cond:Condition ) extends SqlCommand{
val head = Some(h)
def arg = cond.condition
pms ++= cond.params
val command = "WHERE %s"
}
class Group( val h:SqlCommand, val arg:String ) extends SqlCommand {
val head = Some(h)
val command = "GROUP BY %s"
}
class Order( val h:SqlCommand, val arg:String ) extends SqlCommand {
val head = Some(h)
val command = "ORDER BY %s"
}
class Insert extends SqlCommand{
val head = None
def arg:String = ""
val command = "INSERT"
def into( table:String ) = new Into( this, table ) with SelectConditionale
def values( values:Any* ) = new Values( this , values: _* ) with Executable
}
class Into( val h:SqlCommand, table:String ) extends SqlCommand{
val head = Some(h)
val command = "INTO %s"
var cols:String = ""
override def arg = table + " " + cols
def apply( columns:String* ) = {
cols = columns.mkString( "(", ",", ")" )
this
}
def values( values:Any* ) = new Values( this , values: _* ) with Executable
}
class Values( val h:SqlCommand, values:Any* ) extends SqlCommand {
val head = Some(h)
val command = "VALUES %s"
pms ++= values
override def arg = Array.make( values.size, "?").mkString( "(", ",", ")" )
}
class Update( val arg:String ) extends SqlCommand{
val head = None
val command = "UPDATE %s"
def set( sets:SetVal* ) = new SetValues( this, sets: _* ) with ExecuteConditionale
}
class SetValues( val h:SqlCommand, sets:SetVal* ) extends SqlCommand {
val head = Some(h)
val command = "SET %s"
var cols:String = ""
pms ++= sets.map{ _.param }
override def arg = sets.mkString(",")
}
case class SetVal( column:String ){
var param:Any = null
def =/( v:Any ) = param = v
override def toString = "%s = ?".format( column )
}

scala定义ruby中的times方法

2011-12-21 10:21:47.0

在Ruby中int类有个times方法,大概使用方式是:

5 times{pritln("hello world"}

将打印出5次hello world

在scala中类似的使用方法是

(1 to 5).foreach(println("hello world")

不过还是不如ruby的使用直观

下面我们可以通过scala强大的implicit 翻译过来就是隐式转换来实现这个功能,scala的隐式转换就好像js.protype给原生类加上新的方法

scala用while循环读取reader或者流

2011-12-06 15:07:06.0

在scala中希望通过JAVA的那种方式来读取文件while( (line = reader.readNext()) != null ) { .... }

编译的时候警告 values of types Unit and Null using `!=' will always yield true

原因是scala中并不支持A=B=C这种方式来赋值

搜索了相关资料,可以通过花括号来解决装这个问题

while({line=reader.readNext; line != null})

在scala中使用java的集合类

2011-11-30 13:49:27.0

在scala中默认就可以使用JAVA的集合类比如list,set,map等。但是只能使用JAVA中的方法。

比如scala非常方便的foreach就不能使用了

编译器提示如下错误:

value foreach is not a member of java.util.List

难道scala对JAVA的兼容性只能用java的原始方法?

google了下 在类中导入如下语句

import scala.collection.JavaConversions._
objs.toList.foreach(obj => 。。。)

scala中的占位符

2011-11-29 11:44:05.0

本文特意介绍了下scala语言中的占位符,主要是一些语法糖,和编程上的一些便利性, scala中的占位符让人眼前一亮,这种魔术代码在写代码的时候还是很有用的;

占用符,就是_ 在scala的代码中会看到大量的_

先来段简单的

def sum(x:Int,y:Int,z:Int) :Int = x+y+z
val s=sum _
println(s(4,5,6))

再看这个

def sum(x:Int,y:Int,z:Int) :Int = x+y+z
val s=sum(2,3,_:Int)
println(s(4))

Java实现blog ping

2010-07-28 16:37:49.0

想给博客加上pingback的功能,在百度,google中一顿乱搜,相关的文章好少。。

然后再各大源代码搜索引擎中寻找也没有找到有关于任何blog ping的文章...

我说的没有是指没有blog ping的实现原理,相关代码示例等。。

倒是找到了通过ping服务加快各搜索引擎

收录博客文章的一些介绍文章,so用Java实现blog ping功能来提高搜索引擎对博客的收录速度

通过网上的文章,东了解一点,西了解一点弄了个简单的blog ping功能,一更新文章后自动ping百度,goole等提供自动ping服务的中文搜索引擎或者RSS聚合

Java实现标签云

2010-07-24 17:15:47.0

博客的标签云功能实现已经很久了,但是只有标签功能,没有云的功能,囧!~~~

标签云主要有以下几点重要的 功能:

能根据标签下面文章的多少来决定标签的显示样式的大小

标签云能实现随机颜色

这样标签云就能云起来了,每个标签的字体大小根据数量来决定,数量越多的字体越大,最小的数量也使用12px字体,这样看起来不会太累,颜色直接随机好了

public void tag_cloud(Map<String, Integer> tags) {
int maxsize = 38;//最大字体大小
int minsize = 12;
List<Integer> list2 = CollectionUtils.toList(tags);//这里是我自己的内库实现的map转换为list
int maxval = CollectionUtils.max(list2);//获取标签下文章数量的最大值
int minval = CollectionUtils.min(list2);//获取最小值
int spread = maxval - minval;
int step=1;
if(spread!=0)
step = (maxsize - minsize) / spread;
String[] color = new String[] { "#FF0000", "#FFCC00", "#FF9900",
        "#0099FF", "#999999" };
Iterator<String> it = tags.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
int val = tags.get(key);
int index = RandomUtil.nextInt(0, color.length - 1);//产生0到数组长度的随机数字,来实现随机颜色
int size = Math.round(minsize + ((val - minval) * step));
System.out.println("<a href=\"#\" style=\"font-size:"+size+"px;color:"+color[index]+"\">"+key+"</a>");
}
}

Java中伪造referer来获取数据

2010-06-23 14:31:47.0

很多网站的防采集的办法,就是判断浏览器来源referer和cookie以及userAgent,道高一尺魔高一丈.

在Java中获取一个网站的HTML内容可以通过HttpURLConnection来获取.我们在HttpURLConnection中可以设置referer来伪造referer,轻松绕过这类防采集的网站

HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setRequestProperty("referer", "http://www.popo4j.com");
conn.setRequestProperty("cookie", "http://www.popo4j.com");
InputStream inputStream = conn.getInputStream();
//保存inputstream中的东西就OK了

打造一个快速添加键值的QuickMap

2010-06-21 11:31:36.0

看到有个朋友在博客上抱怨,他恨透JAVA了,new 一个HashMAp然后一个个去put,太烦了,以前我也有这烦恼,最重要的是我这人太懒,哈哈

来看下,正常情况下我们是实例化一个HashMap然后一个个put,如下:

Map<String, Object> mp1=new HashMap<String, Object>();
mp1.put("a", 1);
mp1.put("b", 2);
mp1.put("c", 3);
mp1.put("d", 4);
mp1.put("e", 5);

java同时创建目录和文件

2010-06-18 13:29:49.0

在java中貌似不能同时创建目录和文件,需要分步创建,即不能在创建目录的时候,同时创建该目录下的文件,如果要创建的话,需要分两步,下边是创建的代码,这一点很烦,用mkdirs也没有用

String path = "D:/test/d.txt";
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();