SVN与ReviewBoard联动(3)

前面做测试,生成了很多错误的review request。
但没有找到可以批量删除的工具,于是自己写了一个。

deleterequest.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Created on 2016-11-24
@author: Hansen
获取指定svn文件夹下,指定svn版本的注释
'''

import os
import sys

#获取指定svn版本的注释
def del_rb_request(rid1,rid2):
    for rid in range(rid1,rid2):
        cmd='curl -X DELETE --header "Authorization: token API_TOKEN" http://127.0.0.1/api/review-requests/'+str(rid)+'/'
        print(cmd)
        logs = os.popen(cmd.encode()).readlines()
        for log in logs:
            print(log)

#start here
del_rb_request(0,86)

SVN与ReviewBoard联动(2)

接上一篇。

1、脚本写了没多久,但郁闷的是测通上面的脚本我花了很久,后来发现主要是字符集的问题。

我用的是Debian默认字符集为UTF8,python2.7默认字符集为ASCII。
后面,设置了python的字符集默认为UTF8,第一篇的脚本才测通了。
/usr/lib/python2.7/sitecustomize.py

# install the apport exception handler if available
import sys

sys.setdefaultencoding('UTF8')

try:
    import apport_python_hook
except ImportError:
    pass
else:
    apport_python_hook.install()

2、然后发现RBT貌似不支持UTF8的中文参数,反正我没有测通,好吧,自己写了一个脚本将SVN上的中文注释更新到mysql中。
说明一下,RBT的这个问题,我已经向社区提交Bug了,亲测补丁有效,大家等待下一版本就好了。

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Created on 2016-11-24
@author: Hansen
用于更新rb的说明
'''

import sys
import datetime
import MySQLdb
import nsvnutils

#记录日志
def nlog(logpath,msg):
    fo = open(logpath,'a+')
    try:
        fo.write(msg+'\n')
    finally:
        fo.close()

#更新rb的reviewrequest说明
def update_rb_comment():
    #获取连接
    try:
        connection=MySQLdb.connect(user='user',passwd="passwd",host='127.0.0.1',port=3306,db='db',charset='utf8')
        subconnection=MySQLdb.connect(user='user',passwd="passwd",host='127.0.0.1',port=3306,db='db',charset='utf8')
        #print('mysql connection ok')
        nlog('/mnt/rb/sql.log','mysql connection ok')
    except Exception as ex:
        #print(str(ex))
        nlog('/mnt/rb/sql.log',str(ex))
        return

    #获取需要处理的数据
    try:
        cursor=connection.cursor()
	subcursor=subconnection.cursor()
        sql="select id,summary from reviews_reviewrequest r where r.description='' or r.description is null"
        cursor.execute(sql)
        #print('mysql select ok')
        nlog('/mnt/rb/sql.log','mysql select ok')
        for row in cursor.fetchall():
            rid=str(row[0])
            ss=row[1].split('_Rev')
	    if len(ss)==2:
                nsvnutils.get_repo_name(ss[0])
                comment=nsvnutils.get_svn_log(ss[1])
		commiter=nsvnutils.get_svn_commiter(ss[1])
                subsql="update reviews_reviewrequest r set r.description='"+commiter+"_"+comment+"' where r.id="+rid
	        #print(subsql)
                nlog('/mnt/rb/sql.log',subsql)
		subcursor.execute(subsql)
            else:
                #print('skiping id='+rid+' summary='+row[1])
                nlog('/mnt/rb/sql.log','skiping id='+rid+' summary='+row[1])
        subconnection.commit()
    except Exception as ex:
        #print(str(ex))
        nlog('/mnt/rb/sql.log',str(ex))
	return
    finally:
        cursor.close()
	subcursor.close()

    connection.close()
    subconnection.close()

