Apache 2.2 日志文件access.log过大的处理
修改配置文件,按日期创建日志。
CustomLog “|D:/apache2/bin/rotatelogs.exe D:/apache2/logs/access%Y%m_%d.log 86400 480″ common
ErrorLog “|D:/apache2/bin/rotatelogs.exe D:/apache2/logs/error%Y%m_%d.log 86400 480″
修改配置文件,按日期创建日志。
CustomLog “|D:/apache2/bin/rotatelogs.exe D:/apache2/logs/access%Y%m_%d.log 86400 480″ common
ErrorLog “|D:/apache2/bin/rotatelogs.exe D:/apache2/logs/error%Y%m_%d.log 86400 480″
Tomcat6 : http://tomcat.apache.org/download-60.cgi
下载:apache-tomcat-6.0.36.exe
apache httpd server 2.2: http://www.fayea.com/apache-mirror//httpd/binaries/win32/
下载:httpd-2.2.22-win32-x86-no_ssl.msi
apache tomcat connector: http://archive.apache.org/dist/tomcat/tomcat-connectors/jk/binaries/win32/jk-1.2.31/
下载:mod_jk-1.2.31-httpd-2.2.3.so
安装路径:
E:\Apache2.2
E:\apache-tomcat-6.0.36-1
E:\apache-tomcat-6.0.36-2
项目路径:
E:\work\demo
修改 E:\Apache2.2\conf\httpd.conf 文件。
1)、加载外部配置文件:
文件最后一行加上
include conf/mod_jk.conf
2)配置项目路径:
Alias /demo "E:/work/demo"
ScriptAlias /cgi-bin/ "E:/Apache2.2/cgi-bin/"
3)配置目录权限:
Order Deny,Allow Allow from all
4)配置默认首页: 增加 index.jsp
DirectoryIndex index.jsp index.html
5)增加 E:\Apache2.2\conf\mod_jk.conf 文件内容:
LoadModule jk_module modules/mod_jk-1.2.31-httpd-2.2.3.so JkWorkersFile conf/workers.properties #指定那些请求交给tomcat处理,"controller"为在workers.propertise里指定的负载分配控制器名 JkMount /*.jsp controller
同时将 mod_jk-1.2.31-httpd-2.2.3.so 文件放入 E:\Apache2.2\modules 文件夹下。
6)增加 E:\Apache2.2\conf\workers.properties 文件内容:
#server worker.list = controller #========tomcat1======== worker.tomcat1.port=10009 worker.tomcat1.host=localhost worker.tomcat1.type=ajp13 worker.tomcat1.lbfactor = 1 #========tomcat2======== worker.tomcat2.port=11009 worker.tomcat2.host=localhost worker.tomcat2.type=ajp13 worker.tomcat2.lbfactor = 1 #========controller,负载均衡控制器======== worker.controller.type=lb worker.controller.balanced_workers=tomcat1,tomcat2 worker.controller.sticky_session=false worker.controller.sticky_session_force=1 #worker.controller.sticky_session=1
1)Tomcat-1 配置
E:\apache-tomcat-6.0.36-1\conf\server.xml
需要修改端口的地方:
1)Tomcat-2 配置
E:\apache-tomcat-6.0.36-2\conf\server.xml
需要修改端口的地方:
项目 web.xml 文件需在 下增加。
test.jsp
Cluster App Test
Server Info:
<%
out.println(request.getLocalAddr() + " : " + request.getLocalPort() + "
");
%>
<%
out.println("
ID " + session.getId() + "
");
// 如果有新的 Session 属性设置
String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0) {
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
}
out.println("Session 列表
");
System.out.println("============================");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value + "
");
System.out.println(name + " = " + value);
}
%>
名称:
值:
先启动Apache2服务,之后依次启动两个tomcat。 分别访问: http://127.0.0.1:10080/test.jsp http://127.0.0.1:11080/test.jsp http://127.0.0.1/test.jsp 接下来测试你懂得,三者 seesion 内容一致即配置成功。
1、若测试结果不成功,可以查看日志看看报什么错误,是否配置疏忽了什么环节,apache的权限有没有配置等,注意版本; 2、放在session里的对象需要序列化,即类 implements Serializable。
下载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下。
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 SSTAG1 ";
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() + "]");
}
}
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("", "");
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("", "");
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 + "毫秒]");
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);
实现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
下面这种方式不太合理,建议在创建索引库的时候排序,这样查询的时候只用分页即可,若有多个排序条件可单独创建索引库。
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主要功能花了三天时间,当然,性能如何还待测试和优化。
select to_char(sysdate,'YYYY/MM/DD') FROM DUAL; -- 2007/09/20 select to_char(sysdate,'YYYY') FROM DUAL; -- 2007 select to_char(sysdate,'YYY') FROM DUAL; -- 007 select to_char(sysdate,'YY') FROM DUAL; -- 07 select to_char(sysdate,'MM') FROM DUAL; -- 09 select to_char(sysdate,'DD') FROM DUAL; -- 20 select to_char(sysdate,'D') FROM DUAL; -- 5 select to_char(sysdate,'DDD') FROM DUAL; -- 263 select to_char(sysdate,'WW') FROM DUAL; -- 38 select to_char(sysdate,'W') FROM DUAL; -- 3 select to_char(sysdate,'YYYY/MM/DD HH24:MI:SS') FROM DUAL; -- 2007/09/20 15:24:13 select to_char(sysdate,'YYYY/MM/DD HH:MI:SS') FROM DUAL; -- 2007/09/20 03:25:23 select to_char(sysdate,'J') FROM DUAL; -- 2454364 select to_char(sysdate,'RR/MM/DD') FROM DUAL; -- 07/09/20
function sel(obj){
var id=obj.value;
var qx=document.getElementsByName("id");
for(var i = 0; i id.length&&v.startWith(id)){
if(obj.checked){
qx[i].checked=true;
} else{
qx[i].checked=false;
}
}
if(v!=""&&v.length<id.length&&id.startWith(v)){
if(obj.checked){
} else{
qx[i].checked=false;
}
}
}
}
0001 00010001 00010002 00010003
增加权限:
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());//自己重构的日志方法
查询1公里范围内的经纬度数据:
select 6371.012 *
acos(cos(acos(-1) / 180 * d.LATITUDE) *
cos(acos(-1) / 180 * 31.885972440801) *
cos(acos(-1) / 180 * d.LONGITUDE - acos(-1) / 180 * 117.30923429642) +
sin(acos(-1) / 180 * d.LATITUDE) *
sin(acos(-1) / 180 * 31.885972440801))*1 as a,
id,name
from loc_data d
where 6371.012 *
acos(cos(acos(-1) / 180 * d.LATITUDE) *
cos(acos(-1) / 180 * 31.885972440801) *
cos(acos(-1) / 180 * d.LONGITUDE - acos(-1) / 180 * 117.30923429642) +
sin(acos(-1) / 180 * d.LATITUDE) *
sin(acos(-1) / 180 * 31.885972440801))*1 < 1 order by a asc
MyEclispe 9.1 注册:
http://www.lephones.info/servlet/MyEclipseGenServlet
Subscriber:wizzer
Subscription Code:jLR8ZC-855550-60585657570866770
使用百度地图JS API,制作一个自刷新页面,将从数据库查询出的经纬度作为一个坐标点传给百度API JS,当获得位置信息后执行JS里的AJAX方法访问另外一个页面,将地址保存入库。
function myrefresh(){ window.location.reload(force=true);}setTimeout(‘myrefresh()’,1000);
window.location.reload(force=true)
绕过缓存,从服务器下载文档。
window.location.reload(force=false)
这个是默认的,检测服务器上文档是否改变,如没有改变,就从缓存调出。
ps:因google反地址解析API有频率限制,所以只好用百度地图了,没有找到百度地图URL形式的API,只能另辟蹊跷。:)
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;
}
}
}
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);
}
}
1、软件下载
Oauth服务端: http://code.google.com/p/oauth/ 通过SVN,下载源码。
或者下载站长整合好的示例源码:http://115.com/file/aqvpzqhz
客户端下载:http://code.google.com/p/oauth-signpost/ oauth-signpost
或者下载站长整合好的示例源码:http://115.com/file/bhy1d2ce
2、服务端源码下载后,把相关代码整合在一起(或直接下载站长整合好的代码),修改net.oauth.provider.core.SampleOAuthProvider 类,把从 provider.properties 读取的信息改为从数据库中读取,如APP_KEY、APP_SCERET、描述、回调地址。
3、net.oauth.example.provider.servlets下面的四个类,这里对应着oauth3个请求url,跟一个用于测试的链接,可以根据需求修改,如将调用Oauth的用户信息记录下来。
4、修改web.xml 增加三个请求url
request_token
net.oauth.provider.servlets.RequestTokenServlet
request_token
/oauth/request_token
access_token
net.oauth.provider.servlets.AccessTokenServlet
access_token
/oauth/access_token
authorize
net.oauth.provider.servlets.AuthorizationServlet
authorize
/oauth/authorize
5、做个拦截器,只要通过某url访问的都需要进行Oauth认证:
web.xml
OauthFilter
web.school.phone.OauthFilter
OauthFilter
/phone/*
web.school.phone.OauthFilter
package web.school.phone;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
import net.oauth.provider.core.SampleOAuthProvider;
import net.oauth.server.OAuthServlet;
public class OauthFilter implements Filter {
public void destroy() {
}
public void init(FilterConfig fConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
try{
OAuthMessage requestMessage = OAuthServlet.getMessage(req, null);
OAuthAccessor accessor = SampleOAuthProvider.getAccessor(requestMessage);
SampleOAuthProvider.VALIDATOR.validateMessage(requestMessage, accessor);
System.out.println("[OauthFilter:passed]:"+req.getRequestURI());
chain.doFilter(request, response);//验证通过则转向
} catch (Exception e){
//验证不通过
SampleOAuthProvider.handleException(e, req, res, false);
}
}
}
6、执行客户端代码,提示输入验证码时,把控制台打印的URL放到浏览器里打开,输入授权码:
(服务端AuthorizationServlet 里面修改验证不通过要跳转的页面,页面上会打印一些参数)
网页中实现自动上传本地文件,而不需要用户选择,这种应用场景很多,例如业务系统中需要使用的二代身份证扫描器、一体机(扫描仪)、摄像头拍照等。
首先介绍一个国外网站: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
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截图,自动把文件上传到服务器,于是联系作者。作者是个好人哈,分享了一些经验甚至代码。目前在作者的帮助下,已实现的网页控件的文件自动上传功能,可传多个文件、多表单项。
下面要解决如何在线安装的问题了……
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('/img/private/images/icon_home1.png', '', '', '', '', '', '', '','','#ff0000','');
});
//新增一个点时处理方法
function doaddpoint(img, name, dz, id, jd, wd, dh, lxr,sm,color,type)
{
var sContent ="人员姓名: " + lxr + " 手机号码: " + dh + " 定位时间: " + sm + " 上传地址: " + dz + " 定位方式: " + type + "
";
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("" + lxr +"",{offset:new BMap.Size(20,0)}));
}
BMap.Convertor.translate(gpsPoint,0,translateOptions);
}
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;
}
}
}
最近被Android系统的APN自动切换网络问题折腾死了,软件使用CMNET网络,而系统自带的一些软件必须使用CMWAP,或者手机厂家搞的一些后台服务或者流氓软件总是在切换网络。没办法,只好想个解决之道了。
我的解决方案是: 1、在程序启动时,注册 Receiver 监视网络状态,当网络发生变化判断不是CMNET时则切换网络; 2、为了保险起见,在每个HTTP链接请求前加上网络判断。
本软件主要实现了功能如下: 拍照、定位、表单文件上传、查询、短信拦截(用于通过短信指令获得手机当前位置)、拨打电话、定时自动上传定位数据、版本更新等。
如下粘贴APN网络判断网站代码: 1、NetworkChangeReceiver 网络状态监视
package com.wiz.receiver;
import com.wiz.tools.NetCheck;
import com.wiz.tools.StringUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkChangeReceiver extends BroadcastReceiver {
NetCheck netCheck=new NetCheck();
public void onReceive(Context context, Intent intent) {
Log.e("NetworkChangeReceiver", "onReceive");
ConnectivityManager conManager= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
NetworkInfo info = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
String apn = StringUtils.null2String(info.getExtraInfo());
if (!"cmnet".equals(apn.toLowerCase())) {
netCheck.checkNetworkInfo(context);
}
}
}
}
2、Activity 中注册 NetworkChangeReceiver
NetworkChangeReceiver ncr = new NetworkChangeReceiver(); IntentFilter upIntentFilter = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); this.registerReceiver(ncr, upIntentFilter);// 网络状态监控
3、APN判断及网络切换
package com.wiz.tools;
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.util.Log;
public class NetCheck {
public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
public static final Uri CURRENT_APN_URI = Uri
.parse("content://telephony/carriers/preferapn");
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"));
}
cursor.close();
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"));
}
cursor.close();
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 boolean checkNetworkInfo(Context c) {
boolean ret=false;
ConnectivityManager conManager= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean internet=conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
String oldAPN = StringUtils.null2String(info.getExtraInfo());
String oldSQLAPN=StringUtils.null2String(getCurrentAPNFromSetting(c.getContentResolver()));
Log.e("NetCheck checkNetworkInfo","oldAPN:"+oldAPN+" oldSQLAPN:"+oldSQLAPN);
if (internet==false||!"cmnet".equals(oldAPN.toLowerCase())||!"cmnet".equals(oldSQLAPN.toLowerCase())) {
if("cmwap".equals(oldAPN.toLowerCase())&&"cmnet".equals(oldSQLAPN.toLowerCase())){
updateCurrentAPN(c.getContentResolver(), "cmwap");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
updateCurrentAPN(c.getContentResolver(), "cmnet");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
ret=true;
}
return ret;
}
}
4、HTTP请求前的判断
if (nc.checkNetworkInfo(LoginActivity.this)) {
Thread.sleep(5000);// 设置cmnet网络
}
本文原创,转载请注明来源 wizzer.cn。
public void transImage(String fromFile, String toFile, int width, int height, int quality)
{
try
{
Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
// 缩放图片的尺寸
float scaleWidth = (float) width / bitmapWidth;
float scaleHeight = (float) height / bitmapHeight;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 产生缩放后的Bitmap对象
Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
// save file
File myCaptureFile = new File(toFile);
FileOutputStream out = new FileOutputStream(myCaptureFile);
if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
out.flush();
out.close();
}
if(!bitmap.isRecycled()){
bitmap.recycle();//记得释放资源,否则会内存溢出
}
if(!resizeBitmap.isRecycled()){
resizeBitmap.recycle();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
ProgressDialog 解决“第一次执行图标转动,第二次执行不转动”代码:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("正在登陆,请稍等...");
progressDialog.setCancelable(true);
// 设置ProgressDialog 是否可以按退回按键取消
return progressDialog;
default:
return null;
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case PROGRESS_DIALOG:
dialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
removeDialog(PROGRESS_DIALOG);//这个起作用
if (progressThread != null) {
progressThread = null;
}
}
});
}
}
public class APNActivity extends Activity {
public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
public static final Uri CURRENT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int _cmnetId = addAPN();
SetAPN(_cmnetId);
}
public void checkAPN(){
// 检查当前连接的APN
Cursor cr = getContentResolver().query(CURRENT_APN_URI, null, null,
null, null);
while (cr != null && cr.moveToNext()) {
// APN id
String id = cr.getString(cr.getColumnIndex("_id"));
// APN name
String apn = StringUtils.null2String(cr
.getString(cr.getColumnIndex("apn")));
// Toast.makeText(getApplicationContext(),
// "当前 id:" + id + " apn:" + apn, Toast.LENGTH_LONG).show();
}
//新增一个cmnet接入点
public int addAPN() {
int id = -1;
ContentResolver resolver = this.getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "cmnet");
values.put("apn", "cmnet");
Cursor c = null;
Uri newRow = resolver.insert(APN_URI, values);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
int idIndex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idIndex);
}
if (c != null)
c.close();
return id;
}
//设置接入点
public void SetAPN(int id) {
ContentResolver resolver = this.getContentResolver();
ContentValues values = new ContentValues();
values.put("apn_id", id);
resolver.update(CURRENT_APN_URI, values, null, null);
}
}