Commit 6435f65a by shuai

20180925,首次提交

parents
/.classpath
/.project
.idea
.settings
bin/
lib/
log/
testoutput/
test-output/
环境要求:
1. 安装Java jdk 和 ant到本地环境
运行准备和步骤:
1. 确保工程目录下的resources目录下的tmp.xls 文件不存在。
2. 打开data.xls文件,在Input sheet中的填写测试数据(一行数据就是一次接口调用). 可以把data_all.xls里Testcase Sheet里需要执行的测试用例复制到data.xls的Input里(带表头)。清除data.xls里output sheet里的数据。
保存并关闭data.xls.(必须关闭)
3. 选择测试环境配置: 修改env.properties里的环境值。 可以参照env.prod.properties和env.beta.properties
4. 在工程目录下执行,ant。
配置:
1. 测试数据表说明:data.xls
1)数字输入excel会变成字符型。如果参数为数字型,请输入单引号+数字。例如’10000。
2)OpenId,productId,orderId:
OpenId,productId,orderId需要从之前测试步骤执行结果获取的,填写"code". 代码会使用从之前的测试结果中取得的openid,prouductId,orderId。
3)VerifyCode
a. verifycode需要从之前测试步骤执行结果获取本条用例使用的手机号的verifycode的,填写"code_own"
b. verifycode需要从之前测试步骤执行结果获取非本条用例使用的手机号的verifycode的,填写"code_others"
c. verifycode需要从之前测试步骤执行结果获取本条用例使用的手机号的已过期的verifycode的,填写"code_old"
4)statusCode,errcode,errmsg需要填写期望返回值
5) 对于需要全新客户信息的case,需要把cleanDB字段置为Y。
2. env.properties 文件:
isProduct=Y 表示 生产环境运行,不会连接数据做数据插入和检查。注意,生产环境执行时,如果要测插入商品接口,请在data表的字段busiId和busiName填写实际值,不要使用“code”。
查看结果:
1)测试用例全部执行后,打开data.xls文件, 在output里查看结果。
说明: 在非beta环境运行时,测试case运行结束后,会清除数据库中的测试数据。如需不清除数据,需要comment掉:BestbuyGMAPITest.java里afterClass() function下的
this.cleanCustomerInfo();
this.cleanProductsFromDB();
this.cleanOrdersFromDB();
<project name="auto_test" default="testoutput" basedir=".">
<!-- Define <testng> task -->
<taskdef name="testng" classname="org.testng.TestNGAntTask">
<classpath>
<pathelement location="lib/testng-6.9.12.jar" />
</classpath>
</taskdef>
<property name="testoutputdir" location="testoutput" />
<property name="srcdir" location="src" />
<property name="libdir" location="lib" />
<property name="full-compile" value="true" />
<property name="basedir" value="D:/workspace/auto_test/" />
<path id="classpath.test">
<fileset dir="${libdir}">
<include name="**/*.jar" />
</fileset>
<pathelement location="${testoutputdir}" />
<pathelement location="${srcdir}" />
</path>
<target name="clean">
<delete dir="${basedir}/bin" />
</target>
<target name="compile" depends="clean">
<mkdir dir="${basedir}/bin" />
<javac srcdir="${srcdir}" encoding="UTF-8" destdir="${basedir}/bin" verbose="${full-compile}" classpathref="classpath.test" includeantruntime="off" debug="on" debuglevel="lines,vars,source" />
</target>
<path id="classes">
<fileset dir="${libdir}" includes="*jar"/>
<fileset dir="${libdir}" includes="*zip"/>
<pathelement location="${basedir}/bin/"/>
</path>
<target name="runtest" depends="compile">
<testng outputdir="${testoutputdir}" classpathref="classes" delegateCommandSystemProperties="true">
<xmlfileset dir="${basedir}" includes="testng.xml" />
</testng>
</target>
<target name="testoutput" depends="runtest">
<xslt in="${testoutputdir}/testng-results.xml" style="${testoutputdir}/testng-results.xsl" out="${testoutputdir}/index.html ">
<param name="testNgXslt.outputDir" expression="${basedir}/testoutput/" />
<classpath refid="classpath.test" />
</xslt>
</target>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Failed suite-ys">
<test name="Default test-ys">
<classes>
<class name="com.puhui.test.RenMai_APITest">
<methods>
<include name="f" invocation-numbers="0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 "/>
</methods>
</class>
</classes>
</test>
</suite>
package aoutTestCode;
import java.io.File;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.offcn.TestUnti.Log;
import sun.util.logging.resources.logging;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class MakeCode {
public static void main(String[] args){
MakeCode mc=new MakeCode();
try {
// mc.aoutMakeCode("xml_makecode/MakeCode.xml");
mc.aoutMakeCode("xml_makecode/rgxs-MakeCode.xml");
} catch (Exception e) {
Log.logError("aoutMakeCode_error");
e.printStackTrace();
}
Log.logInfo("aoutMakeCode_ok");
}
public void aoutMakeCode(String path) throws Exception {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("templates"));
Map<String,Object> root = new HashMap<String,Object>();
xmlToftl xml=new xmlToftl(path);
root.put("package_name", xml.getName("package_name"));
root.put("implements_name",xml.getName("implements_name"));
root.put("class_name", xml.getName("class_name"));
root.put("father_class_name", xml.getName("father_class_name"));
root.put("parameters", xml.getNameAndKey("parameters","parameter"));
root.put("initialize_Disable", xml.getBoolean("initialize_Disable"));
root.put("initializes", xml.getNameAndKey("initializes","initialize"));
root.put("handleInput_Disable", xml.getBoolean("handleInput_Disable"));
root.put("handleInput_replaces", xml.getNameAndTypeAndKey("handleInput_replaces","handleInput_replace"));
root.put("handleInputs_Verifications", xml.getNameAndTypeAndKey("handleInputs_Verifications","handleInputs_Verification"));
root.put("SendRequest_Disable", xml.getBoolean("SendRequest_Disable"));
root.put("SendRequest", xml.getName("SendRequest"));
root.put("handleOutput_Disable", xml.getBoolean("handleOutput_Disable"));
root.put("handleOutput_saves", xml.gethandleOutput_save("handleOutput_saves","handleOutput_save","handleOutput"));
root.put("handleOutput_Table", xml.getName("handleOutput_Table"));
root.put("handleOutput_TableKey", xml.getKey("handleOutput_Table"));
Template t1 = cfg.getTemplate("code.ftl");
File directory = new File(".");
String package_name=xml.getName("package_name").replace(".", "\\");
String FilePath = directory.getCanonicalPath() +File.separator+"src"+File.separator+package_name+File.separator;
File Files = new File(FilePath);
File FilesName = new File(FilePath,xml.getName("class_name")+".java");
Log.logInfo("makeFolder:"+(Files.mkdirs()));
Log.logInfo("makeFile:"+(FilesName.createNewFile()));
//显示生成的数据
Writer out = new FileWriter(FilesName);
t1.process(root, out);
out.flush();
out.close();
}
}
package aoutTestCode;
import java.io.File;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ParseXml {
@SuppressWarnings("unused")
private String filePath;
private Document document;
private Element root;
public ParseXml(String filePath) {
super();
this.filePath = filePath;
this.load(filePath);
}
public void load(String filePath) {
File file=new File(filePath);
if(file.exists()){
SAXReader saxReader=new SAXReader();
try {
document=saxReader.read(file);
root = document.getRootElement();
} catch (DocumentException e) {
System.out.println("文件加载异常"+filePath);
}
}else{
System.out.println("文件没找到");
}
}
public Element getElementObject(String elementPath){
return (Element)document.selectSingleNode(elementPath);
}
public String getElementText(String elementPath){
Element element=this.getElementObject(elementPath);
if(element!=null){
return element.getTextTrim();
}else{
return null;
}
}
public List<Map<String,String>> getElementsName_text(String parameters){
Element P=root.element(parameters);
List<Element> Elements = P.elements("parameter");
for (Element element : Elements) {
System.out.print(element.attributeValue("name")+" ");
System.out.println(element.getTextTrim());
}
return null;
}
public static void main(String[] args) {
ParseXml parseXml=new ParseXml("config/config.xml");
String element=parseXml.getElementText("/config/browser");
System.out.println(element);
}
}
package aoutTestCode;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class xmlToftl {
@SuppressWarnings("unused")
private String filePath;
private Document document;
private Element root;
public xmlToftl(String filePath) {
this.filePath = filePath;
this.load(filePath);
}
public void load(String filePath) {
File file=new File(filePath);
if(file.exists()){
SAXReader saxReader=new SAXReader();
try {
document=saxReader.read(file);
root=document.getRootElement();
} catch (DocumentException e) {
System.out.println("文件加载异常"+filePath);
}
}else{
System.out.println("文件没找到");
}
}
public static void main(String[] args) {
xmlToftl x=new xmlToftl("templates/MakeCode.xml");
x.go();
}
public void go(){
//获取包名
String package_name=getName("package_name");
//获取类名
String class_name=getKey("class_name");
//获取接口名
String implements_name=getKey("implements_name");
//获取boolean
boolean b=getBoolean("initialize_Disable");
System.out.println(b);
//获取参数
List<Map<String,String>> listParameters=getNameAndKey("parameters","parameter");
//获取参数
List<Map<String,String>> initializes=getNameAndKey("initializes","initialize");
System.out.println(initializes.toString());
//获取参数
List<List<String>> getN=getNameAndTypeAndKey("handleInput_replaces","handleInput_replace");
System.out.println(getN);
//获取参数
List<List<String>> getN1=getNameAndTypeAndKey("handleInputs_Verifications","handleInputs_Verification");
System.out.println(getN1);
//获取参数
Map<String,List<String>> getn2=gethandleOutput_save("handleOutput_saves","handleOutput_save","handleOutput");
System.out.println(getn2);
}
public String getName(String str){
if(str.equals("package_name")){
return root.attributeValue("name");
}
Element element=root.element(str);
return element.attributeValue("name");
}
public String getKey(String str){
Element ementsValue=root.element(str);
String Value=ementsValue.getTextTrim();
return Value;
}
public boolean getBoolean(String str){
String type=getKey(str);
if("true".equals(type)){
return true;
}
return false;
}
public List<Map<String,String>> getNameAndKey(String parameters,String parameter){
Element Elements=root.element(parameters);
@SuppressWarnings("unchecked")
List<Element> liste = Elements.elements(parameter);
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
for (Element element : liste) {
Map<String,String> root = new HashMap<String,String>();
if(element.attributeValue("value")==null){
root.put(element.attributeValue("name"), element.getTextTrim());
}else{
root.put(element.attributeValue("value"), element.getTextTrim());
}
list.add(root);
}
return list;
}
public List<List<String>> getNameAndTypeAndKey(String parameters,String parameter){
Element Elements=root.element(parameters);
@SuppressWarnings("unchecked")
List<Element> liste = Elements.elements(parameter);
List<List<String>> list = new ArrayList<List<String>>();
for (Element element : liste) {
List<String> root = new ArrayList<String>();
if(element.attributeValue("name")!=null){
root.add(element.attributeValue("name"));
}
if(element.attributeValue("type")!=null){
root.add(element.attributeValue("type"));
}
if(element.attributeValue("value")!=null){
root.add(element.attributeValue("value"));
}
if(!element.getTextTrim().equals("")){
root.add(element.getTextTrim());
}
list.add(root);
}
return list;
}
public Map<String,List<String>> gethandleOutput_save(String parameters,String parameter,String handleOutput){
Element Elements=root.element(parameters);
@SuppressWarnings("unchecked")
List<Element> liste = Elements.elements(parameter);
Map<String,List<String>> map = new HashMap<String,List<String>>();
String mapString="";
for (Element element : liste) {
List<String> root = new ArrayList<String>();
if(element.attributeValue("name")!=null){
mapString=element.attributeValue("name");
}
List<Element> listh = element.elements(handleOutput);
for (Element element2 : listh) {
root.add(element2.getTextTrim());
}
map.put(mapString,root);
}
return map;
}
}
package com.offcn.TestData;
import org.testng.annotations.DataProvider;
import com.offcn.TestUnti.ReadExcels;
public class offcn_api_testData {
@DataProvider(name="renmai")
public static Object[][] dp(){
ReadExcels readExcels = new ReadExcels("DataAll.xls","TestCase");
try {
return readExcels.readExcels_return();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.offcn.TestUnti;
/**
* Created by puhui on 2016/8/1.
*/
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AES256Encryption {
// 解密
private static final BASE64Decoder DECODER = new BASE64Decoder();
// 加密
private static final BASE64Encoder ENCODER = new BASE64Encoder();
private final static byte[] hex = "0123456789ABCDEF".getBytes();
/**
* 密钥算法 java6支持56位密钥,bouncycastle支持64位
* */
public static final String KEY_ALGORITHM = "AES";
public static final byte[] AES_PASSWORD_TEXT = "puhui88888888888".getBytes();
/**
* 加密/解密算法/工作模式/填充方式
*
* JAVA6 支持PKCS5PADDING填充方式 Bouncy castle支持PKCS7Padding填充方式
* */
public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
*
* 生成密钥,java6只支持56位密钥,bouncycastle支持64位密钥
*
* @return byte[] 二进制密钥
* */
public static byte[] initkey() throws Exception{
//实例化密钥生成器
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC");
//初始化密钥生成器,AES要求密钥长度为128位、192位、256位
kg.init(256);
// kg.init(128);
//生成密钥
SecretKey secretKey=kg.generateKey();
//获取二进制密钥编码形式
return secretKey.getEncoded();
// 为了便于测试,这里我把key写死了,如果大家需要自动生成,可用上面注释掉的代码
// return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,
// 0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f,
// 0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09,
// 0x06, 0x07, 0x09, 0x0d };
// return AES_PASSWORD_TEXT.getBytes();
}
/**
* 转换密钥
*
* @param key
* 二进制密钥
* @return Key 密钥
* */
public static Key toKey(byte[] key) throws Exception {
// 实例化DES密钥
// 生成密钥
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
return secretKey;
}
/**
* 加密数据
*
* @param data 待加密数据
* @return String 加密后的数据
* */
public static String encrypt(byte[] data) {
try{
// 还原密钥
Key k = toKey(AES_PASSWORD_TEXT);
/**
* 实例化 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
* Cipher.getInstance(CIPHER_ALGORITHM,"BC")
*/
// Security.addProvider(new
// org.bouncycastle.jce.provider.BouncyCastleProvider());
// Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC");
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);
// 执行操作
byte[] aesData = cipher.doFinal(data);
return ENCODER.encode(aesData);//bass64加密
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* AES解密数据
*
* @param data
* 待解密数据
* @return String 解密后的数据
* */
public static String decrypt(String data) throws Exception {
// 欢迎密钥
Key k = toKey(AES_PASSWORD_TEXT);
byte[] deData = DECODER.decodeBuffer(data);
/**
* 实例化 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
* Cipher.getInstance(CIPHER_ALGORITHM,"BC")
*/
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, k);
// 执行操作
byte[] aa = cipher.doFinal(deData);// 十六进制
return new String(aa);
}
/**
* 将16进制数组转换成字符串
*
* @Description:
* @Title: parseHexStr2Byte
* @user: ningyijie
* @return: String
*/
public static String parseHexStr2Byte(byte[] b) {
byte[] buff = new byte[2 * b.length];
for (int i = 0; i < b.length; i++) {
buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
buff[2 * i + 1] = hex[b[i] & 0x0f];
}
return new String(buff);
}
/**
* @param args
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "a111111";
System.out.println("原文:" + str);
try {
// 加密数据
String data = AES256Encryption.encrypt(str.getBytes());
System.out.println("aes加密后:"+data);
// 解密
String aa = AES256Encryption.decrypt("+RRDgv8Dst9RyN9E0XKPAA=");
System.out.println("aes解密后:" + aa);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.offcn.TestUnti;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密解密工具类
*
* @author yupeng
*/
public class AESUtils {
//private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);
// 参数加密密码
public static final String AES_PASSWORD_TEXT = "puhui888888";
// token加密密码
public static final String AES_PASSWORD_TOKEN = "puhui888888";
public static final String FLAG = "!@#";
/**
* 生成当前时间点的加密token
* Token的格式为uid加上时间
* @param uid
* @return
*/
public static String generateToken(String uid) {
StringBuffer tokenStr = new StringBuffer();
long time = new Date().getTime();
tokenStr.append(uid).append(FLAG).append(time);// 生成token
String encrypTokenStr = encrypt(tokenStr.toString(), AES_PASSWORD_TOKEN); // token加密
return encrypTokenStr;
}
/**
* 通过加密token获取UID
*
* @author xiaobowen
* @param encryptToken
* @return uid
*/
public static String getUID(String encryptToken) {
String token = decrypt(encryptToken, AES_PASSWORD_TOKEN);
return getUIDByToken(token);
}
/**
* 通过加密token获取token时间
*
* @author gaozhenbao
* @param encryptToken
* @return time
*/
public static String getTiime(String encryptToken) {
String token = decrypt(encryptToken, AES_PASSWORD_TOKEN);
return getTimeByToken(token);
}
public static String getUIDByToken(String token) {
if (token == null)
return null;
String[] params = token.split(FLAG);
if (params == null || params.length != 2) {
return null;
} else {
// logger.info("token为{},解析为{}",token,params[0]);
return params[0];
}
}
public static String getTimeByToken(String token) {
if (token == null)
return null;
String[] params = token.split(FLAG);
if (params == null || params.length != 2) {
return null;
} else {
return params[1];
}
}
/**
* 获取解密token
*
* @param decryTokenStr
* @return
*/
public static String analyzeToken(String decryTokenStr) {
return decrypt(decryTokenStr, AES_PASSWORD_TOKEN);
}
/**
* AES加密
*
* @author wangyaowei
* @param userpassword 需要加密的密码
* @return enpassword AES加密后的密码
*/
public static String encrypt(String userpassword){
return encrypt(userpassword, AES_PASSWORD_TOKEN);
}
/**
* AES加密
*
* @author yupeng
* @param content
* 需要加密的内容
* @param password
* 加密密码
* @return
*/
public static String encrypt(String content, String password) {
if (content == null) {
return null;
}
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 提供AES密钥算法的(对称)密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();// 生成一个密钥
// byte[] enCodeFormat = secretKey.getEncoded();//基本编码格式的密钥
// SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
// System.out.println("key:" +
// CommonUtils.parseByte2HexStr(key.getEncoded()));
cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化 加密模式
byte[] result = cipher.doFinal(byteContent);
String encryptResultStr = parseByte2HexStr(result);
return encryptResultStr; // 加密 后的16进制
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* AES解密
*
* @author yupeng
* @param content
* 待解密内容(十六进制)
* @param password
* 解密密钥
* @return
*/
public static String decrypt(String content, String password) {
return decrypt(parseHexStr2Byte(content), password);
}
/**
* AES解密
*
* @author yupeng
* @param content
* 待解密内容
* @param password
* 解密密钥
* @return
*/
public static String decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 提供AES密钥算法的(对称)密钥生成器
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 解密模式
byte[] result = cipher.doFinal(content);// 解密为16进制
String resultStr = new String(result);// 将16进制转化为字符串
return resultStr; // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
package com.offcn.TestUnti;
import com.puhui.aes.AesEncryptionUtil;
import org.apache.commons.lang3.StringUtils;
/**
* 加密和解密
*
* @author wangcj
*/
public class EncryptionUtil {
private static final String prefix = "xy";
private EncryptionUtil() {
}
/**
* 加密
*
* @author wangcj
* @param content
* @return
*/
public static String encrypt(String content) {
String tempContent = content;
if (StringUtils.isBlank(tempContent)) {
return tempContent;
}
if (tempContent.startsWith(prefix)) {
return tempContent;
}
return AesEncryptionUtil.encrypt(tempContent);
}
/**
* 解密
*
* @author wangcj
* @param content
* @return
*/
public static String decrypt(String content) {
String tempContent = content;
if (StringUtils.isBlank(tempContent)) {
return tempContent;
}
if (tempContent.startsWith(prefix)) {
return AesEncryptionUtil.decrypt(tempContent);
}
return tempContent;
}
public static void main(String[] args) {
String s1=EncryptionUtil.encrypt("18230065651");
String s=EncryptionUtil.decrypt("e10adc3949ba59abbe56e057f20f883e");
System.out.println("加密后,卡号是:"+s1);
System.out.println("解密后,卡号是:"+s);
}
}
\ No newline at end of file
package com.offcn.TestUnti;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by puhui on 2017/1/9.
*/
public class GetTaoBaoCookies {
public static List<Map<String, String>> initCookies(FileReader fr) throws IOException {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(fr);
String line = "";
int m = 1;
while ((line = br.readLine()) != null) {
System.err.println("第" + m + "行");
m++;
String[] arrs = line.split("\t");
Map<String, String> map = new HashMap<>();
map.put("path", arrs[2]);
map.put("name", arrs[arrs.length - 2]);
map.put("value", arrs[arrs.length - 1]);
map.put("domain", arrs[0]);
list.add(map);
}
return list;
}
@Test
public void getcookies() throws IOException {
FileReader fr = new FileReader("d:/cookies.txt");
List<Map<String, String>> list = initCookies(fr);
System.out.println();
Map a = new HashMap();
a.put("xx", JSONArray.fromObject(list));
System.out.println(JSONObject.fromObject(a));
}
}
package com.offcn.TestUnti;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class GetVerifyCode {
//获取验证码的前置信息
public static RestAssured getVerifyCode() {
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://106.75.3.8";
ra_VerifyCode.port = 8765;
ra_VerifyCode.basePath = "/puhui-notification-server/api/v1/message/query";
return ra_VerifyCode;
}
//获取验证码并分析出返回
public static String getGetResponse(String phone) {
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://106.75.3.8";
ra_VerifyCode.port = 8765;
ra_VerifyCode.basePath = "/puhui-notification-server/api/v1/message/query";
Response ra_VerifyCode1 = ra_VerifyCode.given().param("mobile", phone).get();
String str2 = ra_VerifyCode1.body().jsonPath().getString("消息内容").split(",")[0]
.split(":")[1].trim().toString();
return str2;
}
}
package com.offcn.TestUnti;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
\ No newline at end of file
package com.offcn.TestUnti;
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println
(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}
System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();
System.out.println();
System.out.println(cert);
System.out.println();
System.out.println
("Added certificate to keystore 'jssecacerts' using alias '"
+ alias + "'");
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}
package com.offcn.TestUnti;
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log {
/**
* @param args
*/
private static Logger logger;
private static String filePath="src/log4f.properties";
private static boolean flag = false;
@SuppressWarnings("static-access")
private static synchronized void getPropertyFile(){
logger=logger.getLogger("TestProject");
PropertyConfigurator.configure(new File(filePath).getAbsolutePath());
flag=true;
}
private static void getFlag(){
if(flag==false){
Log.getPropertyFile();
}
}
public static void logInfo(String message){
Log.getFlag();
logger.info(message);
}
public static void logError(String message){
Log.getFlag();
logger.error(message);
}
public static void logWarn(String message){
Log.getFlag();
logger.warn(message);
}
}
package com.offcn.TestUnti;
/**
* Created by puhui on 2016/8/10.
*/
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具类,
*
* @author luyujian
*/
public class MD5keyUtil {
/**
* 返回加密的密文
*
* @param str
* 要加密的字符串
* @return
*/
public static String getMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) { // NOSONAR
System.out.println(e.getMessage());
} catch (UnsupportedEncodingException e) { // NOSONAR
System.out.println(e.getMessage());
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString().toUpperCase();
}
public static void main(String[] arg) {
System.out.println(getMD5Str("22"));
}
}
package com.offcn.TestUnti;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.json.JSONObject;
public class MapUtil {
public static void main(String[] args) {
HashMap<String, Object> hm=new HashMap<String, Object>();
hm.put("1", "a1");
hm.put("statusCode", "a2");
hm.put("3", "a3");
hm.put("errcode", "a4");
hm.put("5", "a5");
hm.put("errmsg", "a6");
HashMap<String, Object> newhm=Expect(hm);
System.out.println("@AfterClass_data_ext="+JSONObject.fromObject(newhm).toString());
}
//马洪亮
// 生成数组格式的json串
public static String getArrayJson(String para) {
StringBuffer sb = new StringBuffer();
sb.append("[");
if (para.contains(";")) {
for (int i = 0; i < para.split(";").length; i++) {
sb.append("{");
sb.append(para.split(";")[i]);
sb.append("},");
}
sb.deleteCharAt(sb.length() - 1);
}else{
sb.append("{");
sb.append(para);
sb.append("}");
}
sb.append("]");
return sb.toString();
}
//显示整个map
public static String showMap(HashMap<String, Object> data){
Set<Map.Entry<String,Object>> set=data.entrySet();
Iterator<Entry<String, Object>> it=set.iterator();
HashMap<String, Object> newdata=new HashMap<String, Object>();
StringBuffer sb=new StringBuffer();
while(it.hasNext()){
Map.Entry<String,Object> me=it.next();
String key=me.getKey();
Object value=me.getValue();
sb.append(key+":"+value+",");
}
return sb+"";
}
//显示整个map
public static String showMap_String(Map<String, String> data){
Set<Map.Entry<String,String>> set=data.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
HashMap<String, String> newdata=new HashMap<String, String>();
StringBuffer sb=new StringBuffer();
while(it.hasNext()){
Map.Entry<String,String> me=it.next();
String key=me.getKey();
String value=me.getValue();
sb.append(key+":"+value+",");
}
return sb+"";
}
//返回期望结果
public static HashMap<String, Object> Expect(HashMap<String, Object> data){
Set<Map.Entry<String,Object>> set=data.entrySet();
Iterator<Entry<String, Object>> it=set.iterator();
HashMap<String, Object> newdata=new HashMap<String, Object>();
while(it.hasNext()){
Map.Entry<String,Object> me=it.next();
String key=me.getKey();
Object value=me.getValue();
if(key.equals("statusCode") || key.equals("code") || key.equals("msg") || key.equals("custom")){
newdata.put(key, value);
}
}
return newdata;
}
//获得数据中的Parameter,并修改成json模式
public static String getParameter(HashMap<String, Object> data){
String s=MapUtil.getValue("parameter",data);
StringBuffer sb=new StringBuffer();
sb.append("{");
sb.append(s);
sb.append("}");
return sb.toString();
}
// //获取验证码map中不是参数描述的手机号的验证码
// public static String getOthersVerifyCode(String ownPhoneNumber) {
// String verifycode = "";
// Iterator<Entry<String, String>> it = BasicsGM.verifyCode.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry<String, String> entry = it.next();
// if (!entry.getKey().equals(ownPhoneNumber)) {
// verifycode = entry.getValue();
// break;
// }
// }
// return verifycode;
// }
//获取verifyCode-map中指定的key所对应的值
// public static String getOldVerifyCode(String phone) {
// String str="";
// str=BasicsGM.verifyCode.get(phone);
// return str;
// }
//获取map中指定的key所对应的值,返回字符串
public static String getValue(String ownPhoneNumber,HashMap<String, Object> data) {
Object verifycode = null;
Iterator<Entry<String, Object>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
if (entry.getKey().equals(ownPhoneNumber)) {
verifycode = entry.getValue();
// System.out.println(verifycode);
break;
}
}
return verifycode+"";
}
//在parameter中查看,是否有(第二个参数)电话的关键字,有的话返回数字值
public static String getNumber(String parameter,String number){
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split(":");
String str_strcomma=Arrays.toString(str);
// System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(number)){
int start=str_strcomma.indexOf(',');
str_strcomma=str_strcomma.substring(start+1,str_strcomma.length()-1);
for (int i =0;i< str_strcomma.length(); i++) {
if (Character.isDigit(str_strcomma.charAt(i))) {
sb.append(str_strcomma.charAt(i));
}
}
}
}
return sb.toString();
}
//在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getParameter(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split(":");
String str_strcomma=Arrays.toString(str);
// System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start+2,str_strcomma.length()-1));
return sb.toString();
}
}
return sb.toString();
}
//在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getParameter_accurate(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String str=strcomma[k].split(":")[0];
String str_strcomma= MapUtil.killQuotes(str, "\"");//去掉双引号的education
// String String str_strcomma==str;
// System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.equals(Letter)){
try {
sb.append(strcomma[k].split(":")[1]);
} catch (Exception e) {
Log.logInfo("字段没有后半部分");
}
return sb.toString();
}
}
return sb.toString();
}
//去掉字母值的指定符号,参数1字符串,参数2指定符号
public static String killQuotes(String parameter,String Letter){
StringBuffer sb=new StringBuffer();
for(int k=0;k<parameter.length();k++){
if(parameter.charAt(k)!= '"'){
sb.append(parameter.charAt(k));
}
}
return sb.toString();
}
//去掉字母值的指定符号,参数1字符串,参数2指定符号
public static String killQuotes(String parameter,char Letter){
StringBuffer sb=new StringBuffer();
for(int k=0;k<parameter.length();k++){
if(parameter.charAt(k)!= Letter){
sb.append(parameter.charAt(k));
}
}
return sb.toString();
}
//在parameter中,按照第二个参数进行分割,分割成两段,获取后面那段的内容
public static String getParameterList(String parameter,String Letter){
if(parameter==null || parameter.equals("")){
return "";
}
String[] strcomma=parameter.split(Letter);
if(strcomma.length>0 && strcomma[1]!=null){
return strcomma[1].toString();
}
return "";
}
}
package com.offcn.TestUnti;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* 魔蝎验签
* @author puhui
*
*/
public class MoXie {
public static void main(String[] args) {
String s="{\"mobile\":\"13910960649\",\"user_id\":\"d9c3a0add4d545fbb236f25671e189ed-order\",\"task_id\":\"12345\",\"name\":\"姚帅\",\"idcard\":\"11022119811222061X\",\"result\":\"true\",\"message\":\"报告通知\",\"timestamp\":3000}";
System.out.println(MoXie.base64Hmac256(s, "27c7e4bc518c48d095d9caf544771876"));
}
public static String base64Hmac256(String payload, String secret) {
try {
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256Hmac.init(secretKey);
return Base64.encodeBase64String(sha256Hmac.doFinal(payload.getBytes()));
} catch (Exception ignored) {
return "";
}
}
public static String jiaFanXieXian(String str){
str=str.replaceAll("\"", "\\\"");
return str;
}
}
package com.offcn.TestUnti;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.http.ContentType.JSON;
/**
* Created by puhui on 16/9/14.
*/
public class MockServerTestUtil {
static RestAssured ra;
public static RestAssured getLocalRAEnv(){
if (ra == null){
ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(SSLConfig.sslConfig().allowAllHostnames());
ra.baseURI = "http://127.0.0.1";
ra.port = 30800;
}
return ra;
}
public static void sendSingleMessageResponse(String mobile, String messageContent){
Response re = getLocalRAEnv().given().
param("token", "faketoken").
param("senderId", 1).
param("senderName", "iqianjin").
param("mobile", mobile).
param("messageContent", messageContent).
param("bsCode", "sbcode").
when().get("/api/v1/message/getSend").thenReturn();
re.getBody().print();
re.then().statusCode( 200 );
}
//batchNo批次号非必要参数,
// messageContent messageContents 单条内容和多条容不能共存,优先单一内容发送,多条内容发送是与发送号码一一对应的。
public static JsonPath sendmutiMessageResponse(List<String> mobiles, List<String> messageContents){
Map<String, Object> jsonAsMap = new HashMap();
jsonAsMap.put("senderName","testmuti");
jsonAsMap.put("messageContents",messageContents);
jsonAsMap.put("mobiles",mobiles);
jsonAsMap.put("bscode","fakebscode");
Response re = getLocalRAEnv().given().contentType(JSON).body(jsonAsMap).
when(). post("/api/v1/message/send").thenReturn();
re.getBody().print();
re.then().statusCode( 200 );
return re.getBody().jsonPath();
}
public static JsonPath getSingleMessageResponse(String mobile){
Response re = getLocalRAEnv().given().
param("mobile", mobile).
when(). get("/api/v1/message/query").thenReturn();
re.getBody().print();
re.then().statusCode( 200 );
return re.getBody().jsonPath();
}
}
package com.offcn.TestUnti;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.json.JSONObject;
public class MyDateUtil {
public static void main(String[] args) {
getTime(24,0,0);
}
//按需生成字符串时间,参数是小时、分、秒,最好别有进位
public static String getTime(int hour,int minute,int seconds) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.HOUR_OF_DAY,(calendar.get(Calendar.HOUR_OF_DAY)+hour)>22?22:calendar.get(Calendar.HOUR_OF_DAY)+hour);
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+minute);
calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND)+seconds);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
// System.out.println(format.format(calendar.getTime()));
if(calendar.get(Calendar.HOUR_OF_DAY)==0){
throw new RuntimeException("只能创建当日房间,今日时间不足,请休息一会儿吧~");
}
return format.format(calendar.getTime());
}
//返回当前时间字符串
public static String getTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = sdf.format(d);
return s;
}
}
package com.offcn.TestUnti;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySqlUtil {
//查询表名tableName的条件是condition的结果集
public ResultSet selectFromDB(String tableName, String condition) throws Exception {
Connection conn = null;
String sql;
ResultSet rs = null;
String url = ReadProperties.GetPropertyByKey("sqlurl");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
sql = "select * from " + tableName + " where " + condition;
// System.out.println("select_sql="+sql);
rs = stmt.executeQuery(sql);
return rs;
}
}
package com.offcn.TestUnti;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import com.offcn.process.BasicsGM;
import com.offcn.system.system;
import com.offcn.test.APITest;
import java.util.Arrays;
public class OAuthTokenUnti {
public APITest RAPI;
// private static OAuth2AccessToken token;
public static OAuth2AccessToken token;
public static void main(String[] args) {
String strToken=OAuthTokenUnti.getOathToken("gmysx").getValue();
System.out.println("strToken="+strToken);
}
public static OAuth2AccessToken getOathToken(String system){
if(token == null){
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(getResource(system),new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
restTemplate.setMessageConverters(Arrays.<HttpMessageConverter<?>> asList(converter));
token = restTemplate.getAccessToken();
}
return token;
}
private static ClientCredentialsResourceDetails getResource(String system){
ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
system tem=(system)(BasicsGM.map.get(system));
resource.setAccessTokenUri(tem.getAccess_token_uri());
resource.setClientId(tem.getClient_id());
resource.setClientSecret(tem.getClient_secret());
resource.setGrantType(tem.getGrant_type());
return resource;
}
}
package com.offcn.TestUnti;
import java.util.Random;
import java.util.regex.Pattern;
/**
* Created with IntelliJ IDEA.
* Description:
* 手机号正则: ^1[34578][0-9]{9}
* 生成手机号工具类
*
* @author
* Date: 2017-11-09
* Time: 10:24
*/
public class PhoneNoGeneratorUtil {
private static String firstNum = "1";
private static String[] secondNumArray = {"3", "4", "5", "7", "8"};
public static void main(String[] args) {
System.out.println(PhoneNoGeneratorUtil.getPhoneNo());
}
/**
* 调用一次生成一个手机号,手机号后9位数字通过循环生成
*/
public static String getPhoneNo() {
StringBuffer sb = new StringBuffer();
Random random = new Random();
String secondNum = secondNumArray[random.nextInt(secondNumArray.length)];
sb.append(firstNum);
sb.append(secondNum);
for (int i = 0; i < 9; i++) {
Integer thirdNum = random.nextInt(10);
sb.append(thirdNum.toString());
}
return sb.toString();
}
/**
* 当需要生成较大量的手机号时调用该方法
* 后9位数字随机生成,长度不足时则补0
*/
public String getMultiPhoneNo() {
StringBuffer sb = new StringBuffer();
Random random = new Random();
String secondNum = secondNumArray[random.nextInt(secondNumArray.length)];
sb.append(firstNum);
sb.append(secondNum);
Integer thirdNum = 1 + random.nextInt(999999999);
if (thirdNum.toString().length() <= 9) {
sb.append(thirdNum);
for (int i = 1; i <= 9 - thirdNum.toString().length(); i++) {
sb.append(0);
}
} else {
sb.append(thirdNum.toString());
}
return sb.toString();
}
/**
* 手机号校验
*/
public boolean checkPhoneNo(String phoneNum) {
// 定义手机号的规则
String phoneNumPattern = "^1[34578][0-9]{9}";
// 比对phoneNum是否符合定义的规则
boolean result = Pattern.matches(phoneNumPattern, phoneNum);
return result;
}
}
package com.offcn.TestUnti;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcels {
private String fileName;
private String SheetName;
public ReadExcels() {
}
public ReadExcels(String fileName, String sheetName) {
this.fileName = fileName;
SheetName = sheetName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getSheetName() {
return SheetName;
}
public void setSheetName(String sheetName) {
SheetName = sheetName;
}
@SuppressWarnings({ "unused", "resource" })
public Object[][] readExcels_return() throws Exception{
String targetFile = "TestData/"+fileName;
FileInputStream fis = new FileInputStream(new File(targetFile));
Workbook wb = WorkbookFactory.create(new File(targetFile));
Sheet sheet = wb.getSheet(SheetName);
int rows=sheet.getPhysicalNumberOfRows();
//有多少行数据就创建多少个map,首行是标题第二行开始才是数据,所以rows-1
@SuppressWarnings("unchecked")
HashMap<String, Object>[][] arrmap = new HashMap[rows-1][1];
List<String> list = new ArrayList<String>();
//每个子map分别为arrmap[0][0]、arrmap[1][0]、arrmap[2][0]。。。
for(int i = 1 ; i < sheet.getPhysicalNumberOfRows() ; i++){
arrmap[i-1][0] = new HashMap<>();
}
//获取标题行数据存放在list里面
for(int i = 0 ; i < 1 ; i++){
Row r = sheet.getRow(i);
for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
Cell cell = r.getCell(j);
list.add(getCellValue(cell));
}
}
Log.logInfo("数据源读取记录:共有几列数据="+list.size());
Log.logInfo("数据源读取记录:共有几行数据="+arrmap.length);
for(int i = 1 ; i < sheet.getPhysicalNumberOfRows() ; i++){
Row r = sheet.getRow(i);
for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
Cell cell = r.getCell(j);
String brandName=getCellValue(cell);
if (!brandName.equals("null")){//如果单元格不等于空,才进行存储
// System.out.println("i="+i+",j="+j);
arrmap[i - 1][0].put(list.get(j), brandName);//分别往每个子map中存放数据,每行是一个map
}
}
}
/**
* 查看数据提取结果
for(int i=0;i<arrmap.length;i++){
for(int j=0;j<arrmap[i].length;j++){
System.out.print(" "+arrmap[i][j]);
}
System.out.println();
}
for(int i=0;i<arrmap.length;i++){
HashMap<String, Object> arr=arrmap[i][0];
System.out.println("处理后数据="+JSONObject.fromObject(arr).toString());
}
*/
return arrmap;
}
private String getCellValue(Cell cell){
int cellType=0;
try {
cellType = cell.getCellType();
} catch (Exception e) {
return "无法解析";
}
String value = "";
if(cellType == Cell.CELL_TYPE_STRING){
value = cell.getStringCellValue();
}else if(cellType == Cell.CELL_TYPE_NUMERIC){
value = String.valueOf(cell.getNumericCellValue());
}else if(cellType == Cell.CELL_TYPE_BOOLEAN){
value = String.valueOf(cell.getBooleanCellValue());
}else if(cellType == Cell.CELL_TYPE_BLANK){
value = "";
}else if(cellType == Cell.CELL_TYPE_FORMULA){
value = String.valueOf(cell.getCellFormula());
}else{
value = "";
}
return value;
}
}
package com.offcn.TestUnti;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) {
// String s=ReadProperties.GetPropertyByKey("rgxs");
// System.out.println(s);
// ClearProperty();
// SetProperty("123","111");
}
public static String GetPropertyByKey(String key) {
Properties pps = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"class.properties";
InputStream in = new BufferedInputStream (new FileInputStream(sourceFile));
pps.load(in);
String value = pps.getProperty(key);
return value;
}catch (IOException e) {
return null;
}
}
//得到information中的值
public static String GetinformationByKey(String key) {
Properties pps = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"information.properties";
InputStream in = new BufferedInputStream (new FileInputStream(sourceFile));
pps.load(in);
String value = pps.getProperty(key);
return value;
}catch (IOException e) {
return null;
}
}
//
public static void updateProperty(String name,String value){
Properties prop = new Properties();// 属性集合对象
File directory = new File(".");
try {
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"information.properties";
FileInputStream fis = new FileInputStream(sourceFile);// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
fis.close();// 关闭流
// 获取属性值,sitename已在文件中定义
// System.out.println("获取属性值:password=" + prop.getProperty("password"));
// 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件
// System.out.println("获取属性值:country=" + prop.getProperty("country", "中国"));
// 修改sitename的属性值
prop.setProperty(name, value);
// 文件输出流
FileOutputStream fos = new FileOutputStream(sourceFile);
// 将Properties集合保存到流中
prop.store(fos,"");
fos.close();// 关闭流
// Log.logInfo("成功保存环境信息文件。");
} catch (IOException e) {
// Log.logError("保存环境信息文件失败。");
e.printStackTrace();
}
}
//判断Properties文件是否为空
public static boolean isBoolean(){
File directory = new File(".");
try {
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"information.properties";
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream(sourceFile);// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
boolean b=prop.isEmpty();
fis.close();// 关闭流
return b;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static void ClearProperty() {
File directory = new File(".");
try {
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"information.properties";
File file =new File(sourceFile);
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String GetPropertyByClassName(String key) {
Properties pps = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"reflect.properties";
InputStream in = new BufferedInputStream (new FileInputStream(sourceFile));
pps.load(in);
String value = pps.getProperty(key);
return value;
}catch (IOException e) {
return null;
}
}
public static String GetPropertyByClassName(String key,String qudao) {
Properties pps = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+qudao+"_reflect.properties";
InputStream in = new BufferedInputStream (new FileInputStream(sourceFile));
pps.load(in);
String value = pps.getProperty(key);
return value;
}catch (IOException e) {
return null;
}
}
}
package com.offcn.TestUnti;
import com.offcn.process.BasicsGM;
import com.offcn.system.system;
import redis.clients.jedis.*;
public class RedisUtils {
public enum RedisPath{
LOGINVERIFYCODE("bestbuy:customer:sendCode:app:login:"),
SETDEALVERIFYCODE("bestbuy:customer:sendCode:app:setDeal:");
private String path;
RedisPath(String redisPath){
this.path = redisPath;
}
public String toString(){
return this.path.toString();
}
}
//获取电话号码所对应的验证码采用redis方式
public String getVerifyCode(String phoneNumber){
system tem=(system)(BasicsGM.map.get("gmysx"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get(("BESTBUY:CUST:PHONEMSG:"+phoneNumber));
if(verifyCode==null){
Log.logInfo("getVerifyCode Cannot get verifyCode not in Redis for "+ phoneNumber);
verifyCode="";
}
return verifyCode;
}
//获取自营渠道的图片验证码
public String getZyVerifyCode(String phoneNumber){
if(phoneNumber==null){
phoneNumber="";
}
system tem=(system)(BasicsGM.map.get("zy"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get(("bestbuy:customer:imgCode:app:register:"+phoneNumber));
if(verifyCode==null){
Log.logInfo("getZyVerifyCode Cannot get verifyCode not in Redis for "+ phoneNumber);
verifyCode="";
}
Log.logInfo("自营渠道的图片验证码:"+verifyCode);
return verifyCode;
}
//获取自营3.0渠道的图片验证码
public String getZy3VerifyCode(String phoneNumber){
if(phoneNumber==null){
phoneNumber="";
}
system tem=(system)(BasicsGM.map.get("zy3"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get(("bestbuy:customer:imgCode:app:register:v1:"+ phoneNumber));
if(verifyCode==null){//
Log.logInfo("getZyVerifyCode Cannot get verifyCode not in Redis for "+ phoneNumber);
verifyCode="";
}
Log.logInfo("自营渠道的图片验证码:"+verifyCode);
return verifyCode;
}
//自营渠道的短信验证码bestbuy:customer:sendCode:app:register
public String getZyDuanXinCode(String phoneNumber){
system tem=(system)(BasicsGM.map.get("zy"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get(("bestbuy:customer:sendCode:app:register:"+phoneNumber));
if(verifyCode==null){
Log.logInfo("getZyDuanXinCode Cannot get verifyCode not in Redis for "+ phoneNumber);
verifyCode="";
}
Log.logInfo("自营渠道的短信验证码:"+verifyCode);
return verifyCode;
}
//通用方法
public String getRedisCode(RedisPath redisPath,String phoneNumber){
system tem=(system)(BasicsGM.map.get("zy"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get((redisPath.toString()+phoneNumber));
if(verifyCode==null){
Log.logInfo("获取验证码失败,电话: "+ phoneNumber);
verifyCode="";
}
Log.logInfo("获取的验证码为:"+verifyCode);
return verifyCode;
}
//获取蛋壳的注册验证码
public String getDkVerifyCode(String phoneNumber){
if(phoneNumber==null){
phoneNumber="";
}
system tem=(system)(BasicsGM.map.get("dk"));
String verifyCode=null;
Jedis jedis = new Jedis(tem.getRedis_URI());
jedis.auth("2xqPR2i7OoiKn5bs8tI0");
jedis.select(Integer.valueOf(tem.getRedis_db_index()));
verifyCode=jedis.get(("BESTBUY:CUST:PHONEMSG:"+ phoneNumber));
if(verifyCode==null){
Log.logInfo("getDkVerfyCode Cannot get verifyCode not in Redis for "+ phoneNumber);
verifyCode="";
}
Log.logInfo("蛋壳注册验证码为:"+verifyCode);
return verifyCode;
}
public static void main(String[] args) {
RedisUtils ru=new RedisUtils();
System.out.println(ru.getZy3VerifyCode("13910960649"));
// System.out.println(getZyDuanXinCode("13910960649"));
}
}
package com.offcn.TestUnti;
import java.util.HashMap;
import com.offcn.interfaces.API;
/**
* 反射工具类
*
* @author yaoshuai
*
*/
public class Reflect_api {
public API Reflections(HashMap<String, Object> data) {
String ClassName = Reflect_api.getRefleserviceUrlxClassName(data);
API obj = null;
Class c = null;
int count=1;
while(true){
try {
c = Class.forName(ClassName);
break;
}catch (ClassNotFoundException e) {
String serviceUrl = data.get("serviceUrl").toString();
String CalssName_new = serviceUrl.split("/")[serviceUrl.split("/").length - 1];
String system = MapUtil.getValue("system", data);
String classRoute = ReadProperties.GetPropertyByKey(system);
ClassName=classRoute+"process."+CalssName_new;
// Log.logError("Reflect_api,ReflexClass Error,Classname=" + ClassName);
// String system = MapUtil.getValue("system", data);
// String classRoute = ReadProperties.GetPropertyByKey(system);
// count++;
// if(!classRoute.equals("com.offcn.api.xyzb.liucheng")){
//// String serviceUrl = data.get("serviceUrl").toString();
//// ClassName = serviceUrl.split("/")[serviceUrl.split("/").length - 1];
// String classRoute1 = ReadProperties.GetPropertyByKey("gmysx");
// ClassName=ClassName.replaceAll(classRoute, classRoute1);
// }
}
if(count==3){
break;
}
}
try{
obj = (API) c.newInstance();
}catch (InstantiationException e) {
Log.logError("Reflect_api,instantiation Error,Classname="
+ ClassName);
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.logError("Reflect_api,Reflection class is not public Error,Classname="
+ ClassName);
e.printStackTrace();
}
return obj;
}
// 获得数据中serviceUrl所对应的类名
private static String getRefleserviceUrlxClassName(
HashMap<String, Object> data) {
String serviceUrl = data.get("serviceUrl").toString();
String CalssName = serviceUrl.split("/")[serviceUrl.split("/").length - 1];
String system = MapUtil.getValue("system", data);
String classRoute = ReadProperties.GetPropertyByKey(system);
// if ("/order/insert".equals(serviceUrl)) {
// if (serviceUrl.indexOf("/order/insert")!=-1) {
// return classRoute+CalssName + "_dd";
// }
//xuwen-添加对商户(sh)的支持
// if("zy".equals(system) || "sh".equals(system) || "dk".equals(system) ){
// String classReflectName = ReadProperties.GetPropertyByClassName(serviceUrl);
// if ( classReflectName!=null ) {
// return classRoute+ classReflectName;
// }
// }
if("xyzb".equals(system)){
String classReflectName = ReadProperties.GetPropertyByClassName(serviceUrl,system);
if ( classReflectName!=null ) {
return classRoute+ classReflectName;
}
}
return classRoute+CalssName;
}
}
package com.offcn.TestUnti;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import jxl.*;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class SheetUtils {
public Workbook workbook;
public Sheet sheet;
public Cell cell;
int rows;
int columns;
public String fileName;
public String sheetName;
public ArrayList<String> arrkey = new ArrayList<String>();
String sourceFile;
/**
* @param fileName
* excel鏂囦欢鍚�
* @param caseName
* sheet鍚�
*/
public SheetUtils(String fileName, String sheetName) {
super();
this.fileName = fileName;
this.sheetName = sheetName;
}
public Object[][] getExcelData() {
try {
workbook = Workbook.getWorkbook(new File(getPath()));
} catch (BiffException | IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
rows = sheet.getRows();
columns = sheet.getColumns();
@SuppressWarnings("unchecked")
HashMap<String, Object>[][] arrmap = new HashMap[rows - 1][1];
if (rows > 1) {
for (int i = 0; i < rows - 1; i++) {
arrmap[i][0] = new HashMap<>();
}
} else {
System.out.println("excel no data");
}
for (int c = 0; c < columns; c++) {
String cellvalue = sheet.getCell(c, 0).getContents();
arrkey.add(cellvalue);
}
for (int r = 1; r < rows; r++) {
for (int c = 0; c < columns; c++) {
Object cellvalue = getCellValue(c, r);
if (cellvalue != null)
arrmap[r - 1][0].put(arrkey.get(c), getCellValue(c, r));
}
}
// for(int i=0;i<arrmap.length;i++){
// for(int j=0;j<arrmap[i].length;j++){
// System.out.println("i="+i+",j="+j);
// System.out.println("arr="+arrmap[i][j]);
// }
// }
return arrmap;
}
public Object getCellValue(int c, int r) {
Object cellvalue = null;
Cell cell = sheet.getCell(c, r);
if (cell.getContents().equals("null")) {
return null;
}
if (sheet.getCell(c, 0).getContents().equals("list")) {
}
if (cell.getType() == CellType.LABEL) {
LabelCell nc = (LabelCell) cell;
return nc.getString();
}
if (cell.getType() == CellType.DATE) {
DateCell nc = (DateCell) cell;
return nc.getDate();
}
if (cell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) cell;
return nc.getValue();
}
return cellvalue;
}
/**
* 鑾峰緱excel鏂囦欢鐨勮矾寰�
*
* @return
* @throws IOException
*/
public String getPath() throws IOException {
sourceFile = "TestData/"+fileName;
return sourceFile;
}
public void writeExcel(String NO,String caseNo, String input,String Description,
String statusline, String resbody,String codeORerrcode,String msgORerrmsy,
String result,String time) {
File file;
try {
// System.out.println(getPath());
file = new File(getPath());
Workbook rwb = Workbook.getWorkbook(file);
File tempfile = new File("TestData/"+fileName);
WritableWorkbook wwb = Workbook.createWorkbook(tempfile, rwb);
WritableSheet ws = wwb.getSheet(sheetName);
if (ws == null) {
ws = wwb.createSheet(sheetName, 0);
}
int rows = ws.getRows();
WritableFont wf = new WritableFont(WritableFont.TAHOMA);
wf.setPointSize(10);
WritableCellFormat wcf = new WritableCellFormat(wf);
ws.addCell(new Label(0, rows, NO, wcf));
ws.addCell(new Label(1, rows, caseNo, wcf));
ws.addCell(new Label(2, rows, input, wcf));
ws.addCell(new Label(3, rows, Description, wcf));
ws.addCell(new Label(4, rows, statusline, wcf));
ws.addCell(new Label(5, rows, resbody, wcf));
ws.addCell(new Label(6, rows, codeORerrcode, wcf));
ws.addCell(new Label(7, rows, msgORerrmsy, wcf));
ws.addCell(new Label(8, rows, time, wcf));
if (result.equals("Pass")) {
wf = new WritableFont(WritableFont.TAHOMA);
wcf = new WritableCellFormat(wf);
wf.setColour(Colour.GREEN);
} else if (result.contains("Fail")) {
wf = new WritableFont(WritableFont.TAHOMA);
wcf = new WritableCellFormat(wf);
wf.setColour(Colour.RED);
} else {
wf = new WritableFont(WritableFont.TAHOMA);
wcf = new WritableCellFormat(wf);
wf.setColour(Colour.YELLOW);
}
ws.addCell(new Label(9, rows, result, wcf));
wwb.write();
wwb.close();
rwb.close();
file.delete();
tempfile.renameTo(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeExcel(String c1, String c2, String c3) {
File file;
try {
file = new File(getPath());
Workbook rwb = Workbook.getWorkbook(file);
File tempfile = new File("TestData/"+fileName);
WritableWorkbook wwb = Workbook.createWorkbook(tempfile, rwb);
WritableSheet ws = wwb.getSheet(sheetName);
if (ws == null) {
ws = wwb.createSheet(sheetName, 0);
}
int rows = ws.getRows();
ws.addCell(new Label(0, rows, c1));
ws.addCell(new Label(1, rows, c2));
ws.addCell(new Label(2, rows, c3));
wwb.write();
wwb.close();
rwb.close();
file.delete();
tempfile.renameTo(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void cleanAndWriteToSheet(String[][] array) {
File file;
try {
file = new File(getPath());
Workbook rwb = Workbook.getWorkbook(file);
File tempfile = new File("TestData/"+fileName);
WritableWorkbook wwb = Workbook.createWorkbook(tempfile, rwb);
WritableSheet ws = wwb.getSheet(sheetName);
if (ws == null) {
ws = wwb.createSheet(sheetName, 0);
}
int rows = ws.getRows();
for (int i = 0; i < rows - 1; i++) {
ws.removeRow(i);
}
for (int r = 0; r < array.length - 1; r++) {
for (int c = 0; c < array[r].length - 1; c++) {
ws.addCell(new Label(c, r, array[r][c]));
}
}
wwb.write();
wwb.close();
rwb.close();
file.delete();
tempfile.renameTo(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.offcn.TestUnti;
import java.util.ArrayList;
public class StringUtils {
public static void main(String[] args) {
String str="\u64cd\u4f5c\u6210\u529f";
System.out.println(decodeUnicode(str));
}
//字符串按符号分隔
public static String[] getArrayString(String custom,String Symbol){
return custom.split(Symbol);
}
//长字符串中是否分别包含字符串数据
public static boolean VerificationString(String custom,String[] ArrayString){
for(int i=0;i<ArrayString.length;i++){
if(!custom.contains(ArrayString[i])){
return false;
}else{
// System.out.println("包含");
continue;
}
}
return true;
}
//Unicode转UTF-8的转化
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
}
package com.offcn.TestUnti;
import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.offcn.system.system;
public class XMLread {
public static void main(String[] args) {
XMLread xml=new XMLread();
@SuppressWarnings("unchecked")
Map<String,Object> map=(Map<String, Object>) xml.getSystem();
system ysx=(system) map.get("Gm_ysx");
system dd=(system) map.get("Gm_dd");
System.out.println(ysx.getRM_port());
System.out.println(dd.getRM_port());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map<String, Object> getSystem(){
Document document = null;
Object obj=null;
Method met=null;
Map<String,Object> map=new HashMap<String,Object>();
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File("src/resources/system.xml")); // 读取XML文件,获得document对象
// 获取根节点
Element root = document.getRootElement();
// 获取根节点下的子节点
for (Iterator i = root.elementIterator(); i.hasNext();) {
// 将每个子节点赋给el
Element el = (Element) i.next();
// 如果节点的名称为“system”,system元素属性name=参数// && systemName.equals(el.attribute("name").getValue())
if ("system".equals(el.getName())) {// 获取节点元素的名称
Class c=Class.forName("com.offcn.system.system");
obj=(Object) c.newInstance();
for (Iterator it = el.elementIterator(); it.hasNext();) {
Element elchild = (Element) it.next();
met=c.getDeclaredMethod(getMethodName(elchild.getName()), String.class);
met.invoke(obj, elchild.getText());
map.put(el.attribute("name").getValue(), obj);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
//获取注入得方法名
private String getMethodName(String str){
String s="set"+str.substring(0,1).toUpperCase()+str.substring(1,str.length());
return s;
}
}
package com.offcn.TestUnti;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;
/**
* 图片识别类
* 第一个参数:几位的中英数
* 第二个参数:图片地址
* 返回解析好的字符串
* @author puhui
*/
public class aliOCR {
public static void main(String[] args) {
// getYZM(6,"d:\\a1.jpg");
getYZM(4,"d:\\t1.jpg");
}
public static String getYZM(int count,String imagePath){
String host = "http://ali-checkcode.showapi.com";
String path = "/checkcode";
String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE 4afc3a5a191a4bbd80b837c3374ac872");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("convert_to_jpg", "0");
bodys.put("img_base64", encodeImgageToBase64(new File(imagePath)));
bodys.put("typeId", "30"+count+"0");
String result=null;
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
result=EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.fromObject(result);
result=obj.getString("showapi_res_body");
JSONObject obj1 = JSONObject.fromObject(result);
result=obj1.get("Result").toString();
System.out.println("获取的验证码是:"+obj1.get("Result"));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//图片转化成base64字符串
public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}
//base64字符串转化成图片
public static boolean GenerateImage(String FilePath,String imgStr)
{ //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imgFilePath = FilePath;//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
package com.offcn.TestUnti;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class cmdUtil {
public static String run(String cmdString) {
Runtime runtime = Runtime.getRuntime();
StringBuffer b=null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(runtime.exec(cmdString).getInputStream(),"GBK"));
//StringBuffer b = new StringBuffer();
String line=null;
b=new StringBuffer();
while ((line=br.readLine())!=null) {
b.append(line+"\n");
}
// System.out.println(b.toString());
} catch (Exception e) {
e.printStackTrace();
}
return b.toString();
}
public static void main(String[] args) {
cmdUtil delp = new cmdUtil();
System.out.println(delp.run("nslookup www.qq.com").contains("Address: 192.168.10.222"));
// delp.run("nslookup www.qq.com");
// delp.run("netsh interface ip set dns \"无线网络连接\" static 192.168.10.222");
}
}
package com.offcn.TestUnti;
import java.text.SimpleDateFormat;
public class randomUtil {
public static String dateString(){
SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr = dateformat.format(System.currentTimeMillis());
return dateStr;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.BasicsGM;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 添加公告
*
* @author puhui
*
*/
public class announce extends XYZB implements API {
public String parameter;//参数集合
public String uuid;
public String nickname;
public String create_time;
public String token_room_num;
public String content;//公告内容
public String id;
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Post_token(data, Url,Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_announcement a",
" a.uuid = '" + Current_uuid + "' ");
rs_bankcard.last();
if (rs_bankcard.getRow() < 1) {
result = result && false;
failReason = failReason + "xyu_announcement info is not in DB;";
} else {
String act_uuid = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("uuid")));
String act_nickname = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("nickname")));
String act_create_time = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("create_time")));
String act_token_room_num = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("token_room_num")));
String act_content = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("content")));
Current_announcement_id=String.
valueOf(rs_bankcard.getString(rs_bankcard.findColumn("id")));
uuid = MapUtil.killQuotes(jp.getString("data.uuid"), "\"");//去掉双引号的uuid
nickname = MapUtil.killQuotes(jp.getString("data.nickname"), "\"");//去掉双引号的uuid
create_time = MapUtil.killQuotes(jp.getString("data.create_time"), "\"");//去掉双引号的uuid
token_room_num = MapUtil.killQuotes(jp.getString("data.token_room_num"), "\"");//去掉双引号的uuid
content = MapUtil.killQuotes(jp.getString("data.content"), "\"");//去掉双引号的uuid
id = MapUtil.killQuotes(jp.getString("data.id"), "\"");//去掉双引号的uuid
if ((!act_uuid.equals(uuid))
|| (!act_nickname.equals(StringUtils.decodeUnicode(nickname)))
|| (!act_create_time.contains(create_time))
|| (!act_token_room_num.equals(token_room_num))
|| (!act_content.contains(content))){
result = result && false;
failReason = failReason + "xyu_announcement info in DB is wrong;";
}
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_announcement info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 删除公告信息
*
* @author puhui
*
*/
public class announce_del extends XYZB implements API {
public String parameter;//参数集合
public String Description;//参数集合
public String id;//文件id
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
id = MapUtil.getParameter(parameter, "id").trim();
if ((!id.equals("")) && id.equals("code")) {
parameter = Current_announcement_id;
parameter = MapUtil.killQuotes(parameter, "\"");//去掉双引号的Othercode
data.put("parameter", parameter);
return data;
}
if ((!id.equals("")) && id.equals("Othercode")) {
parameter = Integer.valueOf(Current_id)-2+"";
parameter = MapUtil.killQuotes(parameter, "\"");//去掉双引号的Othercode
data.put("parameter", parameter);
return data;
}
data.put("parameter", id);
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Map<String, Object> jsonAsMap = new HashMap<>();
parameter = MapUtil.getValue("parameter", data);
Response re = RequestDataUtils.Del_Token(data,Client_token, "/api/v1/announce/"+parameter);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room_files f ",
" f.id = '" + Current_id + "' ");
rs_bankcard.last();
if (rs_bankcard.getRow()!=0){
result = result && false;
failReason = failReason + "xyu_room_files info in DB is wrong;";
} else {
Log.logInfo("xyu_room_files info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room_files info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 获取公告列表
*
* @author puhui
*
*/
public class announce_get extends XYZB implements API {
public String parameter;//参数集合
public String Description;
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
// 获取parameter对应的内容
Description = MapUtil.getValue("Description", data);
if(Description.contains("错误token")){
Response re = RequestDataUtils.Get_Errtoken(data, "/api/v1/announce", Client_token);
return re;
}else if(Description.contains("超长token")){
Response re = RequestDataUtils.Get_Longtoken(data, "/api/v1/announce", Client_token);
return re;
}else if(Description.contains("无token")){
Response re = RequestDataUtils.Get_Notoken(data, "/api/v1/announce");
return re;
}
Response re = RequestDataUtils.Get_Noparameter(data, "/api/v1/announce",Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if((data.get("custom") != null) && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if (jp.getString("data") != null) {
parameter = MapUtil.getValue("parameter", data);
String dataarr[] =jp.getString("data.data").split("]");
System.out.println(jp.getString("data.data"));
try {
ResultSet xyu_announcement=null;
xyu_announcement = this.selectFromDB(
" xyu_announcement a ",
" a.token_room_num = '" + Current_room + "' ");
xyu_announcement.last();
// System.out.println(dataarr.length);
// System.out.println(xyu_announcement.getRow());
if (xyu_announcement.getRow()!=dataarr.length) {
result = result && false;
failReason = failReason + "xyu_announcement.getRow() is not dataarr.length;";
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_announcement info in DB;";
e.printStackTrace();
}
}
}
if (result){
return "Pass";
}else{
return "Fail:" + failReason;
}
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 提交回答
*
* @author puhui
*
*/
public class answer extends XYZB implements API {
public String parameter;//参数集合
public String id;//
public String answer;//
public String private_;//
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
id = MapUtil.getParameter(parameter, "id").trim();
answer = MapUtil.getParameter(parameter, "answer").trim();
private_ = MapUtil.getParameter(parameter, "private").trim();
if ((!id.equals("")) && id.equals("code")) {
id=Current_questions_id;
parameter = parameter.replace("\"id\":code", "\"id\":\""+ Current_questions_id + "\"");
}
if ((!answer.equals("")) && answer.equals("random")) {
answer="我也不会啊。。。";
parameter = parameter.replace("\"answer\":random", "\"answer\":\""+ answer + "\"");
}
if (!private_.equals("")) {
parameter = parameter.replace("\"private_\"", "\"private\"");
}
data.put("parameter", parameter);
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Post_token(data, Url,Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
private_ = MapUtil.killQuotes(private_, "\"");//去掉双引号的private_
answer = MapUtil.killQuotes(answer, "\"");//去掉双引号的answer
id = MapUtil.killQuotes(id, "\"");//去掉双引号的id
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room_answer ",
" 1 = 1");
rs_bankcard.last();
if (rs_bankcard.getRow() < 1) {
result = result && false;
failReason = failReason + "xyu_room_answer info is not in DB;";
} else {
String act_id = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("id")));
String act_answer = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("answer")));
act_answer = MapUtil.killQuotes(act_answer, "\"");
String act_question_id = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("question_id")));
String act_private = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("private")));
// System.out.println(private_);
// System.out.println(act_private);
// System.out.println(answer);
// System.out.println(StringUtils.decodeUnicode(act_answer));
// System.out.println(id);
// System.out.println(act_question_id);
if ((!private_.equals(act_private))
|| (!answer.equals(StringUtils.decodeUnicode(act_answer)))
|| (!id.equals(act_question_id))){
result = result && false;
failReason = failReason + "xyu_room_answer info in DB is wrong;";
}
}
} catch (Exception e) {
e.printStackTrace();
result = result && false;
failReason = failReason + "cannot verify xyu_room_answer info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 禁止提问
*
* @author puhui
*
*/
public class ask_status extends XYZB implements API {
public String parameter;//参数集合
public String Description;//参数集合
public String is_ask;//
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
is_ask = MapUtil.getParameter(parameter, "is_ask").trim();
is_ask=MapUtil.killQuotes(is_ask, "\"");
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Map<String, Object> jsonAsMap = new HashMap<>();
jsonAsMap.put("is_ask", is_ask);
// System.out.println(room_nums.get("Not_edited"));
Response re = RequestDataUtils.Put_Token(data,Client_token, Url,jsonAsMap);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
String act_is_ask = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("is_ask")));
if (!is_ask.equals(act_is_ask)){
result = result && false;
failReason = failReason + "xyu_room info in DB is wrong;";
} else {
Log.logInfo("xyu_room info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 全员禁言
*
* @author puhui
*
*/
public class banned_status extends XYZB implements API {
public String parameter;//参数集合
public String Description;//参数集合
public String is_banned;//
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
is_banned = MapUtil.getParameter(parameter, "is_banned").trim();
is_banned=MapUtil.killQuotes(is_banned, "\"");
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Map<String, Object> jsonAsMap = new HashMap<>();
jsonAsMap.put("is_banned", is_banned);
// System.out.println(room_nums.get("Not_edited"));
Response re = RequestDataUtils.Put_Token(data,Client_token, Url,jsonAsMap);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
String act_is_banned = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("is_banned")));
if (!is_banned.equals(act_is_banned)){
result = result && false;
failReason = failReason + "xyu_room info in DB is wrong;";
} else {
Log.logInfo("xyu_room info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 获取禁言状态
*
* @author puhui
*
*/
public class banned_status_get extends XYZB implements API {
public String Description;//参数集合
public int id;//房间id
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
// 获取parameter对应的内容
Description = MapUtil.getValue("Description", data);
if(Description.contains("错误token")){
Response re = RequestDataUtils.Get_Errtoken(data, "/api/v1/banned_status", Client_token);
return re;
}else if(Description.contains("超长token")){
Response re = RequestDataUtils.Get_Longtoken(data, "/api/v1/banned_status", Client_token);
return re;
}else if(Description.contains("无token")){
Response re = RequestDataUtils.Get_Notoken_NoCookie(data, "/api/v1/banned_status");
return re;
}
Response re = RequestDataUtils.Get_Noparameter(data, "/api/v1/banned_status",Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
String is_banned=jp.getString("data.is_banned");
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
// System.out.println(rs_bankcard.getString("is_banned"));
if (!is_banned.equals(rs_bankcard.getString("is_banned"))){
result = result && false;
failReason = failReason + "xyu_room info in DB is wrong;";
} else {
Log.logInfo("xyu_room info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 获取发言间隔时间
*
* @author puhui
*
*/
public class banned_time extends XYZB implements API {
public String Description;//参数集合
public int id;//房间id
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Get_Noparameter(data, Url,Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
String banned_time=jp.getString("data.banned_time");
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
if (!banned_time.equals(rs_bankcard.getString("banned_time"))){
result = result && false;
failReason = failReason + "xyu_room info in DB is wrong;";
} else {
Log.logInfo("xyu_room info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.MyDateUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 更新发言间隔时间
*
* @author puhui
*
*/
public class banned_time_up extends XYZB implements API {
public String parameter;//参数集合
public String Description;//参数集合
public String banned_time;//
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
banned_time = MapUtil.getParameter(parameter, "banned_time").trim();
banned_time=MapUtil.killQuotes(banned_time, "\"");
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Map<String, Object> jsonAsMap = new HashMap<>();
jsonAsMap.put("banned_time", banned_time);
// System.out.println(room_nums.get("Not_edited"));
Response re = RequestDataUtils.Put_Token(data,Client_token, "/api/v1/banned_time",jsonAsMap);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
//是否是线上环境
if (!isProduct) {
try {
ResultSet rs_bankcard = this.selectFromDB(
" xyu_room r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
String act_banned_time = String
.valueOf(rs_bankcard.getString(rs_bankcard.findColumn("banned_time")));
if (!banned_time.equals(act_banned_time)){
result = result && false;
failReason = failReason + "xyu_room info in DB is wrong;";
} else {
Log.logInfo("xyu_room info in DB is correct;");
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.util.HashMap;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
/**
* 用户离开房间
*
* @author puhui
*
*/
public class del extends XYZB implements API {
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Del_Token(data, Client_token, Url);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data").length()>4){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("操作成功".equals(jp.getString("msg"))){
try {
ResultSet rs_bankcard=null;
rs_bankcard = this.selectFromDB(
" xyu_room_users r ",
" r.uuid = '" + Current_uuid + "' ");
rs_bankcard.last();
// System.out.println(rs_bankcard.getRow());
if(!(rs_bankcard.getString("online").equals("0"))){
result = result && false;
failReason = failReason + "online is not find;";
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.xyzb;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.ReadProperties;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.XYZB;
import net.sf.json.JSONObject;
/**
* 获取房间用户信息
*
* @author puhui
*
*/
public class getRooms extends XYZB implements API {
public String parameter;//参数集合
public String Description;
public String password;//姓名
public String room_num;
public String current_page;
public String first_page_url;
public String last_page;
public String last_page_url;
public String next_page_url;
public String path;
public String per_page;
public String prev_page_url;
public String to;
public String total;
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
parameter = MapUtil.getValue("parameter", data);
password = MapUtil.getParameter(parameter, "password").trim();
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
// 获取parameter对应的内容
Description = MapUtil.getValue("Description", data);
if(Description.contains("错误token")){
Response re = RequestDataUtils.Get_Errtoken(data, "/api/v1/users", Client_token);
return re;
}else if(Description.contains("超长token")){
Response re = RequestDataUtils.Get_Longtoken(data, "/api/v1/users", Client_token);
return re;
}else if(Description.contains("无token")){
Response re = RequestDataUtils.Get_Notoken(data, "/api/v1/users");
return re;
}
Response re = RequestDataUtils.Get_token(data, "/api/v1/users",Client_token);
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(jp.getString("msg"));
if ((data.get("code") != null )
&& ((jp.getString("code") == null) || (!jp.getString(
"code").equals(data.get("code").toString())))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null)
&& ((msg == null) || (!msg.equals(data.get("msg").toString())))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if((data.get("custom") != null) && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
//如果请求地址接口是studentinfo接口5
if (jp.getString("data") != null) {
parameter = MapUtil.getValue("parameter", data);
first_page_url=jp.getString("data.first_page_url");
last_page_url=jp.getString("data.last_page_url");
next_page_url=jp.getString("data.next_page_url");
prev_page_url=jp.getString("data.prev_page_url");
total=jp.getString("data.total");
String role="";
if(parameter.contains("&")){
String arr[]=parameter.split("&");
role=arr[0].split("=")[1];
}
try {
ResultSet rs_bankcard=null;
if(!parameter.contains("role")){
rs_bankcard = this.selectCountFromDB(
" xyu_room_users r ",
" r.room_num = '" + Current_room + "' ");
rs_bankcard.last();
// System.out.println(rs_bankcard.getString("count(*)"));
}else{
rs_bankcard = this.selectCountFromDB(
" xyu_room_users r ",
" r.room_num = '" + Current_room + "' and role = '"+role+"'");
rs_bankcard.last();
// System.out.println(rs_bankcard.getString("count(*)"));
}
if (!(rs_bankcard.getString("count(*)")).equals(total)) {
result = result && false;
failReason = failReason + "total is not find;";
}
if(!first_page_url.contains(parameter.substring(1, parameter.length()-2))){
result = result && false;
failReason = failReason + "first_page_url is not find;";
}
if(!last_page_url.contains(parameter.substring(1, parameter.length()-2))){
result = result && false;
failReason = failReason + "last_page_url is not find;";
}
if(next_page_url!=null && !next_page_url.contains(parameter.substring(1, parameter.length()-2))){
result = result && false;
failReason = failReason + "next_page_url is not find;";
}
if(prev_page_url!=null && !prev_page_url.contains(parameter.substring(1, parameter.length()-2))){
result = result && false;
failReason = failReason + "prev_page_url is not find;";
}
} catch (Exception e) {
result = result && false;
failReason = failReason + "cannot verify xyu_room info in DB;";
e.printStackTrace();
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment