cosmos |
|
|
35 gaiacli tx send cosmos1dexfnjr9vp27zc0davqwvj4dkka7apmuv2890a 1uatom --from cosmos10hqcl5jkfda2yderf2fxh43py59ujq0stvj0ee --memo qqq --node=tcp://wallet-atom-daemon-01:26657 --chain-id=cosmoshub-2
36 gaiacli tx send cosmos1dexfnjr9vp27zc0davqwvj4dkka7apmuv2890a 1uatom --from cosmos10hqcl5jkfda2yderf2fxh43py59ujq0stvj0ee --memo qqq --node=tcp://wallet-atom-daemon-01:26657 --chain-id=cosmoshub-2 --gas auto --gas-adjustment 1
37 gaiacli tx send cosmos1dexfnjr9vp27zc0davqwvj4dkka7apmuv2890a 1uatom --from cosmos10hqcl5jkfda2yderf2fxh43py59ujq0stvj0ee --memo qqq --node=tcp://wallet-atom-daemon-01:26657 --chain-id=cosmoshub-2 --gas auto --gas-adjustment 1 --fees 10uatom
38 gaiacli tx send cosmos1dexfnjr9vp27zc0davqwvj4dkka7apmuv2890a 1uatom --from cosmos10hqcl5jkfda2yderf2fxh43py59ujq0stvj0ee --memo qqq --node=tcp://wallet-atom-daemon-01:26657 --chain-id=cosmoshub-2 --fees 750uatom
39 gaiacli tx send cosmos1dexfnjr9vp27zc0davqwvj4dkka7apmuv2890a 1uatom --from cosmos10hqcl5jkfda2yderf2fxh43py59ujq0stvj0ee --memo qqq --node=tcp://wallet-atom-daemon-01:26657 --chain-id=cosmoshub-2 --fees 5000uatom
|
trade |
|
|
<?php
/**
* Created by PhpStorm.
* User: liuxh
* Date: 2018/4/6
* Time: 14:38
*/
namespace Money\Game;
use Exception;
use KuCoin\SDK\Exceptions\BusinessException;
use KuCoin\SDK\Exceptions\HttpException;
use KuCoin\SDK\Exceptions\InvalidApiUriException;
use Money\Exchange\Exchange;
use Money\Exchange\KucoinExchange;
class KcGame3
{
public $exchange;
public function __construct(KucoinExchange $exchange)
{
$this->exchange = $exchange;
}
public function run($trade)
{
$feeArray = [
'BTC-USDT' =>
[
"amount" => '0.01',
"number"=>3,
'buyadd' => 0.1,
'waitn' => 1200,
'maxwin' => 4,
'maxlose' => 20,
'fee'=>'0.000125',
'symbol'=>2
],
'ETH-BTC' =>
[
"amount" => '0.1',
'buyadd' => '0.0000001',
'waitn' => 1200,
'maxwin' => 0.0002,
'maxlose' => 0.01,
'fee'=>'0.000125',
'symbol'=>8
]
];
$current_trade_pair = $feeArray[$trade];
if(!isset($current_trade_pair)){
var_dump('not exist:'.$current_trade_pair);
return;
}
$symbol= $current_trade_pair['symbol'];
$first_trade_amount = $current_trade_pair['amount'];
$first_trade_number = $current_trade_pair['number'];
$maxwin = $current_trade_pair['maxwin'];
$buyAdd = $current_trade_pair['buyadd'];
$numberSymbol = 8;
$minSymbol = 6;
$buyId = null;
$buyPrice =null;
$statusArray =[
'waitbuy'=>$first_trade_number,
'buying'=>0,
'waitsell'=>[],
'selling'=>0,
'buyId'=>[],
'sellId'=>[],
];
while(true) {
// var_dump($statusArray);
$tradeDepthInfo = $this->exchange->getDepth($trade);
if (isset($tradeDepthInfo['asks']) && isset($tradeDepthInfo['bids']) && is_array($tradeDepthInfo['asks']) && is_array($tradeDepthInfo['bids'])) {
$bidmax = $tradeDepthInfo['bids'][0][0];
$bid2 = $tradeDepthInfo['bids'][1][0];
$askmin = $tradeDepthInfo['asks'][0][0];
$ask2 = $tradeDepthInfo['asks'][1][0];
if (empty($statusArray['buyId'])) {
if ($statusArray['waitbuy'] != 0) {
$statusArray['waitbuy'] = $statusArray['waitbuy'] - 1;
$statusArray['buying'] = $first_trade_amount;
if (bccomp($statusArray['buying'], 0, $numberSymbol) == 1) {
$orderArray = [
'amount' => $statusArray['buying'],
'price' => bcadd($bidmax, $buyAdd, $symbol),
'tradeType' => 'buy'
];
$resultArray = $this->exchange->addOrder($trade, $orderArray);
$statusArray['buyId'][$resultArray['orderId']] = $resultArray['orderId'];
}
}
}else {
$buyId = array_keys($statusArray['buyId'])[0];
$orderInfo = $this->exchange->getOrder($trade, ['id' => $buyId]);
if (!$orderInfo['isActive']) {
unset($statusArray['buyId'][$buyId]);
if (!$orderInfo['cancelExist']) {
$statusArray['waitsell'][] = bcadd($orderInfo['price'],$maxwin,$symbol);
}
} else {
if (bccomp($orderInfo['price'], $bidmax, $symbol) != 0) {
try {
$this->exchange->cancelOrder($trade, ['id' => $buyId]);
unset($statusArray['buyId'][$buyId]);
$orderInfo = $this->exchange->getOrder($trade, ['id' => $buyId]);
$buying = bcsub($orderInfo['size'],$orderInfo['dealSize'],$numberSymbol);
if(bccomp($buying,0,$minSymbol)==1){
$orderArray = [
'amount' => $buying,
'price' => $bidmax,
'tradeType' => 'buy'
];
$resultArray = $this->exchange->addOrder($trade, $orderArray);
$statusArray['buyId'][$resultArray['orderId']] =$resultArray['orderId'];
}else{
$statusArray['waitsell'][] = bcadd($orderInfo['price'],$maxwin,$symbol);
}
}catch (Exception $e){
if(isset($statusArray['buyId'][$buyId])){
unset($statusArray['buyId'][$buyId]);
}
$orderInfo = $this->exchange->getOrder($trade, ['id' => $buyId]);
if (!$orderInfo['isActive']) {
if (!$orderInfo['cancelExist']) {
$statusArray['waitsell'][] = bcadd($orderInfo['price'],$maxwin,$symbol);
}
}
}
}
}
}
if(!empty($statusArray['sellId'])) {
foreach ($statusArray['sellId'] as $sellId){
$sellOrderInfo = $this->exchange->getOrder($trade, ['id' => $sellId]);
if($sellOrderInfo){
if(!$sellOrderInfo['isActive']){
if (!$sellOrderInfo['cancelExist']) {
unset($statusArray['sellId'][$sellId]);
$statusArray['waitbuy'] = $statusArray['waitbuy'] + 1;
}
}
}
}
}
if(!empty($statusArray['waitsell'])) {
foreach ($statusArray['waitsell'] as $key=>$sellPrice){
$orderArray = [
'amount' => $first_trade_amount,
'price' => $sellPrice,
'tradeType' => 'sell'
];
$resultArray = $this->exchange->addOrder($trade, $orderArray);
$statusArray['sellId'][$resultArray['orderId']] =$resultArray['orderId'];
unset($statusArray['waitsell'][$key]);
}
}
}
}
return;
}
}
|
docker-compose |
|
|
version: "3.1"
networks:
ubuntu:
services:
ubuntu:
container_name: container_ubuntu
hostname: container_ubuntu
image: ubuntu:1.0
build:
context: .
ports:
- "8080:80"
environment:
- TZ=Asia/Shanghai
volumes:
- ./data_ubuntu:/data
networks:
- ubuntu
stdin_open: true
tty: true
logging:
driver: "json-file"
options:
labels: "container_ubuntu"
max-size: "30m"
max-file: "50"
FROM ubuntu:18.04
LABEL maintainer <290979182@qq.com>
ENV VERSION 1.0
RUN cd /root \
&& apt-get update && apt-get install -y apt-utils net-tools sysstat locales git curl wget tar unzip screen subversion iputils-ping vim
RUN apt-get install -y fish gcc g++ golang nodejs python-pip php openjdk-8-jdk openjdk-8-jre maven
RUN apt-get install -y nginx mysql-server mysql-client redis mongodb
#RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
EXPOSE 80
|
git 同步远程新分支 |
|
|
git checkout -b v1 upstream/v1
git push origin v1
|
supervisord |
|
|
[program:server]
command=/root/bin/server
directory=/root/bin/
numprocs=1
autostart=true
autorestart=true
startsecs=10
startretries=3
|
vimrc |
|
|
set tabstop=4
set nocompatible
set number
set autoindent
set smartindent
set ruler
set shiftwidth=4
set cindent
|
autocompile |
|
|
set version=0
if "%~1"=="1" set version=1
@echo Setting environment for using Microsoft Visual Studio 2010 x86 tools.
@call :GetVSCommonToolsDir
@if "%VS110COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR
@call "%VS110COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit
@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR
@if "%FrameworkDir32%"=="" goto error_no_FrameworkDIR32
@if "%FrameworkVersion32%"=="" goto error_no_FrameworkVer32
@if "%Framework35Version%"=="" goto error_no_Framework35Version
@set FrameworkDir=%FrameworkDir32%
@set FrameworkVersion=%FrameworkVersion32%
@if not "%WindowsSdkDir%" == "" (
@set "PATH=%WindowsSdkDir%bin\NETFX 4.0 Tools;%WindowsSdkDir%bin;%PATH%"
@set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%"
@set "LIB=%WindowsSdkDir%lib;%LIB%"
)
@rem
@rem Root of Visual Studio IDE installed files.
@rem
@set DevEnvDir=%VSINSTALLDIR%Common7\IDE\
@rem PATH
@rem ----
@if exist "%VSINSTALLDIR%Team Tools\Performance Tools" (
@set "PATH=%VSINSTALLDIR%Team Tools\Performance Tools;%PATH%"
)
@if exist "%ProgramFiles%\HTML Help Workshop" set PATH=%ProgramFiles%\HTML Help Workshop;%PATH%
@if exist "%ProgramFiles(x86)%\HTML Help Workshop" set PATH=%ProgramFiles(x86)%\HTML Help Workshop;%PATH%
@if exist "%VCINSTALLDIR%VCPackages" set PATH=%VCINSTALLDIR%VCPackages;%PATH%
@set PATH=%FrameworkDir%%Framework35Version%;%PATH%
@set PATH=%FrameworkDir%%FrameworkVersion%;%PATH%
@set PATH=%VSINSTALLDIR%Common7\Tools;%PATH%
@if exist "%VCINSTALLDIR%BIN" set PATH=%VCINSTALLDIR%BIN;%PATH%
@set PATH=%DevEnvDir%;%PATH%
@if exist "%VSINSTALLDIR%VSTSDB\Deploy" (
@set "PATH=%VSINSTALLDIR%VSTSDB\Deploy;%PATH%"
)
@if not "%FSHARPINSTALLDIR%" == "" (
@set "PATH=%FSHARPINSTALLDIR%;%PATH%"
)
@rem INCLUDE
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\INCLUDE" set INCLUDE=%VCINSTALLDIR%ATLMFC\INCLUDE;%INCLUDE%
@if exist "%VCINSTALLDIR%INCLUDE" set INCLUDE=%VCINSTALLDIR%INCLUDE;%INCLUDE%
@rem LIB
@rem ---
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIB=%VCINSTALLDIR%ATLMFC\LIB;%LIB%
@if exist "%VCINSTALLDIR%LIB" set LIB=%VCINSTALLDIR%LIB;%LIB%
@rem LIBPATH
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIBPATH=%VCINSTALLDIR%ATLMFC\LIB;%LIBPATH%
@if exist "%VCINSTALLDIR%LIB" set LIBPATH=%VCINSTALLDIR%LIB;%LIBPATH%
@set LIBPATH=%FrameworkDir%%Framework35Version%;%LIBPATH%
@set LIBPATH=%FrameworkDir%%FrameworkVersion%;%LIBPATH%
@goto end
@REM -----------------------------------------------------------------------
:GetVSCommonToolsDir
@set VS110COMNTOOLS=
@call :GetVSCommonToolsDirHelper32 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper32 HKCU > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKCU > nul 2>&1
@exit /B 0
:GetVSCommonToolsDirHelper32
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "11.0"') DO (
@if "%%i"=="11.0" (
@SET "VS110COMNTOOLS=%%k"
)
)
@if "%VS110COMNTOOLS%"=="" exit /B 1
@SET "VS110COMNTOOLS=%VS110COMNTOOLS%Common7\Tools\"
@exit /B 0
:GetVSCommonToolsDirHelper64
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" /v "11.0"') DO (
@if "%%i"=="11.0" (
@SET "VS110COMNTOOLS=%%k"
)
)
@if "%VS110COMNTOOLS%"=="" exit /B 1
@SET "VS110COMNTOOLS=%VS110COMNTOOLS%Common7\Tools\"
@exit /B 0
@REM -----------------------------------------------------------------------
:error_no_VS110COMNTOOLSDIR
@echo ERROR: Cannot determine the location of the VS Common Tools folder.
@goto end
:error_no_VSINSTALLDIR
@echo ERROR: Cannot determine the location of the VS installation.
@goto end
:error_no_FrameworkDIR32
@echo ERROR: Cannot determine the location of the .NET Framework 32bit installation.
@goto end
:error_no_FrameworkVer32
@echo ERROR: Cannot determine the version of the .NET Framework 32bit installation.
@goto end
:error_no_Framework35Version
@echo ERROR: Cannot determine the .NET Framework 3.5 version.
@goto end
:end
devenv /rebuild Release ./GamePBufLib/GamePBufLib.sln
devenv /rebuild Release ./GamePBufLib/SerializerGen.sln
copy .\GamePBufLib\SerializerGen\bin\Release\SerializerGen.exe .\SerializerGen.exe
copy .\GamePBufLib\SerializerGen\bin\Release\GamePBufLib.dll .\GamePBufLib.dll
.\SerializerGen.exe
copy .\GamePBufLib.dll ..\..\..\Misc\ProtocolBuff\
copy .\GamePBSerializer.dll ..\..\..\Misc\ProtocolBuff\
if %version% == 1 goto end1
pause
:end1
|
处理PB文件 |
|
|
set version=0
if "%~1"=="1" set version=1
md C#
md C++
md Go
protoc.exe --cpp_out=. .\message.proto
protoc.exe --go_out=. .\message.proto
protogen.exe -i:message.proto -o:message.cs
move .\*.h .\C++
move .\*.cc .\C++
move .\*.cs .\C#
move .\*.go .\Go
set rootdir=..\..\..\Code\Server_yao\
xcopy .\C++\*.h %rootdir%Common\Protocol\Include\ /Y
xcopy .\C++\*.cc %rootdir%Common\Protocol\Src\ /Y
autocompile.bat %version%
if %version% == 1 goto end1
pause
:end1
|
test go kcp |
|
|
package main
import (
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/xtaci/kcp-go"
"server/msg/clientmsg"
"math/rand"
"net"
"github.com/golang/protobuf/proto"
)
const (
REMOTR_ADDR = "127.0.0.1:9999"
)
func SendAndRecv(conn *net.Conn, msgid clientmsg.MessageType, msgdata interface{}) (error, clientmsg.MessageType, []byte) {
//Send
data, err := proto.Marshal(msgdata.(proto.Message))
if err != nil {
return err, 0, nil
}
reqbuf := make([]byte, 4+len(data))
binary.BigEndian.PutUint16(reqbuf[0:], uint16(len(data)+2))
binary.BigEndian.PutUint16(reqbuf[2:], uint16(msgid))
copy(reqbuf[4:], data)
(*conn).Write(reqbuf)
//Recv
headdata := make([]byte, 2)
(*conn).Read(headdata[0:])
msglen := binary.BigEndian.Uint16(headdata[0:])
bodydata := make([]byte, msglen)
bodylen, _ := (*conn).Read(bodydata[0:])
if msglen == 0 || bodylen == 0 {
return errors.New("empty"), 0, nil
}
msgid = clientmsg.MessageType(binary.BigEndian.Uint16(bodydata[0:]))
return nil, msgid, bodydata[2:bodylen]
}
func main() {
// kcp
conn, err := kcp.Dial(REMOTR_ADDR)
if err != nil {
fmt.Println("kcp.Dial error: ", err)
return
}
fmt.Println("connect success")
rand.Seed(time.Now().UnixNano())
reqMsg := &clientmsg.Ping{
ID: proto.Uint32(uint32(rand.Intn(10000))),
}
err, msgid, msgdata := SendAndRecv(&conn, clientmsg.MessageType_MT_PING, reqMsg)
if err != nil {
fmt.Println(err)
return
}
rspMsg := &clientmsg.Pong{}
proto.Unmarshal(msgdata, rspMsg)
fmt.Println("pong ", msgid, rspMsg.GetID())
conn.Close()
}
|
shell 检查参数 |
|
|
#!/bin/bash
function CheckParam()
{
if [[ $# -ne 6 && $# -ne 5 ]];then
echo "Usage: `basename $0` [srcUsername] [srcPassword] [srcGSID] [dstUsername] [dstPassword] [dstGSID]" >&2
#echo " `basename $0` [srcUsername] [srcPassword] [srcGSID] saveto [fileName]" >&2
#echo " `basename $0` [dstUsername] [dstPassword] [dstGSID] loadfrom [fileName]" >&2
exit;
fi
return $#
}
paramCount=$(CheckParam $*)
echo $paramCount
cat /proc/sys/kernel/random/uuid
|
代理获取网页 |
|
|
var http = require('http');
var httpProxy = require('http-proxy');
var url = require('url');
var zlib = require('zlib');
var fs = require('fs');
var baseDir = 'temp';
function HashMap()
{
var size = 0;
var entry = new Object();
this.put = function (key , value)
{
if(!this.containsKey(key))
{
size ++ ;
}
entry[key] = value;
}
this.get = function (key)
{
return this.containsKey(key) ? entry[key] : null;
}
this.remove = function ( key )
{
if( this.containsKey(key) && ( delete entry[key] ) )
{
size --;
}
}
this.containsKey = function ( key )
{
return (key in entry);
}
this.containsValue = function ( value )
{
for(var prop in entry)
{
if(entry[prop] == value)
{
return true;
}
}
return false;
}
this.values = function ()
{
var values = new Array();
for(var prop in entry)
{
values.push(entry[prop]);
}
return values;
}
this.keys = function ()
{
var keys = new Array();
for(var prop in entry)
{
keys.push(prop);
}
return keys;
}
this.size = function ()
{
return size;
}
this.clear = function ()
{
size = 0;
entry = new Object();
}
}
var urlmap = new HashMap();
var urlfetching = '';
httpServer = http.createServer(function(req, res)
{
if(req.url && req.url.indexOf('fetchyou') > 0 && req.url.indexOf('fetchyou') == req.url.length - 'fetchyou'.length)
{
urlmap.clear();
urlmap.put(req.url, "1");
urlfetching = req.url;
console.log(new Date());
}
var chunks = [];
if(req.url == urlfetching || urlmap.containsKey(req.headers['referer'])){
urlmap.put(req.url, "1");
res.on('pipe', function(readStream)
{
readStream.on('data', function(chunk)
{
chunks.push(chunk);
});
readStream.on('end', function()
{
var headers = readStream.headers || [];
var buffer = Buffer.concat(chunks);
var encoding = headers['content-encoding'];
var contenttype = headers['content-type'];
if (encoding == 'gzip')
{
zlib.gunzip(buffer, function(err, decoded)
{
savafile(req.url,decoded,contenttype);
});
}
else if (encoding == 'deflate')
{
zlib.inflate(buffer, function(err, decoded)
{
savafile(req.url,decoded,contenttype);
});
}
else
{
savafile(req.url,buffer,contenttype);
}
});
});
}
goProxy(req,res);
}).listen(8080);
function goProxy(req,res)
{
var proxy = httpProxy.createProxyServer({});
var urlObj = url.parse(req.url);
urlObj.host = urlObj.hostname;
urlObj.port = urlObj.port;
var proxyOptions = {
target: {
host: urlObj.host,
port: urlObj.port
}
};
proxy.web(req, res, proxyOptions, function(e)
{
});
}
function savafile(path,buffer,contenttype)
{
if(!contenttype || !buffer || !buffer.length)return;
console.log("save " + path);
var urlObj = url.parse(path);
if(urlObj.pathname.charAt(urlObj.pathname.length-1) == '/')
{
urlObj.pathname += 'index.html';
}
var dirs = urlObj.pathname.split('/');
if(dirs.length >=20 ) return;
var dirstr = baseDir;
if(!fs.existsSync(dirstr))
{
fs.mkdirSync(dirstr,0777);
}
for(var i = 1,len = dirs.length;i < len-1;i++)
{
dirstr += '/'+dirs[i];
if(!fs.existsSync(dirstr))
{
fs.mkdirSync(dirstr,0777);
}
}
var filename = urlObj.pathname.split('/').join('/');
fs.writeFile(baseDir+filename,buffer,function()
{
fs.chmod(baseDir+filename,0777);
//console.log("fetch end " + path);
});
}
|
erlang工具 |
|
|
后台运行程序
erl -detached -pa ebin -eval "application:start(tcp_server)"
|
合并js文件 |
|
|
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([0-9]+)/([a-z]=.*) index.php?$2 [L,NE]
RewriteRule ^([a-z]=.*) index.php?$1 [L,NE]
</IfModule>
index.php
<?php
header('Content-Type:application/x-javascript');
header('Cache-Control:max-age=1800');
date_default_timezone_set('UTC');
$time = date('D, d M Y H:i:s', time() + 1800) . ' GMT';
header("Expires: $time");
define("BD","/usr/local/openresty/nginx/html/js/");
$file = $_GET['f'];
$loadedfiles = null;
$filemap = array();
if(strpos($file,'|') !== false)
{
$file = explode('|',$file);
$loadedfiles = $file[1];
$file = $file[0];
$loadedfiles = explode(',',$loadedfiles);
for($i = 0;$i < count($loadedfiles);$i++)
{
$filemap[BD.$loadedfiles[$i]] = true;
}
}
if(strpos(realpath(BD.$file),realpath(BD)) === false)
{
echo 'you can not read parent directory.';
exit;
}
$buf = '';
$haserror = false;
function fetchfile($path)
{
global $filemap;
if(!file_exists($path))
{
echo 'file '.$path.' is not exist';
global $haserror;
$haserror = true;
return;
}
if(isset($filemap[$path]))
{
return;
}
$filemap[$path] = true;
$matches = array();
$filestr = file_get_contents($path);
global $buf;
if($filestr)
{
$buf .= $filestr;
}
else
{
return;
}
preg_match_all("/require\([^\(\)]*\)/",file_get_contents($path),$matches);
for($i = 0;$i < count($matches[0]);$i++)
{
$p = '';
if(strpos($matches[0][$i],"'") !== false)
{
$tp = explode("'",$matches[0][$i]);
$p = BD.$tp[1];
}
else if(strpos($matches[0][$i],'"') !== false)
{
$tp = explode('"',$matches[0][$i]);
$p = BD.$tp[1];
}
if($p !== '')
{
if(strpos($p,'.js') !== false)
{
fetchfile($p);
}
else
{
fetchfile($p.'.js');
}
}
}
}
function ob_gzip($content)
{
if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip") && $content != '')
{
extension_loaded("zlib");
$content = gzencode($content);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: ".strlen($content));
}
return $content;
}
fetchfile(BD.$file);
if($haserror == false)
{
$buf = ob_gzip($buf);
echo $buf;
}
?>
|
跨站脚本攻击 |
|
|
http://115.28.18.101/get.php?a=HelloWorld%27%22%3E%3Ciframe%20onload%3Dalert%28%29%3E
|
csrftoken |
|
|
public static int getGTK(String skey){
int iHash = 9999;
char[] skeyChars = skey.toCharArray() ;
for (int i = 0; i <skeyChars.length ; i++) {
iHash += (iHash<<5) + (int)(skeyChars[i]) ;
}
return iHash&0x7fffffff;
}
清理共享内存
ipcs |awk '{if($5==0 || $6==0) printf "ipcrm shm %d\n",$2}' |sh
|
wget使用证书 |
|
|
wget --ca-certificate=myserver.crt https://www.aaa.com
|
gdb corefile |
|
|
gdb -c core.20691_SwitchSvr /usr/local/app/taf/tafnode/data/mgame.SwitchSvr/bin/SwitchSvr
|
SafeRotate类 |
|
|
#include<iostream>
#include<assert.h>
#include<map>
#include<vector>
using namespace std;
template<typename T>
class ExchangeObj
{
private:
class NullType;
protected:
template<typename U> class RetTraits
{
public:
typedef NullType KeyType;
typedef U RetType;
};
template<typename U> class RetTraits<vector<U> >
{
public:
typedef size_t KeyType;
typedef U RetType;
};
template<typename U, typename V> class RetTraits<map<U, V> >
{
public:
typedef U KeyType;
typedef V RetType;
};
template<typename U, typename V, typename W> class RetTraits<map<U, V, W> >
{
public:
typedef U KeyType;
typedef V RetType;
typedef W CompType;
};
public:
ExchangeObj() : idxInUse(0) {}
~ExchangeObj() {}
T* get(){ return &t[idxInUse]; }
T* getUnusedPtr(){ return &t[!idxInUse]; }
T* operator->()
{
return &t[idxInUse];
}
T& operator()()
{
return t[idxInUse];
}
typename RetTraits<T>::RetType& operator[](const typename RetTraits<T>::KeyType& k)
{
return t[idxInUse][k];
}
void exchange()
{
idxInUse = !idxInUse;
}
private:
T t[2];
volatile int idxInUse;
};
int main()
{
ExchangeObj<map<int, int> > mapTest;
mapTest().insert(pair<int,int>(1,3));
assert(mapTest().at(1) == 3);
//load
mapTest.getUnusedPtr()->insert(pair<int,int>(1,4));
mapTest.exchange();
assert(mapTest().at(1) == 4);
mapTest.exchange();
assert(mapTest().at(1) == 3);
assert(mapTest[1] ==3);
return 0;
}
|
关于 jquery-ui |
|
|
jquery-ui和 jquery-mobile不兼容,且手机浏览器经常加载失败
|
perl代码收录 |
|
|
#!/usr/bin/perl
use DBI;
#use File::Lockfile;
use JSON qw/encode_json decode_json/;
use Redis;
use threads;
use POSIX;
use Data::Dumper;
use strict 'vars';
use constant{
HOST=>"mysql.hostname",
PORT=>3306,
USERNAME=>"username",
PASSWORD=>"password",
DB=>"dbname",
REDIS_SVR=>"redis-host:redis-port",
};
my %datas;
sub get_recent_tasks
{
(my $dbh, my $aid) = @_;
my $recentDay = 5;
my @recentTasks = ();
my $sth = $dbh->prepare("select * from rl_account_task where accountid=$aid and isfinish=true and finishtime>=unix_timestamp(date(date_sub(now(),interval $recentDay day)))");
$sth->execute;
while (my $res_ref = $sth->fetchrow_hashref()) {
push(@recentTasks, $res_ref->{'keypointid'});
}
push(@recentTasks, 0);
return @recentTasks;
}
sub load_lessons_of_grade
{
(my $dbh, my $grade, my $pid) = @_;
if($pid == NULL){
my %result;
my $sth = $dbh->prepare("select * from tb_lesson where grade=$grade");
$sth->execute;
while (my $res_ref = $sth->fetchrow_hashref()) {
my $id = $res_ref->{'id'};
@{%result->{$id}} = load_lessons_of_grade($dbh, $grade, $id);
}
return %result;
}else{
my @result = ();
my $sth = $dbh->prepare("select * from tb_lesson where pid=$pid");
$sth->execute;
while (my $res_ref = $sth->fetchrow_hashref()) {
my $id = $res_ref->{'id'};
my $keypoint = $res_ref->{'keypoint'};
push(@result, load_lessons_of_grade($dbh, $grade, $id));
if(defined $keypoint){
my @tt = decode_json($keypoint);
my $arr = @tt->[0];
for(my $i = 0;$i <= $#$arr;$i++){
push(@result, $arr->[$i]);
}
}
}
return @result;
}
}
sub get_grade_keypoints
{
(my $dbh, my $grade) = @_;
my $lessons = %datas->{$grade};
if($lessons == NULL){
%{%datas->{$grade}} = load_lessons_of_grade($dbh, $grade, NULL);
$lessons = %datas->{$grade};
}
return $lessons;
}
sub get_questions_of_keypoint
{
(my $dbh, my $kid) = @_;
my $sth = $dbh->prepare("select test from tb_keypoint where id=$kid limit 1");
$sth->execute;
while (my $res_ref = $sth->fetchrow_hashref()) {
my $test = $res_ref->{'test'};
if($test eq NULL){
last;
}
if($test eq ""){
last;
}
my @testlist = @{decode_json($test)};
my @questions = ();
foreach(@testlist){
my %qinfo = (
"qid" => $_,
"ok" => 0,
);
push(@questions, \%qinfo);
}
my %task = (
"type"=>"task",
"tid"=>$kid,
"qlist"=>\@questions,
"learntime" => 0,
"least" => 5,
"pass"=>0,
"errornum"=>0,
"status"=>0,
);
return %task;
}
return ();
}
sub gen_task
{
(my $accountid, my $redis) = @_;
my $dsn = "DBI:mysql:database=".DB.";host=".HOST.";port=".PORT;
my $dbh = DBI->connect($dsn, USERNAME, PASSWORD);
my $sql = "select * from tb_account where id=$accountid";
my $sth = $dbh->prepare($sql);
$sth->execute;
while (my $res_ref = $sth->fetchrow_hashref()) {
my $id = $res_ref->{'id'};
my $grade = $res_ref->{'grade'};
my $lessons = get_grade_keypoints($dbh, $grade);
my @excludes = get_recent_tasks($dbh, $accountid);
my %hexcludes = map {$_ => 1} @excludes;
my @tasklist = ();
my $count = 0;
while(my ($lesson, $keypoints) = each %{$lessons}){
foreach my $k (@{$keypoints}){
if(!exists($hexcludes{$k})){
my %task = get_questions_of_keypoint($dbh, $k);
if(%task) {
push(@tasklist, \%task);
$count = $count + 1;
}
if($count > 7){
last;
}
}
}
if($count > 7){
last;
}
}
my %newtasks = (
"tasklist" => \@tasklist,
"finishtime" => 0,
"start" => 0,
"resttime" => 0,
"createtime" => time(),
"changerest" => 3,
);
my $strtask = encode_json(\%newtasks);
#update redis
if($redis == NULL){
$redis = Redis->new(server=>REDIS_SVR) || die("redis connect error");
$redis->set("job$accountid", $strtask);
$redis->quit();
}
#update mysql
my $sth = $dbh->prepare("update tb_account set todaytask=? where id=?");
$sth->bind_param(1, $strtask);
$sth->bind_param(2, $accountid);
$sth->execute();
}
}
sub loop
{
my $r = Redis->new(server=>REDIS_SVR) || die("redis connect error");
while(1){
my @aid = $r->brpop("genTasks", 5);
foreach my $id (@aid)
{
if (isdigit($id) && $id != NULL)
{
gen_task($id, $r);
}
}
}
}
sub main
{
my $accountid = 0;
if ($#ARGV == 0) {
$accountid = $ARGV[0];
gen_task($accountid, NULL);
}else{
my @threads;
for(my $i = 0;$i < 5;$i ++)
{
push @threads, threads->create(\&loop);
}
foreach(@threads){
$_->join();
}
}
}
main;
|
python数据库操作 |
|
|
# encoding: utf-8
#!/usr/bin/python
import MySQLdb
import codecs
import json
db = MySQLdb.connect("127.0.0.1","ciaosuser","ciaospwd","ciaosdb" )
cursor = db.cursor()
applist = ["81","82","83"]
cursor.execute("select appID,appName from HtmlAppLibRcmd_playerNum where appID in ("+",".join(applist)+")")
results = cursor.fetchall()
appmap = []
for row in results:
appid = int(row[0])
appname = row[1]
appmap.append([appid,appname])
filename = "./shipeng.test"
data = json.dumps(appmap,ensure_ascii=False)
data = "var AchievementGameList = " + data
f = codecs.open(filename, 'w', encoding='UTF-8')
f.write(data)
# 关闭数据库连接
db.close()
#!/usr/bin/python
# -*- coding: utf-8 -*-
import httplib,urllib
import json
params=urllib.urlencode({"uin":290979182})
headers = {
"Content-Type":"application/x-www-form-urlencoded",
"Referer" : "http://www.qq.com",
"Cookie" : "uin=qq; skey=qq"
}
print "aa"
conn = httplib.HTTPConnection("host")
conn.request(method = "POST", url = "/uri", body = params, headers = headers)
response = conn.getresponse()
if response.status == 200:
body = response.read()
print body
decoded = json.loads(body)
print decoded
name = decoded['RecentGame']["GameName"]
print name
else:
print "error"
|
公钥私钥 |
|
|
下面是OPENSSL生成密钥对示例:
一,使用RSA算法:
生成私钥:openssl genrsa -out privatekey.key 1024
对应公钥:openssl rsa -in privatekey.key -pubout -out pubkey.key
二,使用DSA算法:
生成DSA参数:openssl dsaparam -out dsa_param.pem 1024
生成私钥:openssl gendsa -out dsa_private_key.pem dsa_param.pem
对应公钥:openssl dsa -in dsa_private_key.pem -pubout -out dsa_public_key.pem
san
# 生成一个RSA密钥
$ openssl genrsa -des3 -out 33iq.key 1024
# 拷贝一个不需要输入密码的密钥文件
$ openssl rsa -in 33iq.key -out 33iq_nopass.key
# 生成一个证书请求
$ openssl req -new -key 33iq.key -out 33iq.csr
# 自己签发证书
$ openssl x509 -req -days 365 -in 33iq.csr -signkey 33iq.key -out 33iq.crt
|
lua代码 |
|
|
local http = require("socket.http")
local ltn12 = require("ltn12")
local respbody = {}
local server = "http://www.ciaos.com/api/host.json?host=sina.com"
local result, respcode, respheaders, respstatus = http.request{
method = "GET",
url = server,
sink = ltn12.sink.table(respbody)
}
print(result)
print(respcode)
for k,v in pairs(respheaders) do
print(k,v)
end
print(respstatus)
print(table.concat(respbody))
|
golang 与 lua部分代码 |
|
|
package main
import (
"log"
"net"
"strconv"
"strings"
)
const (
msg_length = 10240
)
//store request map
var requestMap map[int]*net.TCPConn
func proxy(conn *net.TCPConn) {
defer conn.Close()
for {
var data = make([]byte, msg_length)
_, err := conn.Read(data)
if err != nil {
log.Println("proxy disconnect from " + conn.RemoteAddr().String())
return
}
var commands = strings.Split(string(data), " ")
if len(commands) <= 1 || commands[1] == "" {
log.Println("proxy receive bad commands : " + string(data))
return
}
id, err := strconv.Atoi(commands[0])
if rclient, ok := requestMap[id]; ok {
log.Println("router is online " + strconv.Itoa(id))
rclient.Write([]byte(strings.TrimSpace(commands[1])))
_, err = rclient.Read(data)
if err != nil {
log.Println("router disconnect " + conn.RemoteAddr().String())
rclient.Close()
delete(requestMap, id)
return
}
} else {
log.Println("router is offline " + strconv.Itoa(id))
return
}
conn.Write(data)
return
}
}
//
func TcpMain(ip string, port int, router bool) {
//start tcp server
listen, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(ip), port, ""})
if err != nil {
log.Fatalln("listen port error")
return
}
log.Println("start tcp server " + ip + " " + strconv.Itoa(port))
defer listen.Close()
//listen new request
var id int = 0
for {
conn, err := listen.AcceptTCP()
if err != nil {
log.Println("receive connection failed")
continue
}
if router == true {
if rclient, ok := requestMap[id]; ok {
rclient.Close()
delete(requestMap, id)
}
log.Println("connected from " + strconv.Itoa(id) + " addr " + conn.RemoteAddr().String())
requestMap[id] = conn
} else {
go proxy(conn)
}
}
}
func main() {
requestMap = make(map[int]*net.TCPConn)
go TcpMain("127.0.0.1", 1988, false)
TcpMain("0.0.0.0", 1987, true)
}
lua_package_path "/usr/local/openresty/nginx/conf/lua-resty-http-master/lib/?.lua;;";
init_worker_by_lua '
local function proxy()
while true do
local tcpsocket = ngx.socket.tcp()
tcpsocket:setkeepalive(0)
local ok, err = tcpsocket:connect("0.0.0.0", 1987)
if not ok then
ngx.sleep(10)
else
while true do
local result = ""
local line, err, partial = tcpsocket:receive()
if not line then
ngx.sleep(3)
tcpsocket:close()
break
end
ngx.log(ngx.ERR, line)
local http = require "resty.http"
local httpc = http.new()
httpc:connect("127.0.0.1", 80)
local res, err = httpc:request{
path = line,
}
if not res then
result = "failed to request"
else
local reader = res.body_reader
repeat
local chunk, err = reader(8192)
if err then
break
end
if chunk then
result = result .. chunk
end
until not chunk
local bytes, err = tcpsocket:send(result)
if not bytes then
ngx.sleep(3)
tcpsocket:close()
break
end
end
ngx.sleep(3)
end
end
end
end
local ok, err = ngx.timer.at(0,proxy)
if not ok then
ngx.log(ngx.ERR, "timer error")
end
';
|
dmesg.pl |
|
|
#!/usr/bin/perl -w
#
# dmesg rotate
# monitor some key word at dmesg.conf
use strict;
use Data::Dumper;
my $LOGDIR='/var/log/';
my $dmesg_last='dmesg_last';
my $dmesg_all='dmesg_all';
my $conf="/usr/local/ieod-public/dmesg/dmesg.conf";
my $iplist_run;
my $D;
#10m
if (! -d $LOGDIR or ! -x $LOGDIR) {
print "login as root user please!\n";
exit;
}
chdir ($LOGDIR);
if (-f "$dmesg_all" and filesize ($dmesg_all) > 1024*1024*10) {
print "file size gt 10m, do rotate\n";
}
my $NOW=`date +'%F %T'`;
chomp($NOW);
my $o =`dmesg -c > $dmesg_last`;
#my $o =`dmesg > $dmesg_last`;
if (filesize($dmesg_last) > 0) {
open DALL, ">>$dmesg_all";
print DALL "\n------------------------ CHECK POINT:$NOW ------------------------\n";
my @dmesg_lines = `cat $dmesg_last`;
# print DALL "@dmesg_lines";
print "$#dmesg_lines new messages found!, please see /var/log/dmesg_all\n";
if ( -f $conf) {
open F, $conf;
my @conflines = <F>;
close F;
foreach my $dmesgline (@dmesg_lines) {
print DALL $dmesgline;
foreach my $str (@conflines) {
chomp $str;
my ($keyword, $level, $warnid) = split (/::/,$str);
if ($dmesgline =~ /$keyword/) {
push @{$D->{msg}}, [$keyword, $level, $warnid, $dmesgline];
my $errmsg = "ERROR: $level error found, match ERROR-KEYWORD '$keyword' \n" ;
print DALL $errmsg;
print $errmsg;
}
}
}
} else {
print "no conf file found!";
}
close DALL;
} else {
print "no new dmesg found!, old mesg saved in /var/log/$dmesg_all\n";
}
if ($D->{msg}) {
$D->{LOCALIP}= get_localip();
my $t = time;
#$event_time|$D->{LOCALIP}|WARN:".$errmsg."|RaidMonitor|
foreach my $m (@{$D->{msg}}) {
$m->[3] =~ s/\|/-/g;
send2DB (11, "$t|$D->{LOCALIP}|$m->[3]|dmesg|");
}
}
sub filesize {
return (stat(shift))[7];
}
sub send2DB
{
my ($msg_id, $msg_content) = @_;
print ("SYSTEM /usr/local/ieod-public/cc2.0/agent_client.pl 'msg' $D->{LOCALIP} $msg_id '$msg_content' \n");
system("/usr/local/ieod-public/cc2.0/agent_client.pl 'msg' $D->{LOCALIP} $msg_id '$msg_content' ");
}
sub is_innerip {
my $ip = shift || '';
if ($ip =~ /^172\./ or $ip =~ /^192\.168/ or $ip =~ /^10\./) {
return 0;
}
return -1;
}
sub get_localip {
my $self = shift;
my $localip = undef;
my $iplist_run;
my $eth_name = '';
my @ip_out = `/sbin/ifconfig -a`;
foreach my $line (@ip_out) {
if ($line =~ /^\w/) {
$eth_name = (split /\s+/,$line,2)[0];
} else {
if ($line =~ /inet addr:/) {
my @f = split /[\s:]+/, $line;
$iplist_run->{$eth_name} = [ $f[3],$f[7] ];
} elsif ($line =~ /\s+UP/) {
$iplist_run->{$eth_name}->[3] = 'UP';
}
}
}
if ($iplist_run->{eth1} and
$iplist_run->{eth1}->[3] eq 'UP' and
is_innerip($iplist_run->{eth1}->[0]) == 0) {
$localip = $iplist_run->{eth1}->[0];
return $localip;
}
foreach my $eth (keys %$iplist_run) {
if ($iplist_run->{$eth} and
$iplist_run->{$eth}->[3] eq 'UP' and
is_innerip($iplist_run->{$eth}->[0]) == 0) {
$localip = $iplist_run->{$eth}->[0];
return $localip;
}
}
foreach my $eth (keys %$iplist_run) {
if ($iplist_run->{$eth} and
$iplist_run->{$eth}->[3] eq 'UP') {
$localip = $iplist_run->{$eth}->[0];
return $localip;
}
}
return undef;
}
|
xss工具防范 |
|
|
function AQ_SECAPI_ESCAPE(Url,map){
var tmpArr = new Array;
for(var m=0; m<Url.length; m++){
if(Url.charAt(m) == '&'){
var keyLen = [3,4,5,9];
var matchFlag = 0;
for(var n in keyLen){
var l = keyLen[n];
if(m+l <= Url.length){
var subLow = Url.substr(m,l).toLowerCase();
if(map[subLow]){
tmpArr.push(map[subLow]);
m = m+l-1;
matchFlag = 1;
break;
}
}
}
if(matchFlag == 0){
tmpArr.push(Url.charAt(m));
}
}else{
tmpArr.push(Url.charAt(m));
}
}
return tmpArr.join("");
}
function AQ_SECAPI_CheckXss(){
var map = new Object();
var escapeChars = "'\"<>`script:daex/hml;bs64,";
for(var i=0;i<escapeChars.length;i++){
var cha = escapeChars.charAt(i);
var dec = cha.charCodeAt();
var dec7 = dec;
var hex = dec.toString(16);
for(var j = 0; j<(7-dec.toString().length); j++){
dec7 = "0" + dec7;
}
map["" + dec +";"] = cha;
map["" + dec7] = cha;
map["" + hex] = cha;
}
map["<"] = "<";
map[">"] = ">";
map["""] = "\"";
var Url = location.href;
var Refer = document.referrer;
Url = decodeURIComponent( AQ_SECAPI_ESCAPE(Url, map) );
Refer = decodeURIComponent( AQ_SECAPI_ESCAPE(Refer, map));
var XssPattern = new RegExp("['\"<>`]|script:|data:text/html;base64,");
if(XssPattern.test(Url) || XssPattern.test(Refer)){
var version = '1.5'
, cgi = 'http://zyjc.sec.qq.com/dom'
, img = new Image();
img.src = cgi + "?v="+version+"&u=" + encodeURIComponent(Url)+"&r="+encodeURIComponent(Refer);
Url = Url.replace(/['\"<>`]|script:/gi,'M');
Url = Url.replace(/data:text\/html;base64,/gi,'data:text/plain;base64,');
location.href=encodeURI(Url);
}
}
AQ_SECAPI_CheckXss();
|
js幻灯片 |
|
|
http://bartaz.github.io/impress.js/#/its-in-3d
http://lab.hakim.se/reveal-js/#/
http://www.iteye.com/news/28756
|
JS闭包 |
|
|
for i
a.click(
(function(i)
{
return function()
{
//use i
}
})(i))
var result=[];
function foo(){
var i= 0;
for (;i<3;i=i+1){
result[i]=function(){
alert(i)
}
}
};
foo();
result[0](); // 3
result[1](); // 3
result[2](); // 3
var result=[];
function foo(){
var i= 0;
for (;i<3;i=i+1){
result[i]=(function(j){
return function(){
alert(j);
};
})(i);
}
};
foo();
result[0](); // 0
result[1](); // 1
result[2](); // 2
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var _this = this;
return function(){
return _this.name;
};
}
};
alert(object.getNameFunc()()); // My Object
|
myeclipse插件 |
|
|
svn
Subclipse 1.8.x Update Site - http://subclipse.tigris.org/update_1.8.x
|
java的一些 jce代码 |
|
|
//junit 4
package com.test.tool;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.support.http.util.ByteArrayBuffer;
import com.ciaos.CobraHallProto.*;
import com.qq.taf.jce.JceStruct;
public class HttpJcePostTool {
//develop
private static String d_url = "http://localhost/develop";
//test
private static String t_url = "http://localhost/test";
//production
private static String p_url = "http://localhost/product";
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
@SuppressWarnings("unchecked")
public static <T extends JceStruct> T doHttpRequest(int cmdid, JceStruct tReq, JceStruct tRsp){
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
String request = d_url;
TPackageReq req = new TPackageReq();
req.pkgReqHead = new TPkgReqHead();
req.cmdReq = new TCmdReq();
req.cmdReq.cmdReqHead = new TCmdReqHead();
req.pkgReqHead.protocolVer = 3;
req.pkgReqHead.channel = "1216721173";
req.pkgReqHead.platform = PLATFORM._PF_ANDROID;
req.pkgReqHead.appId = 1L;
req.pkgReqHead.appVer = "20301";
req.pkgReqHead.scrRes = "480_854";
req.pkgReqHead.uin = 847422895L;
req.pkgReqHead.uuid = "e21ff1e14e5efae7ffefefefeeeee";
//req.pkgReqHead.coChannel = "1:10000";
// req.cmdReq.cmdReqBody = new byte[1];
// req.pkgReqHead.extHead = new ArrayList<TPkgReqExtHead>();
// TPkgReqExtHead pkgReqExtHead = new TPkgReqExtHead();
// req.pkgReqHead.extHead.add(pkgReqExtHead);
req.cmdReq.cmdReqHead.cmdId = (short) cmdid;
// req.cmdReq.cmdReqHead.sign = new byte[0];
// req.cmdReq.cmdReqHead.encData = new byte[1];
req.cmdReq.cmdReqBody = tReq.toByteArray();
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
try{
URL url = null;
try {
url = new URL(request);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Content-Type", ("text/html; charset=utf-8").replaceAll("\\s", ""));
connection.setRequestProperty("Content-Length", String.valueOf(req.toByteArray().length));
os = new BufferedOutputStream(connection.getOutputStream());
os.write(WupTools.encodeWup(req));
os.flush();
if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK)
{
is = connection.getInputStream();
if (is != null) {
long contentLength = connection.getContentLength();
if (contentLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
if (contentLength < 0) {
contentLength = 4096;
}
ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
try {
byte[] tmp = new byte[4096];
int l = 0;
while ((l = is.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
is.close();
}
TPackageRsp rsp = WupTools.decodeWup(TPackageRsp.class, buffer.buffer());
if(tRsp == null){
return null;
}
Class<? extends JceStruct> rspClazz = tRsp.getClass();
return (T) WupTools.decodeWup(rspClazz, rsp.getCmdRsp().getCmdRspBody());
}
}
}catch(Exception ex){
ex.printStackTrace();
return null;
}
finally{
try {
os.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
connection.disconnect();
}
return null;
}
}
package com.ciaos.testcase;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.ciaos.CobraHallProto.*;
import com.test.tool.HttpJcePostTool;
public class SimpleTestCase {
// @BeforeClass
// public static void setUpBeforeClass() {
// System.out.println("Set up before class");
// }
//
// @Before
// public void testStartBefore() throws Exception {
// System.out.println("before start");
// }
@Test
public void testStart() {
TNBodyStartReq req = new TNBodyStartReq();
TNBodyStartRsp rsp = new TNBodyStartRsp();
req.uin = 3;
rsp = HttpJcePostTool.doHttpRequest(NEW_CMDID._NEW_CMDID_START,req,rsp);
assertEquals("three", rsp.getName());
}
// @After
// public void testStartAfter() throws Exception {
// System.out.println("after start");
// }
@Test
public void testGameDetail() {
MBodyGameDetailReq req = new MBodyGameDetailReq();
MBodyGameDetailRsp rsp = new MBodyGameDetailRsp();
req.gameIdList = new ArrayList<Long>();
req.gameIdList.add(9110000000L);
req.platform = PLATFORM._PF_ANDROID;
rsp = HttpJcePostTool.doHttpRequest(NEW_CMDID._NEW_CMDID_GAMEDETAIL,req, rsp);
assertEquals(1,rsp.gameDetails.size());
}
@Ignore
@Test
public void testSlide() {
Assert.fail("todo");
}
@Ignore
@Test
public void testReport() {
Assert.fail("todo");
}
// @AfterClass
// public static void tearDownAfterClass() {
// System.out.println("Tear down After class");
// }
}
package com.ciaos.testsuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.ciaos.testcase.SimpleTestCase;
@RunWith(Suite.class)
@SuiteClasses({
SimpleTestCase.class
})
public class AllTests {
}
package com.test.tool;
import java.nio.ByteBuffer;
import com.qq.taf.jce.JceDecodeException;
import com.qq.taf.jce.JceInputStream;
import com.qq.taf.jce.JceOutputStream;
import com.qq.taf.jce.JceStruct;
import com.qq.taf.jce.OnIllegalArgumentException;
/**
* Created by hugozhong on 13-10-16.
*/
public class WupTools {
private static String lastError = null;
private static final String ENCODE_CODE = "UTF-8";
public static byte[] encodeWup(JceStruct struct) {
if (null == struct)
return null;
JceOutputStream os = new JceOutputStream();
os.setServerEncoding(ENCODE_CODE);
os.setExceptionHandler(new OnIllegalArgumentException() {
@Override
public void onException(IllegalArgumentException e, ByteBuffer bs, int oldLen, int newLen) {
synchronized (WupTools.class) {
lastError = " IllegalArgumentException bs = " + bs + " oldLen = " + oldLen + " newLen = " + newLen;
}
}
});
struct.writeTo(os);
byte[] datas = os.toByteArray();
return datas;
}
public static <T extends JceStruct> T decodeWup(Class<T> clazz, byte[] datas) {
if (clazz != null && null != datas && datas.length > 0) {
try {
T t = clazz.newInstance();
JceInputStream is = new JceInputStream(datas);
is.setServerEncoding(ENCODE_CODE);
t.readFrom(is);
return t;
} catch (IllegalAccessException e) {
// e.print*StackTrace();
} catch (InstantiationException e) {
// e.print*StackTrace();
} catch (JceDecodeException e) {
throw new RuntimeException("decode wup failed(class:" + clazz.getName() + ")", e);
}
}
return null;
}
/**
* @return the lastError
*/
public static String getLastError() {
synchronized (WupTools.class) {
String result = lastError;
lastError = null;
return result != null ? result : " ";
}
}
}
|