#start here
nlog("/mnt/rb/sql.log", 'Starting job on '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
update_rb_comment()
nlog("/mnt/rb/sql.log", 'Ending job on '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

3、建立定时任务,执行脚本

crontab -l

#10分钟运行一次
*/10 * * * * /home/neohope/scripts/updatedb.py

SVN与ReviewBoard联动(1)

公司的SVN服务器是在Windows上的,ReviewBoard是在Linux虚拟服务器上的。
好吧,主要是历史原因了哦。。。

解决思路是,利用SVN的post-commit钩子,在提交后,将版本号存到一个文件中。
在Linux服务器中,定时去扫描这些文件,有变动的话,则利用RBTools提交请求。

1、Windows中用post-commit钩子获取版本号
post-commit.bat

@echo off
SET REPOS=%1%
SET REV=%2%
SET RPATH=PATH_TO_STORE_FILE

CALL :getfilename %REPOS%

echo %REV% >> %RPATH%\%FNAME%.txt

:success
exit 0

:getfilename
set FNAME=%~nx1

2、Linux中用python脚本扫描文件变动
runme.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Created on 2016-11-24
@author: Hansen
遍历监视文件夹下所有的txt文件
当文件多余两行时,对于每一行,调用rbt生成review请求
最后,只保留最后一行
'''

import os
import sys
import datetime
import nsvnutils

#记录日志
def nlog(logpath,msg):
    fo = open(logpath,'a+')
    try:
        fo.write(msg)
    finally:
        fo.close()

#创建rbt命令,并调用命令
def create_rbt_command(repo, revision1, revision2, logpath):
    title = repo+"_Rev"+revision1
    comment = nsvnutils.get_svn_log(revision1)
    commiter = nsvnutils.get_svn_commiter(revision1)
    #rbt好像不支持utf8参数,因此用更新db的方式添加注释
    cmd = 'rbt post -p --repository ' +repo+" --repository-type svn --server http://127.0.0.1 --api-token API_TOKEN --summary "+title+' '+revision1 
    fo = open(logpath,'a+')
    try:
        fo.write('adding rbt job on '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\n')
	fo.write('PWD is '+os.getcwd()+'\n')
	fo.write('CMD is '+cmd+'\n')
	logs = os.popen(cmd.encode('UTF8')).readlines()
        for log in logs:
	   fo.write(log+'\n')
	fo.write('\n')
    finally:
        fo.close()

#写回最后一行
def write_last_line(txtpath,line):
    fo = open(txtpath,'w+')
    try:
	fo.write(line)
    finally:
        fo.close()

#遍历行
#多于两行则自动生成post review
def enum_line(txtpath,logpath,repo):
    nlog('/mnt/rb/rb.log','Trying repositor '+repo+'\n')
    fi = open(txtpath)
    try:
	lines=fi.readlines()
	linesize=len(lines)
	if linesize <= 1:
            nlog('/mnt/rb/rb.log','Skiping repositor '+repo+'\n')
            return

        for i in range(0, linesize):
            if i+1<linesize:
		rbRepo = nsvnutils.get_repo_name(repo)
                if len(rbRepo)==0 :
                    nlog('/mnt/rb/rb.log','Skiping repositor '+repo+'\n')
                    return

                nlog('/mnt/rb/rb.log','Parsing repository '+rbRepo+'\n')
		create_rbt_command(rbRepo,lines[i].replace('\n','').replace('\r',''),lines[i+1].replace('\n','').replace('\r',''),logpath)
    except Exception as ex:
        nlog('/mnt/rb/rb.log',str(ex))
    finally:
        fi.close()

    write_last_line(txtpath,lines[linesize-1])

#递归遍历文件
def enum_file(targetdir,sufix,logpath):
    for root, dirs, files in os.walk(targetdir, True):
        for fname in files:
            fsufix = os.path.splitext(fname)[1][1:]
	    repo = os.path.splitext(fname)[0]
            if sufix == fsufix:
                txtpath = root+"/"+fname
                #txtpath = root+"\\"+fname
		enum_line(txtpath,logpath,repo)


#start here
nlog("/mnt/rb/rb.log", 'Starting job on '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\n')
enum_file("/mnt/rb","txt", "/mnt/rb/rb.log")
#enum_file("D:/MyProducts/Python/ReviewBoard/rb","txt", "D:/MyProducts/Python/ReviewBoard/rb/rb.log")
nlog("/mnt/rb/rb.log", 'Ending job on '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'\n')

nsvnutils.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Created on 2016-11-24
@author: Hansen
获取指定svn文件夹下,指定svn版本的注释
'''

import os
import sys

#切换路径,并获取repository名称
def get_repo_name(repo):
    mydict = {'REPO1':'REPO1','REPO2':'REPO2'}
    if not mydict.get(repo):
        return '' 
    os.chdir('/home/neohope/repository/'+mydict.get(repo))
    #os.chdir('D:/MyProducts/Python/ReviewBoard/repo/'+mydict(repo))
    return mydict[repo]

#获取指定svn版本的注释
def get_svn_log(revision):
    cmd = 'svn log -r '+revision
    logs = os.popen(cmd).readlines()
    #for log in logs:
    #    print(log)
    if len(logs)>3:
        print(logs[3].replace('\r','').replace('\n',''))
        return logs[3].replace('\r','').replace('\n','')
    else:
        print('no svn comment') 
        return 'no svn comment'

#获取指定svn版本的提交者
def get_svn_commiter(revision):
    cmd = 'svn log -r '+revision
    logs = os.popen(cmd).readlines()
    if len(logs)>2:
        ss=logs[1].split('|')
        if len(ss)>2:
            print(ss[1].strip().replace('\r','').replace('\n',''))
            return ss[1].strip().replace('\r','').replace('\n','')
        else:
            #print('no svn commiter') 
            return 'no svn commiter'
    else:
        #print('no svn commiter') 
        return 'no svn commiter'

#start here
#get_svn_log('193')
#get_svn_commiter('193')

3、建立定时任务,执行脚本

crontab -l

#半小时运行一次
*/30 * * * * /home/neohope/scripts/runme.py

比较麻烦的是,仍需要在Linux下面,先把SVN的repository检出才可以。
同时要注意,要做好SVN及ReviewBoard之间名称的映射。。。

VBoxManage常用命令

1、常用命令

#列出全部虚拟机
VBoxManage list vms
#列出全部运行中的虚拟机
VBoxManage list runningvms
#列出虚拟机信息
VBoxManage showvminfo uuid|vmname
#开启虚拟机
VBoxManage startvm uuid|vmname
#开启虚拟机,无GUI模式
VBoxManage startvm uuid|vmname --type headless
#暂停虚拟机
VBoxManage controlvm uuid|vmname pause
#继续运行虚拟机
VBoxManage controlvm uuid|vmname resume
#按下机箱重启按钮
VBoxManage controlvm uuid|vmname reset
#断电
VBoxManage controlvm uuid|vmname poweroff
#按下机箱电影按钮
VBoxManage controlvm uuid|vmname acpipowerbutton
#按下机箱睡眠按钮
VBoxManage controlvm uuid|vmname acpisleepbutton

2、全部参数

Oracle VM VirtualBox Command Line Management Interface Version 4.3.10
(C) 2005-2014 Oracle Corporation
All rights reserved.

Usage:

  VBoxManage [<general option>] <command>
 
 
General Options:
 
  [-v|--version]            print version number and exit
  [-q|--nologo]             suppress the logo
  [--settingspw <pw>]       provide the settings password
  [--settingspwfile <file>] provide a file containing the settings password
 
 
Commands:
 
  list [--long|-l]          vms|runningvms|ostypes|hostdvds|hostfloppies|
                            intnets|bridgedifs|hostonlyifs|natnets|dhcpservers|
                            hostinfo|hostcpuids|hddbackends|hdds|dvds|floppies|
                            usbhost|usbfilters|systemproperties|extpacks|
                            groups|webcams

  showvminfo                <uuid|vmname> [--details]
                            [--machinereadable]
  showvminfo                <uuid|vmname> --log <idx>

  registervm                <filename>

  unregistervm              <uuid|vmname> [--delete]

  createvm                  --name <name>
                            [--groups <group>, ...]
                            [--ostype <ostype>]
                            [--register]
                            [--basefolder <path>]
                            [--uuid <uuid>]

  modifyvm                  <uuid|vmname>
                            [--name <name>]
                            [--groups <group>, ...]
                            [--ostype <ostype>]
                            [--iconfile <filename>]
                            [--memory <memorysize in MB>]
                            [--pagefusion on|off]
                            [--vram <vramsize in MB>]
                            [--acpi on|off]
                            [--pciattach 03:04.0]
                            [--pciattach 03:04.0@02:01.0]
                            [--pcidetach 03:04.0]
                            [--ioapic on|off]
                            [--hpet on|off]
                            [--triplefaultreset on|off]
                            [--hwvirtex on|off]
                            [--nestedpaging on|off]
                            [--largepages on|off]
                            [--vtxvpid on|off]
                            [--vtxux on|off]
                            [--pae on|off]
                            [--longmode on|off]
                            [--synthcpu on|off]
                            [--cpuidset <leaf> <eax> <ebx> <ecx> <edx>]
                            [--cpuidremove <leaf>]
                            [--cpuidremoveall]
                            [--hardwareuuid <uuid>]
                            [--cpus <number>]
                            [--cpuhotplug on|off]
                            [--plugcpu <id>]
                            [--unplugcpu <id>]
                            [--cpuexecutioncap <1-100>]
                            [--rtcuseutc on|off]
                            [--graphicscontroller none|vboxvga|vmsvga]
                            [--monitorcount <number>]
                            [--accelerate3d on|off]
                            [--accelerate2dvideo on|off]
                            [--firmware bios|efi|efi32|efi64]
                            [--chipset ich9|piix3]
                            [--bioslogofadein on|off]
                            [--bioslogofadeout on|off]
                            [--bioslogodisplaytime <msec>]
                            [--bioslogoimagepath <imagepath>]
                            [--biosbootmenu disabled|menuonly|messageandmenu]
                            [--biossystemtimeoffset <msec>]
                            [--biospxedebug on|off]
                            [--boot<1-4> none|floppy|dvd|disk|net>]
                            [--nic<1-N> none|null|nat|bridged|intnet|hostonly|
                                        generic|natnetwork]
                            [--nictype<1-N> Am79C970A|Am79C973|
                                            82540EM|82543GC|82545EM|
                                            virtio]
                            [--cableconnected<1-N> on|off]
                            [--nictrace<1-N> on|off]
                            [--nictracefile<1-N> <filename>]
                            [--nicproperty<1-N> name=[value]]
                            [--nicspeed<1-N> <kbps>]
                            [--nicbootprio<1-N> <priority>]
                            [--nicpromisc<1-N> deny|allow-vms|allow-all]
                            [--nicbandwidthgroup<1-N> none|<name>]
                            [--bridgeadapter<1-N> none|<devicename>]
                            [--hostonlyadapter<1-N> none|<devicename>]
                            [--intnet<1-N> <network name>]
                            [--nat-network<1-N> <network name>]
                            [--nicgenericdrv<1-N> <driver>
                            [--natnet<1-N> <network>|default]
                            [--natsettings<1-N> [<mtu>],[<socksnd>],
                                                [<sockrcv>],[<tcpsnd>],
                                                [<tcprcv>]]
                            [--natpf<1-N> [<rulename>],tcp|udp,[<hostip>],
                                          <hostport>,[<guestip>],<guestport>]
                            [--natpf<1-N> delete <rulename>]
                            [--nattftpprefix<1-N> <prefix>]
                            [--nattftpfile<1-N> <file>]
                            [--nattftpserver<1-N> <ip>]
                            [--natbindip<1-N> <ip>
                            [--natdnspassdomain<1-N> on|off]
                            [--natdnsproxy<1-N> on|off]
                            [--natdnshostresolver<1-N> on|off]
                            [--nataliasmode<1-N> default|[log],[proxyonly],
                                                         [sameports]]
                            [--macaddress<1-N> auto|<mac>]
                            [--mouse ps2|usb|usbtablet|usbmultitouch]
                            [--keyboard ps2|usb
                            [--uart<1-N> off|<I/O base> <IRQ>]
                            [--uartmode<1-N> disconnected|
                                             server <pipe>|
                                             client <pipe>|
                                             file <file>|
                                             <devicename>]
                            [--lpt<1-N> off|<I/O base> <IRQ>]
                            [--lptmode<1-N> <devicename>]
                            [--guestmemoryballoon <balloonsize in MB>]
                            [--audio none|null|dsound]
                            [--audiocontroller ac97|hda|sb16]
                            [--clipboard disabled|hosttoguest|guesttohost|
                                         bidirectional]
                            [--draganddrop disabled|hosttoguest
                            [--vrde on|off]
                            [--vrdeextpack default|<name>
                            [--vrdeproperty <name=[value]>]
                            [--vrdeport <hostport>]
                            [--vrdeaddress <hostip>]
                            [--vrdeauthtype null|external|guest]
                            [--vrdeauthlibrary default|<name>
                            [--vrdemulticon on|off]
                            [--vrdereusecon on|off]
                            [--vrdevideochannel on|off]
                            [--vrdevideochannelquality <percent>]
                            [--usb on|off]
                            [--usbehci on|off]
                            [--snapshotfolder default|<path>]
                            [--teleporter on|off]
                            [--teleporterport <port>]
                            [--teleporteraddress <address|empty>
                            [--teleporterpassword <password>]
                            [--teleporterpasswordfile <file>|stdin]
                            [--tracing-enabled on|off]
                            [--tracing-config <config-string>]
                            [--tracing-allow-vm-access on|off]
                            [--usbcardreader on|off]
                            [--autostart-enabled on|off]
                            [--autostart-delay <seconds>]
                            [--vcpenabled on|off]
                            [--vcpscreens [<display>],...
                            [--vcpfile <filename>]
                            [--vcpwidth <width>]
                            [--vcpheight <height>]
                            [--vcprate <rate>]
                            [--vcpfps <fps>]
                            [--defaultfrontend default|<name>]

  clonevm                   <uuid|vmname>
                            [--snapshot <uuid>|<name>]
                            [--mode machine|machineandchildren|all]
                            [--options link|keepallmacs|keepnatmacs|
                                       keepdisknames]
                            [--name <name>]
                            [--groups <group>, ...]
                            [--basefolder <basefolder>]
                            [--uuid <uuid>]
                            [--register]

  import                    <ovfname/ovaname>
                            [--dry-run|-n]
                            [--options keepallmacs|keepnatmacs]
                            [more options]
                            (run with -n to have options displayed
                             for a particular OVF)

  export                    <machines> --output|-o <name>.<ovf/ova>
                            [--legacy09|--ovf09|--ovf10|--ovf20]
                            [--manifest]
                            [--iso]
                            [--options manifest|iso|nomacs|nomacsbutnat]
                            [--vsys <number of virtual system>]
                                    [--product <product name>]
                                    [--producturl <product url>]
                                    [--vendor <vendor name>]
                                    [--vendorurl <vendor url>]
                                    [--version <version info>]
                                    [--description <description info>]
                                    [--eula <license text>]
                                    [--eulafile <filename>]

  startvm                   <uuid|vmname>...
                            [--type gui|sdl|headless]

  controlvm                 <uuid|vmname>
                            pause|resume|reset|poweroff|savestate|
                            acpipowerbutton|acpisleepbutton|
                            keyboardputscancode <hex> [<hex> ...]|
                            setlinkstate<1-N> on|off |
                            nic<1-N> null|nat|bridged|intnet|hostonly|generic|
                                     natnetwork [<devicename>] |
                            nictrace<1-N> on|off |
                            nictracefile<1-N> <filename> |
                            nicproperty<1-N> name=[value] |
                            nicpromisc<1-N> deny|allow-vms|allow-all |
                            natpf<1-N> [<rulename>],tcp|udp,[<hostip>],
                                        <hostport>,[<guestip>],<guestport> |
                            natpf<1-N> delete <rulename> |
                            guestmemoryballoon <balloonsize in MB> |
                            usbattach <uuid>|<address> |
                            usbdetach <uuid>|<address> |
                            clipboard disabled|hosttoguest|guesttohost|
                                      bidirectional |
                            draganddrop disabled|hosttoguest |
                            vrde on|off |
                            vrdeport <port> |
                            vrdeproperty <name=[value]> |
                            vrdevideochannelquality <percent> |
                            setvideomodehint <xres> <yres> <bpp>
                                            [[<display>] [<enabled:yes|no> |
                                              [<xorigin> <yorigin>]]] |
                            screenshotpng <file> [display] |
                            vcpenabled on|off |
                            vcpscreens all|none|<screen>,[<screen>...] |
                            setcredentials <username>
                                           --passwordfile <file> | <password>
                                           <domain>
                                           [--allowlocallogon <yes|no>] |
                            teleport --host <name> --port <port>
                                     [--maxdowntime <msec>]
                                     [--passwordfile <file> |
                                      --password <password>] |
                            plugcpu <id> |
                            unplugcpu <id> |
                            cpuexecutioncap <1-100>
                            webcam <attach [path [settings]]> | <detach [path]> | <list>

  discardstate              <uuid|vmname>

  adoptstate                <uuid|vmname> <state_file>

  snapshot                  <uuid|vmname>
                            take <name> [--description <desc>] [--live] |
                            delete <uuid|snapname> |
                            restore <uuid|snapname> |
                            restorecurrent |
                            edit <uuid|snapname>|--current
                                 [--name <name>]
                                 [--description <desc>] |
                            list [--details|--machinereadable]
                            showvminfo <uuid|snapname>

  closemedium               disk|dvd|floppy <uuid|filename>
                            [--delete]

  storageattach             <uuid|vmname>
                            --storagectl <name>
                            [--port <number>]
                            [--device <number>]
                            [--type dvddrive|hdd|fdd]
                            [--medium none|emptydrive|additions|
                                      <uuid|filename>|host:<drive>|iscsi]
                            [--mtype normal|writethrough|immutable|shareable|
                                     readonly|multiattach]
                            [--comment <text>]
                            [--setuuid <uuid>]
                            [--setparentuuid <uuid>]
                            [--passthrough on|off]
                            [--tempeject on|off]
                            [--nonrotational on|off]
                            [--discard on|off]
                            [--bandwidthgroup <name>]
                            [--forceunmount]
                            [--server <name>|<ip>]
                            [--target <target>]
                            [--tport <port>]
                            [--lun <lun>]
                            [--encodedlun <lun>]
                            [--username <username>]
                            [--password <password>]
                            [--initiator <initiator>]
                            [--intnet]

  storagectl                <uuid|vmname>
                            --name <name>
                            [--add ide|sata|scsi|floppy|sas]
                            [--controller LSILogic|LSILogicSAS|BusLogic|
                                          IntelAHCI|PIIX3|PIIX4|ICH6|I82078]
                            [--portcount <1-30>]
                            [--hostiocache on|off]
                            [--bootable on|off]
                            [--remove]

  bandwidthctl              <uuid|vmname>
                            add <name> --type disk|network
                                --limit <megabytes per second>[k|m|g|K|M|G] |
                            set <name>
                                --limit <megabytes per second>[k|m|g|K|M|G] |
                            remove <name> |
                            list [--machinereadable]
                            (limit units: k=kilobit, m=megabit, g=gigabit,
                                          K=kilobyte, M=megabyte, G=gigabyte)

  showhdinfo                <uuid|filename>

  createhd                  --filename <filename>
                            [--size <megabytes>|--sizebyte <bytes>]
                            [--diffparent <uuid>|<filename>
                            [--format VDI|VMDK|VHD] (default: VDI)
                            [--variant Standard,Fixed,Split2G,Stream,ESX]

  modifyhd                  <uuid|filename>
                            [--type normal|writethrough|immutable|shareable|
                                    readonly|multiattach]
                            [--autoreset on|off]
                            [--property <name=[value]>]
                            [--compact]
                            [--resize <megabytes>|--resizebyte <bytes>]

  clonehd                   <uuid|inputfile> <uuid|outputfile>
                            [--format VDI|VMDK|VHD|RAW|<other>]
                            [--variant Standard,Fixed,Split2G,Stream,ESX]
                            [--existing]

  convertfromraw            <filename> <outputfile>
                            [--format VDI|VMDK|VHD]
                            [--variant Standard,Fixed,Split2G,Stream,ESX]
                            [--uuid <uuid>]
  convertfromraw            stdin <outputfile> <bytes>
                            [--format VDI|VMDK|VHD]
                            [--variant Standard,Fixed,Split2G,Stream,ESX]
                            [--uuid <uuid>]

  getextradata              global|<uuid|vmname>
                            <key>|enumerate

  setextradata              global|<uuid|vmname>
                            <key>
                            [<value>] (no value deletes key)

  setproperty               machinefolder default|<folder> |
                            hwvirtexclusive on|off |
                            vrdeauthlibrary default|<library> |
                            websrvauthlibrary default|null|<library> |
                            vrdeextpack null|<library> |
                            autostartdbpath null|<folder> |
                            loghistorycount <value>
                            defaultfrontend default|<name>

  usbfilter                 add <index,0-N>
                            --target <uuid|vmname>|global
                            --name <string>
                            --action ignore|hold (global filters only)
                            [--active yes|no] (yes)
                            [--vendorid <XXXX>] (null)
                            [--productid <XXXX>] (null)
                            [--revision <IIFF>] (null)
                            [--manufacturer <string>] (null)
                            [--product <string>] (null)
                            [--remote yes|no] (null, VM filters only)
                            [--serialnumber <string>] (null)
                            [--maskedinterfaces <XXXXXXXX>]

  usbfilter                 modify <index,0-N>
                            --target <uuid|vmname>|global
                            [--name <string>]
                            [--action ignore|hold] (global filters only)
                            [--active yes|no]
                            [--vendorid <XXXX>|""]
                            [--productid <XXXX>|""]
                            [--revision <IIFF>|""]
                            [--manufacturer <string>|""]
                            [--product <string>|""]
                            [--remote yes|no] (null, VM filters only)
                            [--serialnumber <string>|""]
                            [--maskedinterfaces <XXXXXXXX>]

  usbfilter                 remove <index,0-N>
                            --target <uuid|vmname>|global

  sharedfolder              add <uuid|vmname>
                            --name <name> --hostpath <hostpath>
                            [--transient] [--readonly] [--automount]

  sharedfolder              remove <uuid|vmname>
                            --name <name> [--transient]

  guestproperty             get <uuid|vmname>
                            <property> [--verbose]

  guestproperty             set <uuid|vmname>
                            <property> [<value> [--flags <flags>]]

  guestproperty             delete|unset <uuid|vmname>
                            <property>

  guestproperty             enumerate <uuid|vmname>
                            [--patterns <patterns>]

  guestproperty             wait <uuid|vmname> <patterns>
                            [--timeout <msec>] [--fail-on-timeout]

  guestcontrol              <uuid|vmname>

                              exec[ute]
                              --image <path to program> --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose] [--timeout <msec>]
                              [--environment "<NAME>=<VALUE> [<NAME>=<VALUE>]"]
                              [--wait-exit] [--wait-stdout] [--wait-stderr]
                              [--dos2unix] [--unix2dos]
                              [-- [<argument1>] ... [<argumentN>]]

                              copyfrom
                              <guest source> <host dest> --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]
                              [--dryrun] [--follow] [--recursive]

                              copyto|cp
                              <host source> <guest dest> --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]
                              [--dryrun] [--follow] [--recursive]

                              createdir[ectory]|mkdir|md
                              <guest directory>... --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]
                              [--parents] [--mode <mode>]

                              removedir[ectory]|rmdir
                              <guest directory>... --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]
                              [--recursive|-R|-r]

                              removefile|rm
                              <guest file>... --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]

                              ren[ame]|mv
                              <source>... <dest> --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]

                              createtemp[orary]|mktemp
                              <template> --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--directory] [--secure] [--tmpdir <directory>]
                              [--domain <domain>] [--mode <mode>] [--verbose]

                              list <all|sessions|processes|files> [--verbose]

                              process kill --session-id <ID>
                                           | --session-name <name or pattern>
                                           [--verbose]
                                           <PID> ... <PID n>

                              [p[s]]kill --session-id <ID>
                                         | --session-name <name or pattern>
                                         [--verbose]
                                         <PID> ... <PID n>

                              session close  --session-id <ID>
                                           | --session-name <name or pattern>
                                           | --all
                                           [--verbose]

                              stat
                              <file>... --username <name>
                              [--passwordfile <file> | --password <password>]
                              [--domain <domain>] [--verbose]

                              updateadditions
                              [--source <guest additions .ISO>] [--verbose]
                              [--wait-start]
                              [-- [<argument1>] ... [<argumentN>]]

                              watch [--verbose]

  debugvm                   <uuid|vmname>
                            dumpguestcore --filename <name> |
                            info <item> [args] |
                            injectnmi |
                            log [--release|--debug] <settings> ...|
                            logdest [--release|--debug] <settings> ...|
                            logflags [--release|--debug] <settings> ...|
                            osdetect |
                            osinfo |
                            getregisters [--cpu <id>] <reg>|all ... |
                            setregisters [--cpu <id>] <reg>=<value> ... |
                            show [--human-readable|--sh-export|--sh-eval|
                                  --cmd-set] 
                                <logdbg-settings|logrel-settings>
                                [[opt] what ...] |
                            statistics [--reset] [--pattern <pattern>]
                            [--descriptions]

  metrics                   list [*|host|<vmname> [<metric_list>]]
                                                 (comma-separated)

  metrics                   setup
                            [--period <seconds>] (default: 1)
                            [--samples <count>] (default: 1)
                            [--list]
                            [*|host|<vmname> [<metric_list>]]

  metrics                   query [*|host|<vmname> [<metric_list>]]

  metrics                   enable
                            [--list]
                            [*|host|<vmname> [<metric_list>]]

  metrics                   disable
                            [--list]
                            [*|host|<vmname> [<metric_list>]]

  metrics                   collect
                            [--period <seconds>] (default: 1)
                            [--samples <count>] (default: 1)
                            [--list]
                            [--detach]
                            [*|host|<vmname> [<metric_list>]]

  natnetwork                add --netname <name>
                            --network <network>
                            [--enable|--disable]
                            [--dhcp on|off]
                            [--port-forward-4 <rule>]
                            [--loopback-4 <rule>]
                            [--ipv6 on|off]
                            [--port-forward-6 <rule>]
                            [--loopback-6 <rule>]

  natnetwork                remove --netname <name>

  natnetwork                modify --netname <name>
                            [--network <network>]
                            [--enable|--disable]
                            [--dhcp on|off]
                            [--port-forward-4 <rule>]
                            [--loopback-4 <rule>]
                            [--ipv6 on|off]
                            [--port-forward-6 <rule>]
                            [--loopback-6 <rule>]

  natnetwork                start --netname <name>

  natnetwork                stop --netname <name>

  hostonlyif                ipconfig <name>
                            [--dhcp |
                            --ip<ipv4> [--netmask<ipv4> (def: 255.255.255.0)] |
                            --ipv6<ipv6> [--netmasklengthv6<length> (def: 64)]]
                            create |
                            remove <name>

  dhcpserver                add|modify --netname <network_name> |
                                       --ifname <hostonly_if_name>
                            [--ip <ip_address>
                            --netmask <network_mask>
                            --lowerip <lower_ip>
                            --upperip <upper_ip>]
                            [--enable | --disable]

  dhcpserver                remove --netname <network_name> |
                                   --ifname <hostonly_if_name>

  extpack                   install [--replace] <tarball> |
                            uninstall [--force] <name> |
                            cleanup

Debain8安装ReviewBoard

1、安装需要的软件及软件包

#更新apt软件列表
apt-get update

#安装mysql
apt-get install mysql-server

#安装apache2
apt-get install apache2

#安装mod_wsgi
apt-get install libapache2-mod-wsgi

#安装memcached
apt-get install memcached

#安装patch
apt-get install patch

#安排subversion
apt-get install subversion

2、配置MySQL

#修改配置文件
vi /etc/mysql/my.cnf
#添加下面内容
[client]
default-character-set=utf8
[mysqld]
character-set-server=utf8


#重启mysql
/etc/init.d/mysql restart


#新建数据库、用户并授权
mysql -u root -p
mysql> CREATE DATABASE reviewboard CHARACTER SET utf8;
mysql> CREATE USER 'reviewboard'@'localhost' IDENTIFIED BY 'reviewboard';
mysql> GRANT ALL PRIVILEGES ON reviewboard.* to 'reviewboard'@'localhost';

3、配置svn(我的svn和reviewboard不是在一台机器上的,不需要重新配置)

4、配置Python2.7环境

#安装python-setuptools
apt-get install python-setuptools

#安装python-dev
apt-get install python-dev

#安装python-mysqldb
apt-get install python-mysqldb
#替代方案
#easy_install mysql-python

#安装python-svn
apt-get install python-svn

#安装 libffi-dev
apt-get install libffi-dev

#安装ReviewBoard
easy_install ReviewBoard

#你可以用pip安装
#eays_install pip
#pip install pipdeptree
#pip install ReviewBoard

5、安装网站

#这句话会报错,因为依赖的Django版本冲突所导致的
rb-site install /var/www/reviewboard

#查看插件依赖
pipdeptree

#可以看到
#ReviewBoard依赖Django [required: <1.7,>=1.6.11, installed: 1.8]
#django-haystack依赖Django [required: >=1.8, installed: 1.8]
argparse==1.2.1
chardet==2.3.0
lxml==3.4.0
MySQL-python==1.2.3
numpy==1.8.2
pycups==1.9.63
pycurl==7.19.5
pygobject==3.14.0
pysmbc==1.0.15.3
python-apt==0.9.3.11
python-debian==0.1.27
  - six [required: None, installed: 1.8.0]
python-debianbts==1.11
pyxdg==0.25
reportbug==6.6.3
ReviewBoard==2.5.1
  - Django [required: <1.7,>=1.6.11, installed: 1.8]
  - django-evolution [required: <=0.7.999,>=0.7.5, installed: 0.7.6]
    - Django [required: <1.7.0,>=1.4.10, installed: 1.8]
  - django-haystack [required: >=2.3.1, installed: 2.5.0]
    - Django [required: >=1.8, installed: 1.8]
    - Django [required: <1.10, installed: 1.8]
  - django-multiselectfield [required: None, installed: 0.1.4]
    - django [required: >=1.4, installed: 1.8]
  - Djblets [required: <=0.9.999,>=0.9, installed: 0.9.3]
    - Django [required: >=1.6.11,<1.8.999, installed: 1.8]
    - django-pipeline [required: <1.3.9999,>=1.3.23, installed: 1.3.27]
      - futures [required: >=2.1.3, installed: 3.0.5]
    - feedparser [required: >=5.1.2, installed: 5.2.1]
    - pillowfight [required: None, installed: 0.2]
      - Pillow [required: None, installed: 2.6.1]
    - pytz [required: None, installed: 2016.7]
  - docutils [required: None, installed: 0.12]
  - markdown [required: <2.4.999,>=2.4.0, installed: 2.4.1]
  - mimeparse [required: >=0.1.3, installed: 0.1.3]
  - paramiko [required: >=1.12, installed: 2.0.2]
    - cryptography [required: >=1.1, installed: 1.5.2]
      - cffi [required: >=1.4.1, installed: 1.8.3]
        - pycparser [required: None, installed: 2.14]
      - enum34 [required: None, installed: 1.1.6]
      - idna [required: >=2.0, installed: 2.1]
      - ipaddress [required: None, installed: 1.0.17]
      - pyasn1 [required: >=0.1.8, installed: 0.1.9]
      - setuptools [required: >=11.3, installed: 28.6.0]
      - six [required: >=1.4.1, installed: 1.8.0]
    - pyasn1 [required: >=0.1.7, installed: 0.1.9]
  - pycrypto [required: >=2.6, installed: 2.6.1]
  - Pygments [required: >=1.6, installed: 2.0.1]
  - python-dateutil [required: ==1.5, installed: 1.5]
  - python-memcached [required: None, installed: 1.58]
    - six [required: >=1.4.0, installed: 1.8.0]
  - pytz [required: None, installed: 2016.7]
  - recaptcha-client [required: None, installed: 1.0.6]
  - Whoosh [required: >=2.6, installed: 2.7.4]
roman==2.0.0
SOAPpy==0.12.22
  - defusedxml [required: None, installed: 0.4.1]
  - wstools [required: None, installed: 0.4.3]
    - docutils [required: None, installed: 0.12]
wsgiref==0.1.2

#所以降级django-haystack就好了
easy_install -m django
easy_install -m django-haystack
easy_install django-haystack==2.3.1
easy_install reviewboard

6、安装网站,并修改网站权限

#安装网站,按提示输入
rb-site install /var/www/reviewboard
chown -R www-data /var/www/reviewboard/htdocs/media/uploaded
chown -R www-data /var/www/reviewboard/data
chown -R www-data /var/www/reviewboard/logs
chown -R www-data /var/www/reviewboard/htdocs/media/ext
chown -R www-data /var/www/reviewboard/htdocs/static/ext

7、配置访问权限

#配置访问权限
vi /var/www/reviewboard/conf/settings_local.py

#修改下面一行,这是不限制任何访问
ALLOW_HOSTS=['*']

8、配置apache2虚拟目录

cp /var/www/reviewboard/conf/apache-wsgi.conf /etc/apache2/sites-available/reviewboard.conf
#按实际需要的部署情况,编辑reviewboard.conf
cd /etc/apache2/sites-enabled
ln -s ../sites-avaiable/reviewboard.conf

9、重启apache2

/etc/init.d/apache2 restart

10、打开浏览器就可以登录啦

11、另外,我是在虚拟机中部署的reviewboard,我尝试了用nginx反向代理reviewboard,但没有成功。
用firebug看到,json中的ip地址没有改写,最后发现是因为django没有正确的处理absolute_path。
好像增加一些django的配置就好了,但实在是没时间处理了。
最后用bridege方式将虚拟机映射出来,完成部署。

ASP.Net检测到有潜在危险的Request.Form值

前两天公司一哥们遇到了这个问题,记录一下解决方法:

ASP.NET 2.0
方案一:将aspx文件中的page项添加ValidateRequest=”false”

  <%@ Page ValidateRequest="false"  Language="C#" AutoEventWireup="true" CodeFile="xxx.aspx.cs" Inherits="xxx.xxx" %>  

方案二:修改web.config配置文件(全局有效,慎用)

  <system.web> 
      <pages validateRequest="false"></pages>   
  </system.web> 

ASP.NET 4.0
方案一:修改web.config配置文件(全局有效,慎用)

  <system.web>
      <httpRuntime requestValidationMode="2.0" />
      <pages validateRequest="false"></pages>
  </system.web>

ASP.NET MVC
方案一:修改web.config配置文件(全局有效,慎用)
修改web.config配置文件(全局有效,慎用)

  <system.web>
      <httpRuntime requestValidationMode="2.0" />
  </system.web>

然后修改控制器

[HttpPost]
[ValidateInput(false)]
public ActionResult XXX(xxx xxx)
{
}

JSP输出容器的JVM参数

<%@ page language="java" import="java.util.*, java.lang.management.*" pageEncoding="UTF-8"%>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>系统参数输出</title>
<style type="text/css">
table
{
    border-collapse:collapse;
}
td
{
    border:1px solid #427BD6;
}
</style>
</head>

<body style="background-color:#f2f2f2;">

<h1>环境变量</h1>
<table>
<%
    Map<String, String> map = System.getenv();
    //RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    //Map<String, String> map = runtimeMxBean.getSystemProperties();
    for(String key : map.keySet())
    {
        out.println("<tr>");
        out.println("<td>");
        out.println(key);
        out.println("</td>");
        out.println("<td>");
        out.println(map.get(key));
        out.println("</td>");
        out.println("</tr>");
    }     
%>
</table>

<h1>JVM参数</h1>
<table>
<% 
    RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
    
    out.println("<tr>");
    out.println("<td>");
    out.println(runtimeMxBean.getVmVendor()+" || "+runtimeMxBean.getVmName() +" || "+ runtimeMxBean.getVmVersion());
    out.println("</td>");
    out.println("</tr>");
    
    out.println("<tr>");
    out.println("<td>");
    out.println(runtimeMxBean.getSpecVendor()+" || "+runtimeMxBean.getSpecName() +" || "+ runtimeMxBean.getSpecVersion());
    out.println("</td>");
    out.println("</tr>");
    
    out.println("<tr>");
    out.println("<td>");
    out.println(runtimeMxBean.getName()+" || "+runtimeMxBean.getStartTime() +" || "+ runtimeMxBean.getUptime());
    out.println("</td>");
    out.println("</tr>");
    
    out.println("<tr>");
    out.println("<td>");
    out.println("MaxMemory="+Runtime.getRuntime().maxMemory()/1024/1024 + "m ");
    out.println("TotalMemory="+Runtime.getRuntime().totalMemory()/1024/1024 + "m ");
    out.println("FreeMemory="+Runtime.getRuntime().freeMemory()/1024/1024 + "m ");
    out.println("</td>");
    out.println("</tr>");
    
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean bean : memoryPoolMXBeans)
    {
        out.println("<tr>");
        out.println("<td>");
        out.println(bean.getName()+" || "+bean.getType()+" || Init="+bean.getUsage().getInit()/1024/1024+
        "m Max="+bean.getUsage().getMax()/1024/1024+"m Used="+bean.getUsage().getUsed()/1024/1024+
        "m Committed="+bean.getUsage().getCommitted()/1024/1024+"m ");
        out.println("</td>");
        out.println("</tr>");
    }
    
    List<String> arguments = runtimeMxBean.getInputArguments();
    for(String arg:arguments)
    {
        out.println("<tr>");
        out.println("<td>");
        out.println(arg);
        out.println("</td>");
        out.println("</tr>");
    }
%>
</table>

<h1>系统参数</h1>
<table>
<%
    Properties props = System.getProperties();
    for(Object o:props.keySet())
    {
        out.println("<tr>");
        out.println("<td>");
        out.println(o);
        out.println("</td>");
        out.println("<td>");
        out.println(props.get(o));
        out.println("</td>");
        out.println("</tr>");
    }
%>
</table>
</body>
</html>

SVN禁止提交时不写注释

最常用的方法,就是使用SVN提供的pre-commit钩子。
具体做法是,在对应的repository下的hooks文件夹下中,新建对于的pre-commit脚本,来禁止提交。

1.windows下pre-commit.bat

@echo off
setlocal

set REPOS=%1
set TXN=%2

rem 保证输入8个字符
svnlook log %REPOS% -t %TXN% | findstr "........" > nul
if %errorlevel% gtr 0 goto :err_action

rem 过滤空格字符
svnlook log %REPOS% -t %TXN% | findstr /ic:"        " > nul
if %errorlevel% gtr 0 goto :success

:err_action
echo 备注信息验证失败。                >&2
echo 提交代码时,必须填写备注信息。    >&2
echo 备注信息不少于8个字符(或4个汉字)。>&2
goto :err_exit


:err_exit
exit 1

:success
exit 0

2.linux下pre-commit.sh

#!/bin/sh

REPOS="$1"
TXN="$2"

SVNLOOK=/usr/local/bin/svnlook
LOGMSG=`$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]" | wc -c`

#要求注释不能少于8个字符,您可自定义
if ["$LOGMSG" -lt 8];
then
  echo -e "\n备注信息验证失败。\n提交代码时,必须填写备注信息。\n备注信息不少于8个字符(或4个汉字)。" 1>&2
  exit 1
fi 

exit 0

XCode7编译Osirix

1、到Github下载源码
https://github.com/pixmeo/osirix

2、用Xcode打开Osirix.xcodeproj,提示要升级配置,升级

3、运行任务Unzip Binaries

4、Osirix目标调整为x86(上面的Binaries都是x86的)

5、编译Osirix,恩,出错了是吧

6、下载openssl库

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install openssl

将/usr/local/opt/openssl/include添加到include路径
将/usr/local/opt/openssl/lib添加到lib路径

7、在Osirix项目中,去除Message依赖

8、还需要调整几个编译错误和几个连接错误,然后就好了
其中有一个错误是有多个jaritab符号,可以找到三个,然后改为不同名或改为static就好了
其余问题都是很简单的问题咯

9、搞定

Java四种引用方式

最近写了个例子,说明了一下强引用、软引用、弱引用、虚引用的区别。

1、NString.java

package com.neohope.reference;

/**
 * Created by Hansen
 */
public class NString {
    private String name;
    private String value;

    public NString(String name, String value)
    {
        this.name = name;
        this.value=value;
    }

    public NString(String name, StringBuilder builder)
    {
        this.name = name;
        this.value=builder.toString();
    }

    public String Name()
    {
        return name;
    }

    public String Value()
    {
        return value;
    }

    @Override
    protected void finalize()
    {
        System.out.println(">> "+Name()+" finalize called");
        try {
            super.finalize();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}

2、TestReferenceA.java

package com.neohope.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

/**
 * Created by Hansen
 * JVM参数:
 * -XX:+PrintGCDetails
 * -Xms6m -Xmx12m
 */
public class TestReferenceA {
    public static void main(String[] args) {
        //申请内存
        Runtime rt=Runtime.getRuntime();
        System.out.println("Total memory is "+rt.totalMemory());
        int MemSize = 1024*1024*1;
        StringBuilder builder = new StringBuilder(MemSize);
        for (int i=0;i<MemSize/8;i++) {
            builder.append("ABCDEFGH");
        }
        System.out.println("Total memory is "+rt.totalMemory());

        //用s00与s01两个大字符串演示强引用与软引用的区别
        NString s00 = new NString("s00",builder);
        NString s01 = new NString("s01",builder);
        //s02与s03演示WeakReference的两种用法
        NString s02 = new NString("s02","s03");
        String key03 = new String("k03");
        NString s03 = new NString("s03","s03");
        //s04演示PhantomReference
        NString s04 = new NString("s04","s04");
        System.out.println("Total memory is "+rt.totalMemory());

        //第1类、强引用的对象,也最常用到的类型,内存不足时JVM将抛出异常也不要释放这些内存
        NString strongRef = s00;
        //第2类、只有软引用的数据,内存不足时JVM会回收这些内存
        SoftReference<NString> softRef = new SoftReference<NString>(s01);
        //第3类、只有弱引用的数据,无论内存是否充足JVM会回收这些内存,也就是弱引用不会影响对象的生命周期
        WeakReference<NString> weakRef = new WeakReference<NString>(s02);
        //WeakHashMap很有用,当key022为null时,s022也就会被GC咯
        WeakHashMap weakHashMap = new WeakHashMap();
        weakHashMap.put(key03,s03);
        //第4类、只有虚引用的数据,一开始refQueue为空,被GC才会有值
        ReferenceQueue refQueue = new ReferenceQueue<String>();
        PhantomReference<NString> phantomRef = new PhantomReference<NString>(s04, refQueue);

        //有强引用时,输出初始化情况
        System.out.println("With strong ref strongRef is " + (strongRef==null?"null":"not null"));
        System.out.println("With strong ref softRef is " + (softRef.get()==null?"null":"not null"));
        System.out.println("With strong ref weakRef is " + (weakRef.get()==null?"null":"not null"));
        System.out.println("With strong ref weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //这里为null,当对象被GC时,会得到虚引用对象
        System.out.println("With strong ref refQueue has " + refQueue.poll());
        System.out.println();

        //去掉初始的强引用
        s00 = null;
        s01 = null;
        s02 = null;
        s03 = null;
        s04 = null;

        //多数情况下,没有来得及GC
        System.out.println("Before gc strongRef is " + (strongRef==null?"null":"not null"));
        System.out.println("Before gc softRef is " + (softRef.get()==null?"null":"not null"));
        System.out.println("Before gc weakRef is " + (weakRef.get()==null?"null":"not null"));
        System.out.println("Before gc weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //null,当对象被GC时,会得到虚引用对象
        System.out.println("Before gc refQueue has " + refQueue.poll());
        System.out.println();

        //强制GC
        System.gc();
        System.out.println("After first gc strongRef is " + (strongRef==null?"null":"not null"));
        System.out.println("After first gc softRef is " + (softRef.get()==null?"null":"not null"));
        //null,weakRef已经被释放了
        System.out.println("After first gc weakRef is " + (weakRef.get()==null?"null":"not null"));
        System.out.println("After first gc weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //与运行环境及GC方法有关,会出现一次有值的情况,然后一直为null
        System.out.println("After first gc refQueue has " + refQueue.poll());
        System.out.println();

        //将key03设为null,强制GC
        key03 = null;
        System.gc();
        System.out.println("After second gc strongRef is " + (strongRef==null?"null":"not null"));
        System.out.println("After second gc softRef is " + (softRef.get()==null?"null":"not null"));
        //null
        System.out.println("After second gc weakRef is " + (weakRef.get()==null?"null":"not null"));
        //empty,由于key被设为空,则会释放掉弱引用对象了
        System.out.println("After second gc weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //与运行环境及GC方法有关,会出现一次有值的情况,然后一直为null
        System.out.println("After second gc refQueue has " + refQueue.poll());
        System.out.println();

        //Finalization
        System.runFinalization();
        System.out.println("After Finalization strongRef is " + (strongRef==null?"null":"not null"));
        System.out.println("After Finalization softRef is " + (softRef.get()==null?"null":"not null"));
        //null
        System.out.println("After Finalization weakRef is " + (weakRef.get()==null?"null":"not null"));
        //empty
        System.out.println("After Finalization weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //与运行环境及GC方法有关,会出现一次有值的情况,然后一直为null
        System.out.println("After Finalization refQueue has " + refQueue.poll());
        System.out.println();

        //申请内存,造成内存不足
        System.out.println("Total memory is "+rt.totalMemory());
        StringBuilder builder2 = new StringBuilder(MemSize);
        for (int i=0;i<MemSize/8;i++) {
            builder2.append("ABCDEFGH");
        }
        NString tmp0 = new NString("tmp0", builder2);
        System.out.println("Total memory is "+rt.totalMemory());

        System.out.println("When mem is low strongRef is " + (strongRef==null?"null":"not null"));
        //null,内存不足时软引用会被释放
        System.out.println("When mem is low softRef is " + (softRef.get()==null?"null":"not null"));
        //null
        System.out.println("When mem is low weakRef is " + (weakRef.get()==null?"null":"not null"));
        //empty
        System.out.println("When mem is low weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //与运行环境及GC方法有关,会出现一次有值的情况,然后一直为null
        System.out.println("When mem is low refQueue has " + refQueue.poll());
        System.out.println();

        //再次申请内存,JMV会内存爆掉
        NString tmp1 = null;
        try
        {
            tmp1 = new NString("tmp1",builder2);
        }
        catch(OutOfMemoryError ex)
        {
            System.out.println("Not enough memory");
        }

        //null
        System.out.println("tmp1 is " + (tmp1==null?"null":"not null"));
        //就算是抛出OutOfMemoryError,仍然不会释放
        System.out.println("When not enough memory strongRef is " + (strongRef==null?"null":"not null"));
        //null
        System.out.println("When not enough memory softRef is " + (softRef.get()==null?"null":"not null"));
        //null
        System.out.println("When not enough memory weakRef is " + (weakRef.get()==null?"null":"not null"));
        //empty
        System.out.println("When not enough memory weakHashMap is " + (weakHashMap.isEmpty() ?"empty":"not empty"));
        //null
        System.out.println("When not enough memory refQueue has " + refQueue.poll());
        System.out.println();
    }
}

3、输出

Total memory is 6094848
Total memory is 6094848
Total memory is 11390976
With strong ref strongRef is not null
With strong ref softRef is not null
With strong ref weakRef is not null
With strong ref weakHashMap is not empty
With strong ref refQueue has null

Before gc strongRef is not null
Before gc softRef is not null
Before gc weakRef is not null
Before gc weakHashMap is not empty
Before gc refQueue has null

After first gc strongRef is not null
After first gc softRef is not null
After first gc weakRef is null
After first gc weakHashMap is not empty
>> s04 finalize called
After first gc refQueue has null
>> s02 finalize called

After second gc strongRef is not null
After second gc softRef is not null
After second gc weakRef is null
After second gc weakHashMap is not empty
After second gc refQueue has java.lang.ref.PhantomReference@15d63da

After Finalization strongRef is not null
After Finalization softRef is not null
After Finalization weakRef is null
After Finalization weakHashMap is not empty
After Finalization refQueue has null

Total memory is 14221312
Total memory is 14221312
When mem is low strongRef is not null
When mem is low softRef is not null
When mem is low weakRef is null
When mem is low weakHashMap is not empty
When mem is low refQueue has null

>> s01 finalize called
Not enough memory
tmp1 is null
When not enough memory strongRef is not null
When not enough memory softRef is null
When not enough memory weakRef is null
When not enough memory weakHashMap is empty
When not enough memory refQueue has null