文章标签 ‘源代码’
2012十二月11

JS源码:网页滚动右下角出现返回顶部goTop

效果如图:

直接贴代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <HEAD>
  <TITLE> Wizzer.cn </TITLE>
  <style type="text/css" media="screen">
#goTop {position:fixed;right:20px;bottom:20px;width:40px;height:32px;padding:8px 0 0;background-color:#69c;border-radius:6px;cursor:pointer;}
#goTop:hover {background-color:#369;}
#goTop:hover .gotop1 {border-left:12px solid #369;border-right:12px solid #369;}
#goTop .gotop1 {width:0;margin:0 auto;border-bottom:12px solid #FFF;border-left:12px solid #69c;border-right:12px solid #69c;}
#goTop .gotop2 {width:10px;height:10px;margin:0 auto;background-color:#FFF;}
</style>
 </HEAD>

 <BODY>

a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>

<div title="返回顶部" id="goTop" style="display:none;">
	<div class="gotop1"></div>
	<div class="gotop2"></div>
</div>

<script type="text/javascript">
	    function $getId(Id) {
	        return document.getElementById(Id);
	    }
	    var goTop = $getId("goTop");
	    window.onscroll = function () {
	        if (document.documentElement.scrollTop + document.body.scrollTop > 350) {
	            goTop.style.display = "";
	        } else {
	            goTop.style.display = "none";
	        }
	    }
	    goTop.onclick = function () {
	        var Timer = setInterval(GoTop, 10);
	        function GoTop() {
	            if (document.documentElement.scrollTop + document.body.scrollTop < 1) {
	                clearInterval(Timer);
	            } else {
	                document.documentElement.scrollTop /= 1.1;
	                document.body.scrollTop /= 1.1;
	            }
	        }
	    }
	</script>
 </BODY>
</HTML>

 

 

2012十一月22

经验分享:Firefox插件开发说明

Firefox插件分为两种,即extension和plugin,网上搜索到的示例多是 XUL应用程序开发,XUL插件安装后需要重启浏览器才能使用,而这篇文章主要介绍如何使用 Add-on 来开发JS+HTML+CSS 应用,如Chrome插件可直接安装使用。

(感兴趣的朋友可以查看本站上一篇文章:chrome插件开发说明,对比一下你会发现chrome插件开发简直太easy – -)

言归正传,Add-on 提供SDK下载和在线开发两种方式,访问 https://builder.addons.mozilla.org/ 通过简单的注册,点击“Create an Add-on Now”,自动生成一个带main.js 的项目,如下图所示,你可以在Data文件夹下上传编辑自己的文件(若上传文件后左侧半天不出来按下F5即可):

Add-on 启动函数为 main.js,这里可以通过 require 申请一些资源权限,而放置在Data用户文件夹里的JS是不能直接使用 require 的,可能是Add-on 框架设计本身就不支持随意的调用系统资源吧,这个时候就得利用 port.on 和 port.emit 来传递变量和执行方法。

网络请求的示例可以访问:https://builder.addons.mozilla.org/package/89576/ 来查看,里面具体介绍了 port.on 和 port.emit 的使用、panel的生成、jQuery的引入、网络请求等,这个例子非常好。

通过查看其他网友分享的代码学习,地址:https://builder.addons.mozilla.org/search/ 输入关键词,查找你关心想实现的功能吧。

 

具体功能开发不在累述,我写的这个简单查询功能的插件在商城里搜索“合肥公积金查询”即可下载,下载后若你是win7系统,则:

C:\Users\Wizzer\AppData\Roaming\Mozilla\Firefox\Profiles\zah0wctd.default\extensions

找到 wizzer.cn@gmail.com.xpi  解压即可,源代码没加密,给大家做学习参考之用。

 

其他:

打包:在根文件夹选择所有文件,压缩成zip文件,改后缀名为 xpi。

安装:把xpi文件拖到firefox浏览器中即可。

调试:ctrl—shfit—j 调试插件。

 

扩展组件在线安装地址:

https://addons.mozilla.org/zh-CN/firefox/addon/%E5%90%88%E8%82%A5%E5%85%AC%E7%A7%AF%E9%87%91%E6%9F%A5%E8%AF%A2/

 

2012十一月20

经验分享:Chrome插件开发源码说明

Chrome插件开发极其简单,只要会JS+HTML+CSS即可,当然我捣鼓的是简单的应用作为学习和验证之用,没有更多的深入。

本示例采用 jQuery 实现用户登录查询公积金余额功能,接口提供的功能较多但作为学习么,只开发了一个查询余额的功能。

运行效果:

1、首先创建文件夹,文档结构如下:

2、编辑manifest.json文件,填写应用信息、访问权限等:

{ 
  "name": "合肥公积金查询",
  "version": "2012.11.20.0",
  "manifest_version": 2,
  "description": "这是一款合肥市住房公积金查询工具,用于学习测试仅提供余额查询。@Wizzer",
  "icons":{"16":"16.png","48":"48.png"},
  "content_scripts":[{
      "js": [ "scripts/lib/jquery-1.7.2.min.js","scripts/main.js"],
      "matches": [ "http://*/*", "https://*/*" ] 
   }],
  "browser_action": {
	"default_icon": "16.png",
	"default_popup": "index.html"
  },
  "homepage_url":"http://www.wizzer.cn",
  "permissions": [ "cookies", "tabs", "http://*/*", "https://*/*" ]

}

注意事项:

A、目前最新版的chrome要求设置  “manifest_version”: 2 ;

B、permissions 配置了cookies权限,因为在应用中加入了记住密码功能;

C、API要求JS不可以内联,就是不能直接在页面元素上写JS,例如点击按钮alert提示都不会执行的;

3、本着JS和HTML分离的原则,编写  main.js 文件:

var url = "http://www.wizzer.cn/chrome";
var key = "接口APP_KEY隐藏";
var zgyhzh="";
var dwyhzh="";
var uptime="";
var hm="";
var mm="";
if (!chrome.cookies) {
  chrome.cookies = chrome.experimental.cookies;
}
function delCookie(name) {
  chrome.cookies.remove({"name": name,"url":url});
}

