- 浏览: 20668 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
william_ai:
bill.830420 写道jsonp是好,但是弊端也是很明显 ...
javascript的跨域请求 -
bill.830420:
jsonp是好,但是弊端也是很明显的,楼主没有说,不能只说优点 ...
javascript的跨域请求 -
william_ai:
在解决跨域问题的方法当中,JSONP解决JavaScript的 ...
javascript的跨域请求 -
tedeum:
字很多,经常处理跨域问题,还没有一个很好的解决方案,收藏一下先 ...
javascript的跨域请求 -
william_ai:
谢谢两位投良好的朋友支持我的帖子,同时也谢谢11位投隐藏的朋友 ...
javascript的跨域请求
收藏列表
- 全部 [34]
- 默认 [3]
- python [3]
- webservice [2]
- sql [1]
- dos [2]
- ant [1]
- 统计 [2]
- shell [7]
- java se [8]
- nginx [1]
- bash [1]
- 域名解析 [1]
- btrace [1]
- dxs [1]
标题 | 标签 | 来源 | |
shell 大小写转换 | |||
tr '[a-z]' '[A-Z]' <<< "adf0ea0c2477783832bf51c486b59898" |
|||
shell 分析java类 | |||
find . -name *.java|grep main| sed -r "s/^.*\/main\/java\///g"|cut -d. -f1 find . -name *.java|grep main|xargs -I {} grep "^import" {}|sort|uniq -c|sort -n find . -name *.java|grep main|awk '{print "===============================================";print $0;system("grep \"^import\" "$0)}' find personal -name *.java|grep /main/ -m1|awk '{print "echo "$0"|sed -r \"s/.*\\/main\\///\"|sed -r \"s/.java$//\"|tr / .";}'|sh find personal -name *.java|grep /main/ -m1|awk '{system("echo "$0"|sed -r \"s/.*\\/main\\///\"|sed -r \"s/.java$//\"|tr / .|xargs -I {} echo \\\"{}\\\"");print "->"}' find personal -name *.java|grep /main/ -m1|awk '{system("echo "$0"|sed -r \"s/.*\\/main\\///\"|sed -r \"s/.java$//\"|tr / .|xargs -I {} echo \\\"{}\\\"");print "->";system("awk \"/^import.*alipay/{print $2}\" "$0"|sed -r \"s/;/\\\"/g\"|sed -r \"s/^/\\\"/g\" ");}' find personal -name *.java|grep /main/ -m2|awk '{system("echo "$0"|sed -r \"s/.*\\/main\\///\"|sed -r \"s/.java$//\"|tr / .|xargs -I {} echo \\\"{}\\\"");print "->";system("awk \"/^import.*alipay/{print $2}\" "$0"|sed -r \"s/;/\\\",/g\"|sed -r \"s/^/\\\"/g\" ");print "\"\";"}' find personal -name *.java|grep /main/ -m2|awk '{print "digraph test{";system("echo "$0"|sed -r \"s/.*\\/main\\///\"|sed -r \"s/.java$//\"|tr / .|xargs -I {} echo \\\"{}\\\"");print "->";system("awk \"/^import.*alipay/{print $2}\" "$0"|sed -r \"s/;/\\\",/g\"|sed -r \"s/^/\\\"/g\" ");print "\"\";";print "}"}' |
|||
ant velocity | java se | 基于Ant+Velocity的简单代码生成器的思路与实现 | |
package com.bnu.tools; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import com.bnu.exception.AppException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.Properties; /** * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class ContentEngine { private VelocityContext context = null; private Template template = null; // private String properties = null ; /** * * @param properties * @throws Exception */ public void init(String properties) throws Exception { if (properties != null && properties.trim().length() > 0) { Velocity.init(properties); } else { Velocity.init(); } context = new VelocityContext(); } public void init(Properties properties) throws Exception { Velocity.init(properties); context = new VelocityContext(); } /** * * @param key * @param value */ public void put(String key, Object value) { context.put(key, value); } /** * 设置模版 * * @param templateFile * 模版文件 * @throws AppException */ public void setTemplate(String templateFile) throws AppException { try { template = Velocity.getTemplate(templateFile); } catch (ResourceNotFoundException rnfe) { rnfe.printStackTrace(); throw new AppException(" error : cannot find template " + templateFile); } catch (ParseErrorException pee) { throw new AppException(" Syntax error in template " + templateFile + ":" + pee); } catch (Exception e) { throw new AppException(e.toString()); } } /** * 设置模版 * * @param templateFile * 模版文件 * @throws AppException */ public void setTemplate(String templateFile, String characterSet) throws AppException { try { template = Velocity.getTemplate(templateFile, characterSet); } catch (ResourceNotFoundException rnfe) { rnfe.printStackTrace(); throw new AppException(" error : cannot find template " + templateFile); } catch (ParseErrorException pee) { throw new AppException(" Syntax error in template " + templateFile + ":" + pee); } catch (Exception e) { throw new AppException(e.toString()); } } /** * 转换为文本文件 */ public String toText() throws AppException { StringWriter sw = new StringWriter(); try { template.merge(context, sw); } catch (Exception e) { throw new AppException(e.toString()); } return sw.toString(); } /** * * @param fileName */ public void toFile(String fileName) throws AppException { try { StringWriter sw = new StringWriter(); template.merge(context, sw); PrintWriter filewriter = new PrintWriter(new FileOutputStream( fileName), true); filewriter.println(sw.toString()); filewriter.close(); } catch (Exception e) { throw new AppException(e.toString()); } } public static void main(String[] args) { ContentEngine content = new ContentEngine(); try { Properties p = new Properties(); Properties varp = new Properties(); String path = args[1]; p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); p.setProperty(Velocity.RUNTIME_LOG, path + "velocity.log"); content.init(p); FileInputStream in = new FileInputStream(args[2]); varp.load(in); content.setTemplate(args[3], "gb2312"); Iterator it = varp.keySet().iterator(); String key = ""; String value = ""; while (it.hasNext()) { key = (String) it.next(); value = varp.getProperty(key); content.put(key, value); } if (args[0].equals("DaoImpl")) { content.put("package_Hibernate", args[4]); content.put("import_ObjectNameDao", args[5]); content.put("import_ObjectName", args[6]); content.put("objectname", args[7]); content.put("ObjectName", args[8]); content.toFile(args[9] + '/' + args[10]);//导出的路径,由参数传递。 } //else 其他情况处理部分,这里省略。 } catch (AppException ae) { ae.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } |
|||
Btrace | btrace | BTrace使用总结 | |
import com.sun.btrace.annotations.*; import static com.sun.btrace.BTraceUtils.*; @BTrace public class TracingScript { @TLS private static long startTime = 0; @OnMethod( clazz="com.learnworld.Counter", method="add" ) public static void startExecute(){ startTime = timeNanos(); } @OnMethod( clazz="com.learnworld.Counter", method="add", location=@Location(Kind.RETURN) ) public static void endExecute(@Duration long duration){ long time = timeNanos() - startTime; println(strcat("execute time(nanos): ", str(time))); println(strcat("duration(nanos): ", str(duration))); } } |
|||
java obj mem | java se | 检测Java对象所占内存大小 | |
public class Sizeof { public static void main (String [] args) throws Exception { // Warm up all classes/methods we will use runGC (); usedMemory (); // Array to keep strong references to allocated objects final int count = 100000; Object [] objects = new Object [count]; long heap1 = 0; // Allocate count+1 objects, discard the first one for (int i = -1; i < count; ++ i) { Object object = null; // Instantiate your data here and assign it to object object = new Object (); //object = new Integer (i); //object = new Long (i); //object = new String (); //object = new byte [128][1] if (i >= 0) objects [i] = object; else { object = null; // Discard the warm up object runGC (); heap1 = usedMemory (); // Take a before heap snapshot } } runGC (); long heap2 = usedMemory (); // Take an after heap snapshot: final int size = Math.round (((float)(heap2 - heap1))/count); System.out.println ("'before' heap: " + heap1 + ", 'after' heap: " + heap2); System.out.println ("heap delta: " + (heap2 - heap1) + ", {" + objects [0].getClass () + "} size = " + size + " bytes"); for (int i = 0; i < count; ++ i) objects [i] = null; objects = null; } private static void runGC () throws Exception { // It helps to call Runtime.gc() // using several method calls: for (int r = 0; r < 4; ++ r) _runGC (); } private static void _runGC () throws Exception { long usedMem1 = usedMemory (), usedMem2 = Long.MAX_VALUE; for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++ i) { s_runtime.runFinalization (); s_runtime.gc (); Thread.currentThread ().yield (); usedMem2 = usedMem1; usedMem1 = usedMemory (); } } private static long usedMemory () { return s_runtime.totalMemory () - s_runtime.freeMemory (); } private static final Runtime s_runtime = Runtime.getRuntime (); } // End of class |
|||
red hat | 统计 | ||
#red hat version lsb_release -a # cat /etc/sysctl.conf # 内核参数 cat /proc/sys/kernel/sem* |
|||
DOMAINCONTROL | 域名解析 | ||
NS73.DOMAINCONTROL.COM NS74.DOMAINCONTROL.COM NS41.DOMAINCONTROL.COM NS42.DOMAINCONTROL.COM |
|||
ant | ant | ||
#first.xml <project name="first_project" default="first_target" basedir="."> <property name="first_dir" location="${basedir}/${ant.project.name}"/> <target name="init_target"> <property name="firtt_value" value="1.0"/> </target> <target name="first_target" depends="init_target"> <ant dir="include/second"> </target> </project> #include/second/build.xml <project name="second" default="all" basedir="."> <property name="dest.dir" location="${dir.core.run}/${ant.project.name}"/> <target name="create-dir"> <mkdir dir="${dest.dir}"/> </target> <target name="copy" depends="create-dir"> <copy todir="${dest.dir}" overwrite="true"> <fileset dir="${basedir}/template"> <include name="bin/**" /> </fileset> </copy> </target> <target name="all"> <antcall target="create-dir"/> <antcall target="copy"/> </target> </project> #ant -buildfile first.xml first_target |
|||
dxs | dxs | ||
541853253 mhb15001582887 1234567 18868730401 |
|||
bash_aliases | bash | ||
alias 1="~/ccbin/ccupdate.sh && ~/ccbin/build.sh && ~/ccbin/deploy.sh" alias b="~/ccbin/build.sh" alias c="~/ccbin/mkview.sh" alias d="~/ccbin/deploy.sh" alias e="[ -f ~/logs/`hostname`/common-error.log ] && { tail -f ~/logs/`hostname`/common-error.log; }" alias f="~/ccbin/build.sh && ~/ccbin/deploy.sh" alias g="grep --color=always" alias h="cd ~" alias l="cd ~/logs/`hostname` && ll" alias k="cd ~/logs/`hostname`/ && rm -f * && cd ~ && jps|awk '/Main/{system(\"kill -9 \"\$1)}'" alias n="netstat -ltnp" alias u="~/ccbin/ccupdate.sh" |
|||
bash completion | shell | ||
_f(){ COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} OPTIONS="`f showoptions`" COMPREPLY=( $( compgen -W '${OPTIONS}' -- $cur) ) return 0 } complete -F _f f |
|||
统计 | 统计 | ||
=SUMPRODUCT((Sheet1!A2:A1000="淘宝")*(Sheet1!L2:L1000="未评价")*(Sheet1!E2:E1000<TODAY())) |
|||
文件比对 | |||
md5sum $1/*.jar | sed -e "s/$1\///g" > /tmp/list1 md5sum $2/*.jar | sed -e "s/$2\///g" > /tmp/list2 diff /tmp/list1 /tmp/list2 |
|||
Makefile | shell | ||
prod=consumequery template_user=admin all:make deploy @echo "Done @ `date +%F' '%T`" build: svn --username test --password xixihaha --no-auth-cache --non-interactive --quiet co http://svnhz.alipay.net/svn/${prod}/trunk $@ # # change user # brep -r -m 1 "/home/${template_user}" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/admin/`whoami`/g" make replace -e r_like=/home/${template_user} r_from=\\\/home\\\/${template_user} r_to=\\\/home\\\/`whoami` r_fd=$@ # # change "taobao" to "alipay" # grep -r -m 1 "/opt/taobao" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/\/opt\/taobao/\/opt\/alipay/g" make replace -e r_like=/opt/taobao r_from=\\\/opt\\\/taobao r_to=\\\/opt\\\/alipay r_fd=$@ # # change "install/httpd" to "httpd" # grep -r -m 1 "/install/httpd" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/install\/httpd/httpd/g" make replace -e r_like=install/httpd r_from=install\\\/httpd r_to=httpd r_fd=$@ clean: rm -rf build rm -rf consumequery rm -rf consumequery-run rm -rf logs rm -rf .m2 rm -rf .subversion rm -rf .logstat rm -rf ccbin rm -rf etc rm -f server.conf rm -f sofa-config.properties rm -f antx.properties ccbin: svn --username test --password xixihaha --no-auth-cache --non-interactive --quiet co http://sources.alipay.net/svn/docs/trunk/SCM/src/ccbin $@ # # change user # grep -r -m 1 "/home/${template_user}" $@|grep -v ".svn"|grep -v ".system"|cut -d: -f1|uniq|xargs sed -i "s/admin/`whoami`/g" make replace -e r_like=/home/${template_user} r_from=\\\/home\\\/${template_user} r_to=\\\/home\\\/`whoami` r_fd=$@ # # change "taobao" to "alipay" grep -r -m 1 "/opt/taobao" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/\/opt\/taobao/\/opt\/alipay/g" # change "taobao" to "alipay" -> /etc/profile mkdir -p ~/etc cp /etc/profile ~/etc/profile sed -i "s/taobao/alipay/g" ~/etc/profile grep -r -m 1 "/etc/profile" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/\/etc\/profile/~\/etc\/profile/g" # # change "install/httpd" to "httpd" # grep -r -m 1 "/install/httpd" $@|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/install\/httpd/httpd/g" make replace -e r_like=install/httpd r_from=install\\\/httpd r_to=httpd r_fd=$@ make:build ccbin ccbin/build.sh deploy:ccbin ccbin/deploy.sh replace: grep -r -m 1 "${r_like}" ${r_fd}|grep -v ".svn"|cut -d: -f1|uniq|xargs sed -i "s/${r_from}/${r_to}/g" |
|||
一行执行多个代码 | dos | ||
: usage under dos : Whether or not "echo 1" is executed successfully, and "echo 2" will be executed. echo 1 & echo 2 : "echo 1" is executed successfully, and that "echo 2" was executed. echo 1 && echo 2 # usage under linux/unix echo 1 ; echo 2 |
|||
UUID short | java se | 由UUID和短域名想到的 | |
public class Test { public static final char[] charMap; static { charMap = new char[64]; for (int i = 0; i < 10; i++) { charMap[i] = (char) ('0' + i); } for (int i = 10; i < 36; i++) { charMap[i] = (char) ('a' + i - 10); } for (int i = 36; i < 62; i++) { charMap[i] = (char) ('A' + i - 36); } charMap[62] = '_'; charMap[63] = '-'; } public static String hexTo64(String hex) { StringBuffer r = new StringBuffer(); int index = 0; int[] buff = new int[3]; int l = hex.length(); for (int i = 0; i < l; i++) { index = i % 3; buff[index] = Integer.parseInt(""+hex.charAt(i),16); if (index == 2) { r.append(charMap[buff[0] << 2 | buff[1] >>> 2]); r.append(charMap[(buff[1] &3) << 4 | buff[2]]); } } return r.toString(); } public static void process() { String uuid = "1838efee-893d-3778-b480-43d6457767ea"; uuid = uuid.replaceAll("-", "").toUpperCase(); uuid = "0" + uuid; uuid = hexTo64(uuid); } public static void test() { for (int i = 0; i < 100000; i++) { process(); } long t1 = System.nanoTime(); for (int i = 0; i < 100000; i++) { process(); } long t2 = System.nanoTime(); System.out.println(t2 - t1); } public static void main(String[] args) { test(); } } |
|||
BITMAP_001 | java se | ||
public class Test { public static final char[] charMap; static { charMap = new char[64]; for (int i = 0; i < 10; i++) { charMap[i] = (char) ('0' + i); } for (int i = 10; i < 36; i++) { charMap[i] = (char) ('a' + i - 10); } for (int i = 36; i < 62; i++) { charMap[i] = (char) ('A' + i - 36); } charMap[62] = '_'; charMap[63] = '-'; } public static void main(String[] args) { int index = Integer.parseInt("001101", 2); System.out.println(charMap[index]); } } |
|||
好用的shell | shell | ||
echo "Start Get Data" export ORACLE_HOME=/oracle/ora92/oracle export LANG=zh_CN.gb18030 export NLS_LANG="SIMPLIFIED CHINESE_CHINA.ZHS16GBK" USER=`cat ./user.sql` ${ORACLE_HOME}/bin/sqlplus -S ${USER} < data.sql > POI.dat edho "End Get Data" echo "Start Generation" date /data/home/python/python2.7.1/Python-2.7.1/python image.py > ./log.log date echo "End Generation" echo "Start Tar" rm -rf poi.tar tar cvf poi.tar poi echo "End Tar" echo "Start FTP" ftp -n 134.96.77.81 <<END quote USER custom quote PASS custom cd /home/maps/maps put poi.tar quit END echo "END FTP" echo "Start Update" (sleep 2 echo "custom" sleep 2 echo "custom" sleep 2 echo "" sleep 2 echo "clear" sleep 2 echo "cd /home/maps/maps" sleep 2 echo "tar xvf poi.tar" sleep 2 echo "^M" )|telnet 134.96.77.81 echo "End Update" |
|||
DOS 命令 | dos | ||
//系统时间 echo %date:~0,10% %time:~0,8% //备份文件 @set _date=%DATE:~0,4%_%DATE:~5,2%_%DATE:~8,2% @FOR /F "tokens=1-6 delims=: " %%i in ('time/t') do @set _time=%%i_%%j @mkdir %_date% @copy /Y image.py %_date%\image_%_time%.py |
|||
awk 文件 排重 | shell | ||
#只在$1中有的行 awk '{if(ARGIND==1) {v[$0]}else{if($0 in v) delete v[$0]}}END{for(i in v) print i}' $1 $2 #同时在$1和$2中的行 awk '{if(ARGIND==1) {v[$0]}else{if($0 in v) print $0}}' $1 $2 |
|||
shell 常用命令 | shell | ||
#shell常用命令 df ls -l wc -l awk /.../'BEGIN{...}{...}END{...}' sed comm -123 find -type sort -rn uniq -c xargs join -t , sed q column -t date +"%F %T" -d-1-(day|month|year) seq -s+ 100|bc |
|||
swap(int a,int b); | java se | ||
//c or java a^=b; b^=a; a^=b; //python a,b = b,a; |
|||
蚂蚁问题 | java se | ||
/** 题目:有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间。 */ public class Ant { public static void main(String[] args) { double[] ants = {3,7,11,17,23}; double mid = 27 / 2.0; double min = mid; double minAnt = 0; for(Double i:ants){ double temp = Math.abs(i-mid); if(temp < min){ min = temp; minAnt = i; } } int maxAnt = (23 > 27 -3)?23:(27-3); System.out.println((int)minAnt); System.out.println(maxAnt); } } |
|||
判断字符串包含问题 | python | ||
a="ABCDEFGHIJKLMNO" b="AFGHIJX" ra=0 for c in a: ra|=2**(ord(c)-65) rb=0 for c in b: rb|=2**(ord(c)-65) r = ra|rb==ra print r |
|||
awk 代替 grep | shell | ||
awk /"0.+1"/ t.dat |
|||
gae python 分页 | python | ||
#the functin of next page: def _next(self): words_query = Word.all() words_query.order("__key__") key = self.request.get("p_next_key") if key: words_query.filter("__key__ >",db.Key(key)) return words_query.fetch(P_SIZE) #the functin of previouspage: def _prev(self): words_query = Word.all() words_query.order("-__key__") key = self.request.get("p_prev_key") if key: words_query.filter("__key__ <",db.Key(key)) words = words_query.fetch(P_SIZE) words.reverse() return words |
|||
webservice with perl | webservice | ||
好久没有没有来javaeye涂鸦源码了,太忙了,真的太忙了,不过这次带来些和webservice有关的东西。不是用 java 的axis、xfire、cxf、也不是用 c 的gsoap,而是用 perl 的SOAP::Lite。这个绝对是懒人做webservice的最佳工具。当然、这是在脱离现有系统环境的前提下说的。废话不说,直接上源码。 ==========客户端代码========== #! /usr/bin/perl use SOAP::Lite; my $service = SOAP::Lite->service('http://127.0.0.1:8080/services/TestService?wsdl'); my $result = $service->getResult(1,"123"); =========================== 这个就是用perl实现webservice的客户端源码。简单吧,O(∩_∩)O哈! |
|||
USER_SOURCE | sql | ||
select * from USER_SOURCE A where A.TEXT like '%---%' |
|||
webservice using gsoap and axis | webservice | ||
第一篇在javaeye的blog,希望只是能得到共享。本文主要目的是实现功能。对gsoap的安装和wsdl2h、soapcpp2 的使用不做介绍,因为gsoap不属于java范畴,而且也确实比较简单。 一. 下载,安装gsoap 二. 开发 1. ws.h //gsoap ns1 service name: WSName //gsoap ns1 service type: WSType //gsoap ns1 service port: http://localhost //gsoap ns1 service namespace: http://namespace //gsoap ns1 service transport: http://schemas.xmlsoap.org/soap/http int ns1__getVersion( char*, char** ); 1.1 用soapcpp2生成代码 2. server.c int main(int argc, char **argv){ //soap_serve(soap_new()); SOAP_SOCKET m, s; struct soap soap; soap_init(&soap); soap_set_mode(&soap, SOAP_C_UTFSTRING); if(argc < 2){ soap_serve(&soap); }else{ m = soap_bind(&soap, NULL, atoi(argv[1]), 100); if(!soap_valid_socket(m)){ soap_print_fault(&soap, stderr); exit(-1); } fprintf(stderr, "Socket connection successful: master socket = %d\n", m); for(;;){ s = soap_accept(&soap); fprintf(stderr, "Socket connection successful: slave socket = %d\n", s); if (!soap_valid_socket(s)){ soap_print_fault(&soap, stderr); exit(-1); } soap_serve(&soap); soap_end(&soap); } } return 0; } int ns1__getVersion( struct soap *soap, char* a, char** r ) { *r = a; return SOAP_OK; } 2.1编译程序并运行 3. Test.java import org.apache.axis.client.Service; import org.apache.axis.client.Call; import javax.xml.namespace.QName; public class Test { public static void main(String[] args) throws Exception { process(); } public static void process() throws Exception { Service service = new Service(); Call call = (Call) service.createCall(); Object[] paraObject = new Object[1]; paraObject[0] = "你好"; String strServiceUrl = http://localhost; //gsoap ns1 service port call.setOperationName(new QName("http://namespace", "getVersion")); //gsoap ns1 service namespace call.setTargetEndpointAddress(new java.net.URL(strServiceUrl)); Object ret = call.invoke(paraObject); System.out.println("ret = " + ret); } } 3.1 编译运行 |
|||
CORBA with JAVA server and Python client | python | ||
最近在玩CORBA,java做的server端,python做的客户端,功能嗷嗷easy。需要注意的地方用红色标记了。下边上代码。 1.首先,我们写一个Arith.idl,简单说明一下,module叫Arith,里面有两个接口一个是Calc,另外一个是Temperature module Arith { interface Calc { void plus(in double x, in double y, out double result); void minus(in double x, in double y, out double result); void multiply(in double x, in double y, out double result); void divid(in double x, in double y, out double result); // raises (ZeroDivision); }; interface Temperature { double CelsiusToFahrenheit(in double celsiusDegree); double FahrenheitToCelsius(in double fahrenheitDegree); }; }; 2.然后是server端的代码 idlj.exe -fall Arith.idl import org.omg.CosNaming.*; // naming service import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import org.omg.PortableServer.*; import org.omg.PortableServer.POA; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import java.util.*; import Arith.*; // the package containing the stubs // and skeletons public class Server { public static void main(String args[]) { try { // create and initialize the ORB String[] parameters = new String[]{ "-ORBInitialPort", "900","-ORBInitialHost", "localhost"}; ORB orb = ORB.init(parameters, null); // get reference to rootpoa & activate the POAManager POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and register it with the ORB CalcServant servantImpl = new CalcServant(); servantImpl.setORB(orb); TemperatureServant tempImpl = new TemperatureServant(); tempImpl.setORB(orb); // get object reference from the servant org.omg.CORBA.Object ref = rootpoa.servant_to_reference(servantImpl); Calc calcRef = CalcHelper.narrow(ref); org.omg.CORBA.Object ref2 = rootpoa.servant_to_reference(tempImpl); Temperature tempRef = TemperatureHelper.narrow(ref2); // Get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // Bind the object reference in naming // add more String name = "Calc"; NameComponent[] nc = ncRef.to_name(name); ncRef.rebind(nc, calcRef); name = "Temp"; NameComponent[] nc2 = ncRef.to_name(name); ncRef.rebind(nc2, tempRef); System.out.println("server started...."); // Wait for invocations from clients java.lang.Object sync = new java.lang.Object(); synchronized (sync) { sync.wait(); } } catch (Exception e) { System.err.println("ERROR: " + e); e.printStackTrace(System.out); } } } 3.下面就是python写的客户端代码了,O(∩_∩)O哈!这里提一下,我们用到了omniORBpy-3.4-python2.5 omniidl -bpython Arith.idl import sys, CosNaming, Arith from Tkinter import * from omniORB import CORBA def frame(root,side): w=Frame(root) w.pack(side=side,expand=YES,fill=BOTH) return w def button(root,side,text,command=None): w=Button(root,text=text,command=command) w.pack(side=side,expand=YES,fill=BOTH) return w def label(root,side,text,command=None): w=Label(root,text=text,command=command) w.pack(side=side,expand=YES,fill=BOTH) return w def dLabel(root,side,text,command=None): w=Label(root,relief=SUNKEN,textvariable=text,command=command) w.pack(side=side,expand=YES,fill=BOTH) return w class Calculator(Frame): num1 = 0 num2 = 0 operation = '+' sys.argv.extend(("-ORBInitRef", "NameService=corbaname::localhost:900")) cfgs = { '+' :['Calc','Arith.Calc' ,'plus' ,], '-' :['Calc','Arith.Calc' ,'minus' ,], '*' :['Calc','Arith.Calc' ,'multiply' ,], '/' :['Calc','Arith.Calc' ,'divid' ,], 'c2f':['Temp','Arith.Temperature','CelsiusToFahrenheit',], 'f2c':['Temp','Arith.Temperature','FahrenheitToCelsius',], } def __init__(self): Frame.__init__(self) self.pack(expand=YES,fill=BOTH) self.master.title("Corba Calculator") self.master.iconname("calcl") display=StringVar() display.set('0') Entry(self,relief=SUNKEN,textvariable=display).pack(side=TOP,expand=YES,fill=BOTH) for key in ("123","456","789","-0."): deyF=frame(self,TOP) for char in key: button(deyF,LEFT,char,lambda w=display,s="%s" % char: w.set(w.get()+s)) opsF=frame(self,TOP) for char in "+-*/=": if char=='=': btn=button(opsF,LEFT,char) btn.bind("<ButtonRelease-1>",lambda e,s=self, w=display: s.calc(w),'+') else: button(opsF,LEFT,char,lambda w=display,c=char: self.setOperation(w, c)) clearF=frame(self,TOP) button(clearF,LEFT,'Clr',lambda w=display: w.set(' ')) #Config the Menu menubar = Menu(self.master) menu = Menu(menubar, tearoff=0) menu.add_checkbutton(label='Converter Component', command=lambda name='Converter Component',w=display:self.addComponent(name,w)) menubar.add_cascade(label="Add Compent", menu=menu) self.master.config(menu=menubar) def addComponent(self, val, display): board = Toplevel() board.title(val) l1=Label(board,text='Fahrenheit - Celsius Converter') l1.grid(row=1,column=1,columnspan=2) v=StringVar() v.set('a Singleton Object') l2=Label(board,textvariable=v) l2.grid(row=2,column=1,columnspan=2) c2fButton = Button(board, text="C2F", command=lambda: self.c2f(display,v,'c2f')) c2fButton.grid(row=3, column=1) f2cButton = Button(board, text="F2C", command=lambda: self.c2f(display,v,'f2c')) f2cButton.grid(row=3, column=2) mainloop() def f2c(self, display, v, op): val=float(display.get()) cfg = self.cfgs[op] v.set(self._genericFun(cfg[0],cfg[1],cfg[2],(val,))) print v.get() def c2f(self, display, v, op): val=float(display.get()) cfg = self.cfgs[op] v.set(self._genericFun(cfg[0],cfg[1],cfg[2],(val,))) print v.get() def setOperation(self, display, op): self.num1 = float(display.get()) self.operation = op display.set(' ') def calc(self,display): result = 0 self.num2 = float(display.get()) cfg = self.cfgs[self.operation] display.set(self._genericFun(cfg[0],cfg[1],cfg[2],(self.num1,self.num2,))) def _genericFun(self, naming, interface, op, pv): result = "Error" # Initialise the ORB orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) if orb is None: return result # Obtain a reference to the root naming context obj = orb.resolve_initial_references("NameService") if obj is None: return result try: rootContext = obj._narrow(CosNaming.NamingContext) except: print "Narrow Exception" return result if rootContext is None: return result # Resolve the name "naming" name = [CosNaming.NameComponent(naming,'')] try: obj = rootContext.resolve(name) except CosNaming.NamingContext.NotFound, ex: print "Name '%s' not found" % naming return result if obj is None: print "Name '%s' not found !" % naming return result # Narrow the object to the interface eo = obj._narrow(eval(interface)) if eo is None: print "%s is not Found !" % interface return result try: t = 'eo.'+op + str(pv) result = eval(t) except : print "ResultError" return result if __name__=="__main__": Calculator().mainloop() 4.好所有代码搞定,O(∩_∩)O哈! 5.配置 5.1 omniORBpy-3.4-python2.5 PATH={omniORBpy-3.4-python2.5}/bin/x86_win32 PYTHONPATH={omniORBpy-3.4-python2.5}/lib/python;{omniORBpy-3.4-python2.5}/lib/x86_win32 LD_LIBRARY_PATH={omniORBpy-3.4-python2.5}/lib/x86_win32 OMNINAMES_LOGDIR=e:\log |