function setCookie(name,value) {
  chrome.cookies.set({"name": name,"value":value,"url":url ,"expirationDate":1392000000});
}

function initCookie() {
  var str="";
  chrome.cookies.get({"name": "hm","url":url },function(cookie){
        str=cookie.value; 
		if(""!=str){
			$('#savehm').attr("checked",true);
			$('#hm').val(Base64.decode(str));
		}
  });
  chrome.cookies.get({"name": "mm","url":url },function(cookie){
		str=cookie.value; 
		if(""!=str){
			$('#savemm').attr("checked",true);
			$('#mm').val(Base64.decode(str));
		}
  });
}

function login(){
	 hm=Base64.encode($('#hm').val());
	 mm=Base64.encode($('#mm').val());

	$.ajax({
        			url : "http://220.178.98.86/hfgjj/service/login.jsp",
        			data : {"hm":hm,"mm":mm,"app_key":key} ,
        			success : function (res) {
						loginData(res);
						return false;
        			},
        			fail : function(res) {
        				loginData(res);
        			}
        		});

}

function loginData(res){
	if(res.indexOf("error")>=0){
	    var obj = jQuery.parseJSON(res);
		if(""!=obj.tip){
			$("#tip").html("<HR><span style='color:red'>"+obj.tip+"</span>");

		}
	}else if(res.indexOf("more")>=0){
		var obj = jQuery.parseJSON(res);
		if("false"==obj.more){
			zgyhzh=obj.zgyhzh;
			dwyhzh=obj.dwyhzh;
			uptime=obj.uptime;
			oneData();

		}else if("true"==obj.more){
			uptime=obj.uptime;
			var zgyhzhlist=obj.zgyhzhlist;
			$.each(zgyhzhlist,function(entryIndex,entry){ 
				if("true"==entry.zt){
					zgyhzh=entry.zgyhzh;
					dwyhzh=entry.dwyhzh;
					oneData();
					$("#note")[0].style.display='block';
					return;

				}
                });     
		}

	}else{

		$("#tip").html("<HR><span style='color:red'>"+res+"</span>");
	}

}
function oneData(){

			var z=Base64.encode(zgyhzh);
			var d=Base64.encode(dwyhzh);
			$.ajax({
        			url : "http://220.178.98.86/hfgjj/service/grindex.jsp",
        			data : {"hm":hm,"mm":mm,"app_key":key,"zgyhzh":z,"dwyhzh":d} ,
        			success : function (res) {
						showData(res);
						return false;
        			},
        			fail : function(res) {

        			}
        		});

}

function showData(res){
	if(res.indexOf("error")>=0){
	    var obj = jQuery.parseJSON(res);
		if(""!=obj.tip){
			$("#tip").html("<HR><span style='color:red'>"+obj.tip+"</span>");

		}
	}else{
			$("#T1")[0].style.display='none'; 
			$("#T2")[0].style.display='block';
	var obj = jQuery.parseJSON(res);
	var scje=obj.scje;

	$("#uptime").html("<span style='color:red'>"+uptime+"</span>");
	$("#yue").html("<span style='color:red'>"+scje+"</span>");
	}
}

function init(){
  initCookie();
  $('#bt').click(function() {
	  if($('#savemm').attr('checked')){
		 setCookie("mm",Base64.encode($('#mm').val()));
		 setCookie("hm",Base64.encode($('#hm').val()));
	  }else if($('#savehm').attr('checked')){
		 setCookie("mm","");
		 setCookie("hm",Base64.encode($('#hm').val()));
	  }else{
		 setCookie("mm","");
		 setCookie("hm","");
	  }
	  $("#tip").html("<HR><span style='color:red'>Loading...</span>");
	  login();

  });

  $('#savemm').click(function() {
	 if($('#savemm').attr('checked')){
		$('#savehm').attr("checked",true);
	 }else{
		$('#savehm').attr("checked",false);
	 }
  });
}

document.addEventListener('DOMContentLoaded', function () {
  init();
});

PS:搞开发的JS都能看懂,就不注释了。。。

4、index.html 页面的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>合肥市住房公积金查询</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<meta http-equiv="Cache-Control" content="no-cache"/><!-- 公共样式 -->
<script type='text/javascript' src='scripts/lib/jquery-1.7.2.min.js'></script>
<script type='text/javascript' src='scripts/lib/Base64.js'></script>
<script type='text/javascript' src='scripts/main.js'></script> 

<STYLE type=text/css>BODY {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
DIV {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
P {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
EM {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
SPAN {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
A {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
TD {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
FORM {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
BUTTON {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
body {COLOR: #333 ;min-width: 220px; margin: 0; font: 12px "Helvetica Neue", Helvetica, Arial, sans-serif; width: auto}

EM {
	FONT-WEIGHT: bold
}
STRONG {
	FONT-WEIGHT: bold
}
DEL {
	TEXT-DECORATION: line-through
}
INPUT {
	MARGIN: 2px 0px; FONT-SIZE: 12px
}
SELECT {
	MARGIN: 2px 0px; FONT-SIZE: 12px
}
IMG {
	BORDER-BOTTOM: medium none; BORDER-LEFT: medium none; BORDER-TOP: medium none; BORDER-RIGHT: medium none
}
HR {
	BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; HEIGHT: 0px; CLEAR: both; BORDER-TOP: #ddd 1px solid; BORDER-RIGHT: 0px
}
A:link {
	COLOR: #36c; TEXT-DECORATION: underline
}
A:visited {
	COLOR: #36c; TEXT-DECORATION: underline
}
A.im {
	COLOR: #f60
}
.im {
	COLOR: #f60
}
.imp {
	COLOR: #f00
}
.gp {
	COLOR: #06c
}
.mp {
	COLOR: #f90
}
.module {
	PADDING-BOTTOM: 0px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; PADDING-TOP: 0px
}
.wrapper {

}
.none {
	DISPLAY: none
}
.header {
	BORDER-BOTTOM: #d2d2d2 1px solid; PADDING-BOTTOM: 2px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; BACKGROUND: #f5f5f5; PADDING-TOP: 2px
}
.footer {
	PADDING-BOTTOM: 2px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; BORDER-TOP: #d2d2d2 1px solid; PADDING-TOP: 2px
}
.logo {
	PADDING-BOTTOM: 0px; PADDING-LEFT: 1px; PADDING-RIGHT: 1px; PADDING-TOP: 2px
}
.logo A {
	FONT-SIZE: 14px; TEXT-DECORATION: none
}
.nav {
	PADDING-BOTTOM: 5px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; PADDING-TOP: 5px
}
.cl {

}
.module {
	MARGIN-TOP: 3px
}
.gtt {
	TEXT-ALIGN: center
}
.capt {
	VERTICAL-ALIGN: middle
}
.err {
	BACKGROUND: #fc9
}
.ptit {
	COLOR: #000; FONT-SIZE: 14px
}
</STYLE>
<BODY> 
<DIV class=wrapper id=top>
<DIV class=logo><A href="http://220.178.98.86/hfgjj/jsp/web/public/search/grlogin.jsp" target="_blank"><IMG alt="合肥市住房公积金中心" 
src="sjimg/logo.jpg"></A></DIV>
<DIV  ID="T1">
<DIV class="tit module"><STRONG>个人公积金查询</STRONG></DIV> 
<DIV class=module>身份证号码<BR>
<INPUT id="hm" maxLength="18" type="text" 
name="hm"> <input id="savehm" name="savehm" type="checkbox"> 记住号码
<BR>密码<BR>
<INPUT id="mm" maxLength="6" type="password" 
name="mm"> <input id="savemm" name="savemm" type="checkbox"> 记住密码
<div id="tip"></div>
<HR>
<INPUT id="bt" class="bts" value="登 录" type="button">
</DIV>
</DIV>
<DIV  ID="T2" style="display:none">
<DIV class="tit module"><STRONG>公积金余额</STRONG></DIV>

截至:<div id="uptime"></div>
您的公积金账户余额为:<div id="yue"></div>
<div id="note" style="display:none">您有多个帐号,本工具只显示您正常缴费的公积金帐号余额。</div>

</DIV>

<DIV class=footer><A href="index.html">返回首页</A>  <BR>Copyright @Wizzer</DIV>

</DIV>

</BODY></HTML>

5、调试部署:

菜单–工具–扩展程序–载入正在开发的扩展程序,右上角会出现16*16的图标,o(∩_∩)o 哈哈

6、将应用发布到google网上应用商城:

首次发布项目之前,您必须支付 US$5.00的一次性开发者注册费。我们收取此费用的目的是对开发者帐户进行验证,并为用户提供更好的保护,以防他们受到欺骗性活动的侵害。 支付注册费后,您就可以发布任意数量的项目,且无需再支付注册费了。

首先你需要有一张VISA信用卡,登陆google电子钱包注册信用卡。

https://www.google.com/checkout/   –注意要加https哦,你懂得

这里要注意的是,自动弹出的第一张信用卡注册界面不是如上的,很可能支付不成功,这个时候进入“支付方式”,选择修改信用卡,出现上面的界面选择New York 输入正确的邮编才能支付成功。

进入开发者中心(扩展程序最下面点击“获取更多扩展程序”,进入网上应用商城)

在开发者中心修改用户偏好设置,勾选“为我在 Chrome 网上应用店中的所有应用启用用户反馈功能。”,否则点击“立即支付注册费”会没反应(实在没辙换成IE试试吧)。

支付成功后耐心等待吧,我正在等待订单审核ing……

7、发布应用:

开发者中心点击添加新项目,把项目文件夹打包为zip压缩包上传即可。其他略,都能看懂。。

8、关于firewall:

以上许多操作,你会发现一会这个网页打不开,那个网页等白天没反应,这个时候你就需要用chrome插件“SwitchySharp”了,具体怎么用百度一下吧,步骤也很多很麻烦,关键是耐心按教程来。

chrome里可以用 SwitchySharp,那么IE里要用怎么办,在IE里手动设置下代理即可,端口号到 SwitchySharp 选项里查看。

可移步:http://www.delver.net/?p=267  看教程~~

9、其他

等订单审核完毕应用发布后,大家就可以在chrome 商城里搜索“合肥公积金查询”,那就是我写的这个应用了,如果你是win7系统的话,可以在:

C:\Users\Wizzer\AppData\Local\Google\Chrome\User Data\Default\Extensions

文件夹下看到源代码。over~~

几点思考,chrome插件是js+html+CSS的网页应用,不能直接执行JSP、ASP、PHP什么的,实现功能都需要调用chrome的接口、你自己应用提供的接口,那么可以不可以使用iframe嵌入自己的应用呢(- -)。

另外就是session传递的问题,从一个页面到另外一页面,信息怎么传递,用cookies感觉不太合适,也不能把所有的逻辑写在一个页面啊,这个需要深入的去研究。

再之就是js不能内联,那么实现一些功能就比较麻烦了,比如动态创建可点击的按钮,现在还没想到什么好办法,相信深入研究是可以解决的,JS要相当的熟才行啊,偶么就一般般。- –

2012八月29

Lucene 3.6.1:中文分词、创建索引库、排序、多字段分页查询以及高亮显示源码

1、准备工作

下载lucene 3.6.1 : http://lucene.apache.org/

下载中文分词IK Analyzer: http://code.google.com/p/ik-analyzer/downloads/list (注意下载的是IK Analyzer 2012_u5_source.zip,其他版本有bug)

下载solr 3.6.1:  http://lucene.apache.org/solr/(编译IK Analyzer时需引用包)

OK,将lucene 、solr 相关包(lucene-core-3.6.1.jar、lucene-highlighter-3.6.1.jar、lucene-analyzers-3.6.1.jar、apache-solr-core-3.6.1.jar、apache-solr-solrj-3.6.1.jar)拷贝到项目lib下,IK源码置于项目src下。

2、从Oracle数据库中取数据创建索引(使用IK分词)

package lucene.util;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.sql.Connection;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import modules.gk.Gk_info;
import modules.gk.Gk_infoSub;
import web.sys.Globals;
import web.db.DBConnector;
import web.db.ObjectCtl;
import web.util.StringUtil;
//Wizzer.cn
public class LuceneIndex {
    IndexWriter writer = null;
    FSDirectory dir = null;
    boolean create = true;//是否初始化&覆盖索引库

    public void init() {
        long a1 = System.currentTimeMillis();
        System.out.println("[Lucene 开始执行:" + new Date() + "]");
        Connection con = DBConnector.getconecttion(); //取得一个数据库连接
        try {
            final File docDir = new File(Globals.SYS_COM_CONFIG.get("sys.index.path").toString());//E:\lucene
            if (!docDir.exists()) {
                docDir.mkdirs();
            }
            String cr = Globals.SYS_COM_CONFIG.get("sys.index.create").toString();//true or false
            if ("false".equals(cr.toLowerCase())) {
                create = false;
            }
            dir = FSDirectory.open(docDir);
//            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
            Analyzer analyzer = new IKAnalyzer(true);
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
            if (create) {
                // Create a new index in the directory, removing any
                // previously indexed documents:
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            } else {
                // Add new documents to an existing index:
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            }
            writer = new IndexWriter(dir, iwc);
            String sql = "SELECT indexno,title,describes,pdate,keywords FROM TABLEA WHERE STATE=1 AND SSTAG<>1 ";
            int rowCount = ObjectCtl.getRowCount(con, sql);
            int pageSize = StringUtil.StringToInt(Globals.SYS_COM_CONFIG.get("sys.index.size").toString());   //每页记录数
            int pages = (rowCount - 1) / pageSize + 1; //计算总页数
            ArrayList list = null;
            Gk_infoSub gk = null;
            for (int i = 1; i < pages+1; i++) {
                long a = System.currentTimeMillis();
                list = ObjectCtl.listPage(con, sql, i, pageSize, new Gk_infoSub());
                for (int j = 0; j < list.size(); j++) {
                    gk = (Gk_infoSub) list.get(j);
                    Document doc = new Document();
                    doc.add(new Field("indexno", StringUtil.null2String(gk.getIndexno()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));//主键不分词
                    doc.add(new Field("title", StringUtil.null2String(gk.getTitle()), Field.Store.YES, Field.Index.ANALYZED));
                    doc.add(new Field("describes", StringUtil.null2String(gk.getDescribes()), Field.Store.YES, Field.Index.ANALYZED));
                    doc.add(new Field("pdate", StringUtil.null2String(gk.getPdate()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));//日期不分词
                    doc.add(new Field("keywords", StringUtil.null2String(gk.getKeywords()), Field.Store.YES, Field.Index.ANALYZED));
                    writer.addDocument(doc);
                    ObjectCtl.executeUpdateBySql(con,"UPDATE TABLEA SET SSTAG=1 WHERE indexno='"+gk.getIndexno()+"'");//更新已索引状态
                }

                long b = System.currentTimeMillis();
                long c = b - a;
                System.out.println("[Lucene " + rowCount + "条," + pages + "页,第" + i + "页花费时间:" + c + "毫秒]");
            }
            writer.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBConnector.freecon(con); //释放数据库连接
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (CorruptIndexException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (dir != null && IndexWriter.isLocked(dir)) {
                        IndexWriter.unlock(dir);//注意解锁
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long b1 = System.currentTimeMillis();
        long c1 = b1 - a1;
        System.out.println("[Lucene 执行完毕,花费时间:" + c1 + "毫秒,完成时间:" + new Date() + "]");
    }
}

 

3、单字段查询以及多字段分页查询高亮显示

 

package lucene.util;

import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.Version;
import modules.gk.Gk_infoSub;

import java.util.ArrayList;
import java.io.File;
import java.io.StringReader;
import java.lang.reflect.Constructor;

import web.util.StringUtil;
import web.sys.Globals;
import org.wltea.analyzer.lucene.IKAnalyzer;
//Wizzer.cn
public class LuceneQuery {
    private static String indexPath;// 索引生成的目录
    private int rowCount;// 记录数
    private int pages;// 总页数
    private int currentPage;// 当前页数
    private int pageSize;   //每页记录数

    public LuceneQuery() {
        this.indexPath = Globals.SYS_COM_CONFIG.get("sys.index.path").toString();
    }

    public int getRowCount() {
        return rowCount;
    }

    public int getPages() {
        return pages;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    /**
     * 函数功能:根据字段查询索引
     */
    public ArrayList queryIndexTitle(String keyWord, int curpage, int pageSize) {
        ArrayList list = new ArrayList();
        try {
            if (curpage <= 0) {
                curpage = 1;
            }
            if (pageSize <= 0) {
                pageSize = 20;
            }
            this.pageSize = pageSize;   //每页记录数
            this.currentPage = curpage;   //当前页
            int start = (curpage - 1) * pageSize;
            Directory dir = FSDirectory.open(new File(indexPath));
            IndexReader reader = IndexReader.open(dir);
            IndexSearcher searcher = new IndexSearcher(reader);
            Analyzer analyzer = new IKAnalyzer(true);
            QueryParser queryParser = new QueryParser(Version.LUCENE_36, "title", analyzer);
            queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
            Query query = queryParser.parse(keyWord);
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(query, res);

            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
            this.rowCount = res.getTotalHits();
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            TopDocs tds = res.topDocs(start, pageSize);
            ScoreDoc[] sd = tds.scoreDocs;
            for (int i = 0; i < sd.length; i++) {
                Document hitDoc = reader.document(sd[i].doc);
                list.add(createObj(hitDoc, analyzer, highlighter));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }
    /**
     * 函数功能:根据字段查询索引
     */
    public ArrayList queryIndexFields(String allkeyword, String onekeyword, String nokeyword, int curpage, int pageSize) {
        ArrayList list = new ArrayList();
        try {
            if (curpage <= 0) {
                curpage = 1;
            }
            if (pageSize <= 0) {
                pageSize = 20;
            }
            this.pageSize = pageSize;   //每页记录数
            this.currentPage = curpage;   //当前页
            int start = (curpage - 1) * pageSize;
            Directory dir = FSDirectory.open(new File(indexPath));
            IndexReader reader = IndexReader.open(dir);
            IndexSearcher searcher = new IndexSearcher(reader);
            BooleanQuery bQuery = new BooleanQuery();  //组合查询
            if (!"".equals(allkeyword)) {//包含全部关键词
                KeywordAnalyzer analyzer = new KeywordAnalyzer();
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//AND
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, allkeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST);  //AND
            }
            if (!"".equals(onekeyword)) { //包含任意关键词
                Analyzer analyzer = new IKAnalyzer(true);
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//OR
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, onekeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST);  //AND
            }
            if (!"".equals(nokeyword)) { //排除关键词
                Analyzer analyzer = new IKAnalyzer(true);
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//NOT
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, nokeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST_NOT);  //AND

            }
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(bQuery, res);
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(bQuery));
            this.rowCount = res.getTotalHits();
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            System.out.println("rowCount:" + rowCount);
            TopDocs tds = res.topDocs(start, pageSize);
            ScoreDoc[] sd = tds.scoreDocs;
            Analyzer analyzer = new IKAnalyzer();
            for (int i = 0; i < sd.length; i++) {
                Document hitDoc = reader.document(sd[i].doc);
                list.add(createObj(hitDoc, analyzer, highlighter));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }

    /**
     * 创建返回对象(高亮)
     */

    private synchronized static Object createObj(Document doc, Analyzer analyzer, Highlighter highlighter) {

        Gk_infoSub gk = new Gk_infoSub();
        try {

            if (doc != null) {
                gk.setIndexno(StringUtil.null2String(doc.get("indexno")));
                gk.setPdate(StringUtil.null2String(doc.get("pdate")));
                String title = StringUtil.null2String(doc.get("title"));
                gk.setTitle(title);
                if (!"".equals(title)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(title.length()));
                    TokenStream tk = analyzer.tokenStream("title", new StringReader(title));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, title));
                    if (!"".equals(htext)) {
                        gk.setTitle(htext);
                    }
                }
                String keywords = StringUtil.null2String(doc.get("keywords"));
                gk.setKeywords(keywords);
                if (!"".equals(keywords)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(keywords.length()));
                    TokenStream tk = analyzer.tokenStream("keywords", new StringReader(keywords));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, keywords));
                    if (!"".equals(htext)) {
                        gk.setKeywords(htext);
                    }
                }
                String describes = StringUtil.null2String(doc.get("describes"));
                gk.setDescribes(describes);
                if (!"".equals(describes)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(describes.length()));
                    TokenStream tk = analyzer.tokenStream("keywords", new StringReader(describes));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, describes));
                    if (!"".equals(htext)) {
                        gk.setDescribes(htext);
                    }
                }

            }
            return gk;
        }
        catch (Exception e) {

            e.printStackTrace();
            return null;
        }
        finally {
            gk = null;
        }

    }

    private synchronized static Object createObj(Document doc) {

        Gk_infoSub gk = new Gk_infoSub();
        try {

            if (doc != null) {
                gk.setIndexno(StringUtil.null2String(doc.get("indexno")));
                gk.setPdate(StringUtil.null2String(doc.get("pdate")));
                gk.setTitle(StringUtil.null2String(doc.get("title")));
                gk.setKeywords(StringUtil.null2String(doc.get("keywords")));
                gk.setDescribes(StringUtil.null2String(doc.get("describes")));
            }
            return gk;
        }
        catch (Exception e) {

            e.printStackTrace();
            return null;
        }
        finally {
            gk = null;
        }

    }
}

 

单字段查询:

        long a = System.currentTimeMillis();
        try {
            int curpage = StringUtil.StringToInt(StringUtil.null2String(form.get("curpage")));
            int pagesize = StringUtil.StringToInt(StringUtil.null2String(form.get("pagesize")));
            String title = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("title")));
            LuceneQuery lu = new LuceneQuery();
            form.addResult("list", lu.queryIndexTitle(title, curpage, pagesize));
            form.addResult("curPage", lu.getCurrentPage());
            form.addResult("pageSize", lu.getPageSize());
            form.addResult("rowCount", lu.getRowCount());
            form.addResult("pageCount", lu.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long b = System.currentTimeMillis();
        long c = b - a;
        System.out.println("[搜索信息花费时间:" + c + "毫秒]");

多字段查询:

        long a = System.currentTimeMillis();
        try {
            int curpage = StringUtil.StringToInt(StringUtil.null2String(form.get("curpage")));
            int pagesize = StringUtil.StringToInt(StringUtil.null2String(form.get("pagesize")));
            String allkeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("allkeyword")));
            String onekeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("onekeyword")));
            String nokeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("nokeyword")));
            LuceneQuery lu = new LuceneQuery();
            form.addResult("list", lu.queryIndexFields(allkeyword,onekeyword,nokeyword, curpage, pagesize));
            form.addResult("curPage", lu.getCurrentPage());
            form.addResult("pageSize", lu.getPageSize());
            form.addResult("rowCount", lu.getRowCount());
            form.addResult("pageCount", lu.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long b = System.currentTimeMillis();
        long c = b - a;
        System.out.println("[高级检索花费时间:" + c + "毫秒]");

4、Lucene通配符查询

            BooleanQuery bQuery = new BooleanQuery();  //组合查询
            if (!"".equals(title)) {
                WildcardQuery w1 = new WildcardQuery(new Term("title", title+ "*"));

                bQuery.add(w1, BooleanClause.Occur.MUST);  //AND
            }
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(bQuery, res);

 

5、Lucene嵌套查询

实现SQL:(unitid like ‘unitid%’  and idml like ‘id2%’) or (tounitid like ‘unitid%’ and tomlid like ‘id2%’ and tostate=1)

                    BooleanQuery bQuery = new BooleanQuery();
                    BooleanQuery b1 = new BooleanQuery();
                    WildcardQuery w1 = new WildcardQuery(new Term("unitid", unitid + "*"));
                    WildcardQuery w2 = new WildcardQuery(new Term("idml", id2 + "*"));
                    b1.add(w1, BooleanClause.Occur.MUST);//AND
                    b1.add(w2, BooleanClause.Occur.MUST);//AND
                    bQuery.add(b1, BooleanClause.Occur.SHOULD);//OR
                    BooleanQuery b2 = new BooleanQuery();
                    WildcardQuery w3 = new WildcardQuery(new Term("tounitid", unitid + "*"));
                    WildcardQuery w4 = new WildcardQuery(new Term("tomlid", id2 + "*"));
                    WildcardQuery w5 = new WildcardQuery(new Term("tostate", "1"));
                    b2.add(w3, BooleanClause.Occur.MUST);//AND
                    b2.add(w4, BooleanClause.Occur.MUST);//AND
                    b2.add(w5, BooleanClause.Occur.MUST);//AND
                    bQuery.add(b2, BooleanClause.Occur.SHOULD);//OR

6、Lucene先根据时间排序后分页

下面这种方式不太合理,建议在创建索引库的时候排序,这样查询的时候只用分页即可,若有多个排序条件可单独创建索引库。
int hm = start + pageSize;
Sort sort = new Sort(new SortField(“pdate”, SortField.STRING, true));
TopScoreDocCollector res = TopScoreDocCollector.create(pageSize, false);
searcher.search(bQuery, res);
this.rowCount = res.getTotalHits();
this.pages = (rowCount – 1) / pageSize + 1; //计算总页数
TopDocs tds =searcher.search(bQuery,rowCount,sort);// res.topDocs(start, pageSize);
ScoreDoc[] sd = tds.scoreDocs;
System.out.println(“rowCount:” + rowCount);
int i=0;
for (ScoreDoc scoreDoc : sd) {
i++;
if(i<start){
continue;
}
if(i>hm){
break;
}
Document doc = searcher.doc(scoreDoc.doc);
list.add(createObj(doc));
}


最新的排序写法:

            int hm = start + pageSize;
            Sort sort = new Sort();
            SortField sortField = new SortField("pdate", SortField.STRING, true);
            sort.setSort(sortField);
            TopDocs hits = searcher.search(bQuery, null, hm, sort);
            this.rowCount = hits.totalHits;
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            for (int i = start; i < hits.scoreDocs.length; i++) {
                ScoreDoc sdoc = hits.scoreDocs[i];
                Document doc = searcher.doc(sdoc.doc);
                list.add(createObj(doc));
            }

ps:
周一完成创建索引库定时任务,周二实现模糊查询中文分词高亮显示及分页,今天实现了通配符查询、嵌套查询、先排序后分页,从零接触到实现Lucene主要功能花了三天时间,当然,性能如何还待测试和优化。

2012六月20

Android:扫描获取AP信息

增加权限:

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE” />

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
			   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			  showMsg(wifiInfo.toString());//自己的显示方法

			  wifiManager.startScan();
			  List mWifiList = wifiManager.getScanResults();
			  for(int i=0;i<mWifiList.size();i++)
				  logger.d(mWifiList.get(i).toString());//自己重构的日志方法
2011十二月22

JAVA源码:将GPS、google地图经纬度坐标转换为百度地图坐标

package smsService;

import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.json.me.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import smsService.cfg.Globals;
import smsService.sms.StringUtil;
import smsService.util.JWD;
import smsService.util.SecBase64;

/**
Wizzer.cn
 */
public class baidu {
    public static void main(String args[]) {
        baidu b = new baidu();
        b.getData("117.3094928", "31.875676");
        System.out.println("");
    }

    public static JWD getData(String jd, String wd) {
        JSONObject holder = new JSONObject();
        String wizzer = "";
        JWD jwd=null;
        try {
            BasicHttpParams httpParameters = new BasicHttpParams();
            // Set the default socket timeout (SO_TIMEOUT)
            HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
            // in milliseconds which is the timeout for waiting for data.
            HttpConnectionParams.setSoTimeout(httpParameters, 15000);

            DefaultHttpClient client = new DefaultHttpClient(httpParameters);
            HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.NETSCAPE);//CookiePolicy.BROWSER_COMPATIBILITY);
            String type="0";//详见百度坐标转换API文档示例
            type=StringUtil.null2String(Globals.SYS_COM_CONFIG.get("sys.baidu.type"));
            HttpGet get = new HttpGet("http://api.map.baidu.com/ag/coord/convert?from="+type +"&to=4&x=" + jd + "&y=" + wd + "&callback=wizzer");
            HttpResponse resp = client.execute(get);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity
                    .getContent(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                sb.append(result);
                result = br.readLine();
            }

            String res = StringUtil.null2String(sb.toString());
            if (res.indexOf("(") > 0 && res.indexOf(")") > 0) {
                String str = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
                String err = res.substring(res.indexOf("error") + 7, res.indexOf("error") + 8);

                if ("0".equals(err)) {
                    jwd=new JWD();
                    JSONObject js = new JSONObject(str);
                    String x = new String(SecBase64.decode(js.getString("x").getBytes()));
                    String y = new String(SecBase64.decode(js.getString("y").getBytes()));
                    jwd.setX(x);
                    jwd.setY(y);
                }
            }
            return jwd;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
2011十二月22

JAVA源码:通过google地图API将经纬度坐标转换为位置描述

package smsService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/*
Wizzer.cn
 */
public class Demo {
	public static void main(String[] args) {
		String addr = GetAddr("31.875676", "117.3094928");
		System.out.println(addr);
		//getCoordinate("中国");
	}

	/**
	 * 根据经纬度反向解析地址,有时需要多尝试几次
	 * 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html
	 * 提交的地址解析请求次数是否有限制?) 如果在 24 小时时段内收到来自一个 IP 地址超过 15,000 个地址解析请求, 或从一个 IP
	 * 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该 IP
	 * 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。
	 *
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @return
	 */
	public static String GetAddr(String latitude, String longitude) {
		String addr = "";

		// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址
		// 密钥可以随便写一个key=abc
		// output=csv,也可以是xml或json,不过使用csv返回的数据最简洁方便解析
		String url = String.format(
				"http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
				latitude, longitude);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addr = retList[2];
						addr = addr.replace("\"", "");
					} else {
						addr = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return addr;
	}

	public static void getCoordinate(String addr)
	{
		String addrs = "";
	    String address = null;
		try {
			address = java.net.URLEncoder.encode(addr,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		};
        String output = "csv";
        String key = "abc";
        String url = String.format("http://maps.google.com/maps/geo?q=%s&output=%s&key=%s", address, output, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					/*
		            String latitude = retList[2];
		            String longitude = retList[3];

		            System.out.println("纬度"+ latitude);
		            System.out.println("经度"+ longitude);
		            */

					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addrs = retList[2];
						addrs = addr.replace("\"", "");
					} else {
						addrs = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(addrs);
	}
}
2011九月6

VB实现自动上传文件网页ActiveX控件(模拟form提交)

网页中实现自动上传本地文件,而不需要用户选择,这种应用场景很多,例如业务系统中需要使用的二代身份证扫描器、一体机(扫描仪)、摄像头拍照等。

首先介绍一个国外网站:http://www.planet-source-code.com/ 里面有许多可用的源代码供参考,搜索 upload file 找到 vb6 file uploader (类似的代码比较多,这个是比较好的一个)。

VB通过模拟HTTP POST过程把文件提交至服务器。

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1
Const BOUNDARY = "Xu02=$"
Const HEADER = "--Xu02=$"
Const FOOTER = "--Xu02=$--"

Function UploadFiles(DirPath As String, strFileName As Variant, strFileForm As Variant, strURL As String, _
Optional postName As Variant, Optional postVar As Variant, Optional strUserName As String, _
Optional strPassword As String) As String

    Dim fName As String
    Dim strFile As String
    Dim strBody As String
    Dim aPostBody() As Byte
    Dim nFile As Integer
    Dim p As Integer

    Set WinHttpReq = New WinHttpRequest

    ' Turn error trapping on
    On Error GoTo SaveErrHandler

    ' Assemble an HTTP request.
    WinHttpReq.Open "POST", strURL, False

    If strUserName <> "" And strPassword <> "" Then
        ' Set the user name and password, for server request authentication
        WinHttpReq.SetCredentials strUserName, strPassword, _
        HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    End If

    '-------------------------- Becareful not to mingle too much here -----------------------------------

    ' Set the header
    WinHttpReq.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY

    ' Assemble the body
    ' Starting tag
    strBody = HEADER

    For i = 0 To UBound(strFileName)

        ' Grap the name
        fName = strFileName(i)

        ' Grap the file
        strFile = GetFile(DirPath & "\" & fName)

            strBody = strBody & vbCrLf & "Content-Disposition: form-data; name=""" & strFileForm(i) & _
             """; filename=""" & fName & """ " & vbCrLf & "Content-type: file" & _
            vbCrLf & vbCrLf & strFile & vbCrLf

        If i < UBound(strFileName) Then
            ' This is boundary tag between two files
            strBody = strBody & "--Xu02=$"
        End If
        strFile = ""

    Next i

'Posted Variable

    For p = 0 To UBound(postName)
    strBody = strBody & HEADER & vbCrLf
    strBody = strBody & "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf
    strBody = strBody & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    'Debug.Print "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    Next p

    ' Ending tag
    strBody = strBody & FOOTER

    ' Because of binary zeros, post body has to convert to byte array
    aPostBody = StrConv(strBody, vbFromUnicode)

    ' Send the HTTP Request.
    WinHttpReq.Send aPostBody

    ' Display the status code and response headers.
    'debug.print WinHttpReq.GetAllResponseHeaders & "  " & WinHttpReq.ResponseText

    UploadFiles = WinHttpReq.ResponseText
    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & WinHttpReq.ResponseText

    Set WinHttpReq = Nothing
    Exit Function

SaveErrHandler:

    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & Err.Description
    UploadFiles = WinHttpReq.ResponseText
    Set WinHttpReq = Nothing

End Function

Function GetFile(strFileName As String) As String

    Dim strFile As String

    ' Grap the file
    nFile = FreeFile
    Open strFileName For Binary As #nFile
    strFile = String(LOF(nFile), " ")
    Get #nFile, , strFile
    Close #nFile

    GetFile = strFile

End Function

'-----------------------------------------------------------
Private Sub Command1_Click()
Dim pst As New clsUploadEngine

'file path (make sure put "\" after folder name)
filepath = App.Path & "\sample\"

'filename array
filearr = Array("scenery1.jpg", "scenery2.jpg", "scenery3.jpg")

'form file post name (equivalent to <input type="file" name="filename">
fileform = Array("fileA", "fileB", "fileC")

'url to post file/information
uploadurl = "http://127.0.0.1:8080/savefile.jsp"

'post parameter & posted variable (optional)
'if no post parameter, just put dummy post, if not error will occur
postparam = Array("id", "uname", "passwd", "op")
postVar = Array("1", "root", "", "tdrupload")

pst.UploadFiles CStr(filepath), filearr, fileform, CStr(uploadurl), postparam, postVar

End Sub

在此基础上,做成ActiveX控件即可。但问题是这个源码上传到服务器的文本文件虽然看起来正常但文件结尾会有空编码、图片损坏。囧。

后来发现 WebNoteEditor 可以实现粘贴QQ截图,自动把文件上传到服务器,于是联系作者。作者是个好人哈,分享了一些经验甚至代码。目前在作者的帮助下,已实现的网页控件的文件自动上传功能,可传多个文件、多表单项。

下面要解决如何在线安装的问题了……

2011八月31

百度地图API:GPS经纬度转换整合版

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
	<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
	<script type="text/javascript" src="http://dev.baidu.com/wiki/static/map/API/examples/script/convertor.js"></script>
</head>
<body style="padding:4px 0px 4px 4px;overflow-y:scroll">
<div style="position:relative; width:100%;height:405px;border:1px solid #D4D0C8;" id="container"></div>
<script language="javascript" id="mapscript">
document.getElementById("container").style.height = document.body.clientHeight+18;
var map = new BMap.Map("container");
map.centerAndZoom("兰州", 5);
map.addControl(new BMap.NavigationControl());
map.enableScrollWheelZoom();//启动鼠标滚轮缩放地图

map.addEventListener('load',function(){

//增加一个标注点
//doaddpoint('<%=appname%>/img/private/images/icon_home1.png', '', '<%=locdata.getRegion()%><%=locdata.getCity()%><%=locdata.getStreet()%>', '', '<%=jd%>', '<%=wd%>', '<%=locdata.getPhone()%>', '<%=Sys_userCtl.getUserNameByloginNames(locdata.getLoginname())%>','<%=locdata.getCtime()%>','#ff0000','<%=Loc_dataCtl.getLocType(locdata)%>');

});
//新增一个点时处理方法
function doaddpoint(img, name, dz, id, jd, wd, dh, lxr,sm,color,type)
{
var sContent ="<div class='tab_TextInput_map' style='width:250px;'><table id='TextInput_map' align=left><tr><td><b>人员姓名:</b></td><td>" + lxr + "</td></tr><tr><td><b>手机号码:</b></td><td>" + dh + "</td></tr><tr><td><b>定位时间:</b></td><td>" + sm + "</td></tr><tr><tr><td><b>上传地址:</b></td><td>" + dz + "</td></tr><tr><td><b>定位方式:</b></td><td>" + type + "</td></tr></table></div>";
var gpsPoint = new BMap.Point(jd,wd);

translateOptions = function (point){
var marker = new BMap.Marker(point);

var infoWindow = new BMap.InfoWindow(sContent);  // 创建信息窗口对象
map.addOverlay(marker);
marker.addEventListener("click", function(){
   this.openInfoWindow(infoWindow);
});
marker.setLabel(new BMap.Label("<span style='color:blue;font-size:16px;font-weight:bold;'>" + lxr +"</span>",{offset:new BMap.Size(20,0)}));   

}
BMap.Convertor.translate(gpsPoint,0,translateOptions);

}

</script>
</div>
</form>
</body>
</html>
2011七月31

Android开发:休眠唤醒或开机后cmwap/cmnet网络不能连接的解决办法

Android手机(移动GSM)在休眠或开机后不能成功启用网络链接(设置都正常),有时候甚至状态栏图标是连接的,但网络依旧不可用。

如下解决方法,不知可通用,但测试HTC野火手机移动版可使用:

(被这个问题折腾死了,从本站相关文章可以看到,之前尝试了APN切换也不行,估计是网络enable==false)

package com.wiz.tools;

import java.lang.reflect.Method;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
 * Wizzer.cn
 * @author Wizzer
 *
 */
public class NetCheck {
	public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
	public static final Uri DEFAULTAPN_URI = Uri
			.parse("content://telephony/carriers/restore");
	public static final Uri CURRENT_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");
	public static Context c1;

	public static String getCurrentAPNFromSetting(ContentResolver resolver) {
		Cursor cursor = null;
		try {
			cursor = resolver.query(CURRENT_APN_URI, null, null, null, null);
			String curApnId = null;
			String apnName1 = null;
			if (cursor != null && cursor.moveToFirst()) {
				curApnId = cursor.getString(cursor.getColumnIndex("_id"));
				apnName1 = cursor.getString(cursor.getColumnIndex("apn"));
			}
			Log.e("NetCheck getCurrentAPNFromSetting", "curApnId:" + curApnId
					+ " apnName1:" + apnName1);
			// find apn name from apn list
			if (curApnId != null) {
				cursor = resolver.query(APN_URI, null, " _id = ?",
						new String[] { curApnId }, null);
				if (cursor != null && cursor.moveToFirst()) {
					String apnName = cursor.getString(cursor
							.getColumnIndex("apn"));
					return apnName;
				}
			}

		} catch (SQLException e) {
			Log.e("NetCheck getCurrentAPNFromSetting", e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return null;
	}

	public static int updateCurrentAPN(ContentResolver resolver, String newAPN) {
		Cursor cursor = null;
		try {
			// get new apn id from list
			cursor = resolver.query(APN_URI, null, " apn = ? and current = 1",
					new String[] { newAPN.toLowerCase() }, null);
			String apnId = null;
			if (cursor != null && cursor.moveToFirst()) {
				apnId = cursor.getString(cursor.getColumnIndex("_id"));
			}
			Log.e("NetCheck updateCurrentAPN", "apnId:" + apnId);
			// set new apn id as chosen one
			if (apnId != null) {
				ContentValues values = new ContentValues();
				values.put("apn_id", apnId);
				resolver.update(CURRENT_APN_URI, values, null, null);
			} else {
				// apn id not found, return 0.
				return 0;
			}
		} catch (SQLException e) {
			Log.e("NetCheck updateCurrentAPN", e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		// update success
		return 1;
	}

	public String getApn(Context c) {
		boolean netSataus = false;

		ConnectivityManager conManager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);	
		if (conManager.getActiveNetworkInfo() != null) {
			netSataus = conManager.getActiveNetworkInfo().isAvailable();

		}
		NetworkInfo info = conManager
		.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		String oldAPN = StringUtils.null2String(info.getExtraInfo());
		Log
		.e("NetCheck getApn", "oldAPN:" + oldAPN + " netSataus:"
				+ netSataus);
		if (netSataus == false) {
			Log.e("NetCheck getApn", "setMobileDataEnabled(true)");
			setMobileDataEnabled(c, true);	

			try {
				Thread.sleep(4012);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if("".equals(oldAPN)){			
			updateCurrentAPN(c.getContentResolver(), "cmnet");
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		info = conManager
		.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		oldAPN = StringUtils.null2String(info.getExtraInfo());
		Log
				.e("NetCheck getApn", "newApn:" + oldAPN);
		return oldAPN.toLowerCase();
	}

	public boolean setMobileDataEnabled(Context c, boolean enabled) {
		final TelephonyManager mTelManager;
		mTelManager = (TelephonyManager) c
				.getSystemService(Context.TELEPHONY_SERVICE);
		try {

			Method m = mTelManager.getClass()
					.getDeclaredMethod("getITelephony");
			m.setAccessible(true);
			Object telephony = m.invoke(mTelManager);
			m = telephony.getClass().getMethod(
					(enabled ? "enable" : "disable") + "DataConnectivity");
			m.invoke(telephony);
			return true;
		} catch (Exception e) {
			Log.e("NetCheck ", "cannot fake telephony", e);
			return false;
		}
	}

}