Commit 231a13fe by Li Yongyu

Merge branch 'master' of https://gitlab.eoffcn.com/lyy56980/study.git

Conflicts:
	studycenter_Api_auto_test/testng.xml
parents 517d2040 de22e6a6
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>study</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>study</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
/.classpath
/.project
.idea
.settings
bin/
log/
testoutput/
test-output/
/.classpath
/.project
.idea
.settings
bin/
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();
环境要求:
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();
package Practice_test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
public class CanshuTiQu {
public static void main(String[] args) {
String str="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":code_own\"";
String a=getAll(str,"verifyCode");
System.out.println("a="+a);
}
// 在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getAll(String parameter, String Letter) {
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();
}
}
package Practice_test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
public class CanshuTiQu {
public static void main(String[] args) {
String str="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":code_own\"";
String a=getAll(str,"verifyCode");
System.out.println("a="+a);
}
// 在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getAll(String parameter, String Letter) {
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();
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
package Practice_test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsUtil_Post_Json {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* post��ʽ���������(httpsЭ��) ����json����
*
* @param url
* �����ַ
* @param content
* ����
* @param charset
* ����
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static void main(String[] args) {
try {
post("https://api.puhuifinance.com/datapi-blacklist-server/api/v1/batchQueryBlacklist/query",
"[{\"queryField\":\"id_no\",\"queryValue\":\"13910960649\"}]",
"utf-8");
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] post(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException,
IOException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("Content-Type","application/json");
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// ˢ�¡��ر�
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
package Practice_test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsUtil_Post_Json {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* post��ʽ���������(httpsЭ��) ����json����
*
* @param url
* �����ַ
* @param content
* ����
* @param charset
* ����
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static void main(String[] args) {
try {
post("https://api.puhuifinance.com/datapi-blacklist-server/api/v1/batchQueryBlacklist/query",
"[{\"queryField\":\"id_no\",\"queryValue\":\"13910960649\"}]",
"utf-8");
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] post(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException,
IOException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("Content-Type","application/json");
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// ˢ�¡��ر�
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
}
\ No newline at end of file
package Practice_test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LMFMD5 {
//创建一个类LMFMD5
public String MD5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// 生成一个MD5加密计算摘要
md.update(sourceStr.getBytes());
// 使用指定的byte数组更新摘要
byte b[] = md.digest();
// 把密文转换成十六进制的字符串形式
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
System.out.println("MD5(" + sourceStr + ",32) = " + result);
// System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
// 注释的是md5的16位取值
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
}
package Practice_test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LMFMD5 {
//创建一个类LMFMD5
public String MD5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// 生成一个MD5加密计算摘要
md.update(sourceStr.getBytes());
// 使用指定的byte数组更新摘要
byte b[] = md.digest();
// 把密文转换成十六进制的字符串形式
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
System.out.println("MD5(" + sourceStr + ",32) = " + result);
// System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
// 注释的是md5的16位取值
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
}
package Practice_test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.offcn.TestUnti.ReadProperties;
public class MySqlUtil {
public static String sql;
public static Connection conn =null;
public static Statement stmt=null;
public static ResultSet result = null;
public static void main(String[] args) {
//update xyu.xyu_room set status=4 where room_num=201808310045;
// int a=updateOrderStatus("xyu.xyu_room","status=4", "room_num=201808310045");
// System.out.println(a);
select( " xyu_room " , " room_name = '中国特长房间名' ");
}
public static void closed(){
try {
result.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void select(String tableName, String condition){
//数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
// sql = "select * from " + " xyu_users;" ;
sql = "select * from " + tableName + " where " + condition;
System.out.println(sql);
// System.out.println("select_sql="+sql);
result = stmt.executeQuery(sql);
result.last();
System.out.println(result.getRow());
if (result.getRow() != 1) {
System.out.println(result.getRow());
} else{
// String act_idNo = String.valueOf(result.getString(result.findColumn("mobile")));
// System.out.println("name:"+act_idNo);
// String act_idNo = String.valueOf(rs_cust_info.getString(rs_cust_info.findColumn("id_no")));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
closed();
}
}
//更改表
public static Integer updateOrderStatus(String fromName,String setCondition, String whereCondition) {
Integer result1=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
String sql = "update "+ fromName +" set "+ setCondition +" where "+ whereCondition;
System.out.println(sql);
result1 = stmt.executeUpdate(sql);//
if (result1 == -1) {
System.out.println("update order states failed!");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("update order states failed!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}try {
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result1;
}
}
package Practice_test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.offcn.TestUnti.ReadProperties;
public class MySqlUtil {
public static String sql;
public static Connection conn =null;
public static Statement stmt=null;
public static ResultSet result = null;
public static void main(String[] args) {
//update xyu.xyu_room set status=4 where room_num=201808310045;
// int a=updateOrderStatus("xyu.xyu_room","status=4", "room_num=201808310045");
// System.out.println(a);
select( " xyu_room " , " room_name = '中国特长房间名' ");
}
public static void closed(){
try {
result.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void select(String tableName, String condition){
//数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
// sql = "select * from " + " xyu_users;" ;
sql = "select * from " + tableName + " where " + condition;
System.out.println(sql);
// System.out.println("select_sql="+sql);
result = stmt.executeQuery(sql);
result.last();
System.out.println(result.getRow());
if (result.getRow() != 1) {
System.out.println(result.getRow());
} else{
// String act_idNo = String.valueOf(result.getString(result.findColumn("mobile")));
// System.out.println("name:"+act_idNo);
// String act_idNo = String.valueOf(rs_cust_info.getString(rs_cust_info.findColumn("id_no")));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
closed();
}
}
//更改表
public static Integer updateOrderStatus(String fromName,String setCondition, String whereCondition) {
Integer result1=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
String sql = "update "+ fromName +" set "+ setCondition +" where "+ whereCondition;
System.out.println(sql);
result1 = stmt.executeUpdate(sql);//
if (result1 == -1) {
System.out.println("update order states failed!");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("update order states failed!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}try {
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result1;
}
}
package Practice_test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
public class OCRTest {
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "42d199bc0a50cd8e109ff880ecc444fe");
connection.setDoOutput(true);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// <pre name="code" class="java">
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("d:\\abc.jpg");
String imageBase = OCRTest.encodeImgageToBase64(file);
imageBase = imageBase.replaceAll("\r\n","");
imageBase = imageBase.replaceAll("\\+","%2B");
String httpUrl = "http://apis.baidu.com/apistore/idlocr/ocr";
String httpArg = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image="+imageBase;
String jsonResult = request(httpUrl, httpArg);
System.out.println("返回的结果--------->"+jsonResult);
}
// //Base64编解码
// private static String encodeTest(String str){
// Base64 base64 = new Base64();
// try {
// str = base64.encodeToString(str.getBytes("UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// System.out.println("Base64 编码后:"+str);
// return str;
// }
//
// private static void decodeTest(String str){
// Base64 base64 = new Base64();
// //str = Arrays.toString(Base64.decodeBase64(str));
// str = new String(Base64.decodeBase64(str));
// System.out.println("Base64 解码后:"+str);
// }
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();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
package Practice_test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
public class OCRTest {
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "42d199bc0a50cd8e109ff880ecc444fe");
connection.setDoOutput(true);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// <pre name="code" class="java">
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("d:\\abc.jpg");
String imageBase = OCRTest.encodeImgageToBase64(file);
imageBase = imageBase.replaceAll("\r\n","");
imageBase = imageBase.replaceAll("\\+","%2B");
String httpUrl = "http://apis.baidu.com/apistore/idlocr/ocr";
String httpArg = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image="+imageBase;
String jsonResult = request(httpUrl, httpArg);
System.out.println("返回的结果--------->"+jsonResult);
}
// //Base64编解码
// private static String encodeTest(String str){
// Base64 base64 = new Base64();
// try {
// str = base64.encodeToString(str.getBytes("UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// System.out.println("Base64 编码后:"+str);
// return str;
// }
//
// private static void decodeTest(String str){
// Base64 base64 = new Base64();
// //str = Arrays.toString(Base64.decodeBase64(str));
// str = new String(Base64.decodeBase64(str));
// System.out.println("Base64 解码后:"+str);
// }
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();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
}
\ No newline at end of file
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils2 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
ra.port = 8765;
ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils2 rdu=new RequestDataUtils2();
Response re=null;
String url="/v1/customer/photo/upload";
try{
File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
.header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
.multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.when()
.post(url+"?photoType=1&photoLocation=2&orderId=38858")
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils2 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
ra.port = 8765;
ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils2 rdu=new RequestDataUtils2();
Response re=null;
String url="/v1/customer/photo/upload";
try{
File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
.header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
.multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.when()
.post(url+"?photoType=1&photoLocation=2&orderId=38858")
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils3 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
// ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
// ra.port = 8765;
// ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils3 rdu=new RequestDataUtils3();
Response re=null; //{}
String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&:;\\|-+)(*~`.?^%$#@{[]><,card_no=qty50636&status=1";
// String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&':;\\|-+)(*~`{}[]><,.?^%$#@!card_no=qty50636&status=1";
Map<String,String> m=new HashMap<String,String>();
m.put("user_name", "ws63417");
m.put("password", "ws63417");
m.put("code", "7bcdc063c9ed80c9f9fee83f1101aaed");
try{
// File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
// .header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
// .multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.cookie("PHPSESSID","7nm2u0efp5leta3quif37dm6r4")
.get(url)
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils3 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
// ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
// ra.port = 8765;
// ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils3 rdu=new RequestDataUtils3();
Response re=null; //{}
String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&:;\\|-+)(*~`.?^%$#@{[]><,card_no=qty50636&status=1";
// String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&':;\\|-+)(*~`{}[]><,.?^%$#@!card_no=qty50636&status=1";
Map<String,String> m=new HashMap<String,String>();
m.put("user_name", "ws63417");
m.put("password", "ws63417");
m.put("code", "7bcdc063c9ed80c9f9fee83f1101aaed");
try{
// File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
// .header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
// .multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.cookie("PHPSESSID","7nm2u0efp5leta3quif37dm6r4")
.get(url)
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
/**
* 人工信审工具类
* @author puhui
*
*/
public class Rgxs{
// public String JSESSIONID;
// public String StatusCode;
// public String time;
public static void main(String[] args) {
Rgxs r=new Rgxs();
String JSESSIONID=r.getJSESSIONID();
r.login(JSESSIONID);
}
public String getJSESSIONID(){
String JSESSIONID;
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login?service=http://10.10.180.37:9092/cas-login";
String s="username=guanxin&password=123456&captcha=&lt=LT-91693-umbYEtmZoAIwfMz6DgJ4TYyMEdJuon-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().get();
Long end=System.currentTimeMillis();
JSESSIONID=re2.getHeader("Set-Cookie").split(";")[0];
System.out.println(JSESSIONID);
return JSESSIONID;
}
public String login(String JSESSIONID){
//登陆http://10.10.227.155:8092/puhui-cas/login;jsessionid=CB6D5A088E0131A8D3DBB4C09CF537EB?service=http://10.10.180.37:9092/cas-login&locale=zh_CN
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login;"+JSESSIONID+"?service=http://10.10.180.37:9092/cas-login&locale=zh_CN";
String Parameter="username=guanxin&password=123456&captcha=&lt=LT-95983-ZMh4JH2vw71sRMqERKcTOHGuiPDUtb-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", JSESSIONID,
"Referer","http://10.10.227.155:8092/puhui-cas/login?service=http://10.10.180.37:9092/cas-login",
"Origin","http://10.10.227.155:8092"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
System.out.println("第二步完成");
System.out.println(re2.getHeaders().toString());
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
return JSESSIONID;
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
/**
* 人工信审工具类
* @author puhui
*
*/
public class Rgxs{
// public String JSESSIONID;
// public String StatusCode;
// public String time;
public static void main(String[] args) {
Rgxs r=new Rgxs();
String JSESSIONID=r.getJSESSIONID();
r.login(JSESSIONID);
}
public String getJSESSIONID(){
String JSESSIONID;
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login?service=http://10.10.180.37:9092/cas-login";
String s="username=guanxin&password=123456&captcha=&lt=LT-91693-umbYEtmZoAIwfMz6DgJ4TYyMEdJuon-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().get();
Long end=System.currentTimeMillis();
JSESSIONID=re2.getHeader("Set-Cookie").split(";")[0];
System.out.println(JSESSIONID);
return JSESSIONID;
}
public String login(String JSESSIONID){
//登陆http://10.10.227.155:8092/puhui-cas/login;jsessionid=CB6D5A088E0131A8D3DBB4C09CF537EB?service=http://10.10.180.37:9092/cas-login&locale=zh_CN
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login;"+JSESSIONID+"?service=http://10.10.180.37:9092/cas-login&locale=zh_CN";
String Parameter="username=guanxin&password=123456&captcha=&lt=LT-95983-ZMh4JH2vw71sRMqERKcTOHGuiPDUtb-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", JSESSIONID,
"Referer","http://10.10.227.155:8092/puhui-cas/login?service=http://10.10.180.37:9092/cas-login",
"Origin","http://10.10.227.155:8092"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
System.out.println("第二步完成");
System.out.println(re2.getHeaders().toString());
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
return JSESSIONID;
}
}
package Practice_test;
public class Test_maxiao {
public static void main(String[] args) {
System.out.println(removeFourChar("えもじ,e-moji,moj"));
}
/**
* 替换四个字节的字符 '\xF0\x9F\x98\x84\xF0\x9F)的解决方案
*
* @param content
* @return
* @author 张栋
* @data 2015年8月11日 上午10:31:50
*/
public static String removeFourChar(String content) {
byte[] conbyte = content.getBytes();
System.out.println(conbyte[0]);
for (int i = 0; i < conbyte.length; i++) {
if ((conbyte[i] & 0xF8) == 0xF0) {
for (int j = 0; j < 4; j++) {
System.out.println("j="+j);
conbyte[i + j] = 0x30;
}
i += 3;
}
}
String contentnew = new String(conbyte);
return contentnew.replaceAll("0000", "");
}
}
package Practice_test;
public class Test_maxiao {
public static void main(String[] args) {
System.out.println(removeFourChar("えもじ,e-moji,moj"));
}
/**
* 替换四个字节的字符 '\xF0\x9F\x98\x84\xF0\x9F)的解决方案
*
* @param content
* @return
* @author 张栋
* @data 2015年8月11日 上午10:31:50
*/
public static String removeFourChar(String content) {
byte[] conbyte = content.getBytes();
System.out.println(conbyte[0]);
for (int i = 0; i < conbyte.length; i++) {
if ((conbyte[i] & 0xF8) == 0xF0) {
for (int j = 0; j < 4; j++) {
System.out.println("j="+j);
conbyte[i + j] = 0x30;
}
i += 3;
}
}
String contentnew = new String(conbyte);
return contentnew.replaceAll("0000", "");
}
}
package Practice_test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.offcn.TestUnti.MapUtil;
public class map_show {
public static void main(String[] args) throws Exception {
Map<String,String> map=new HashMap<String,String>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
System.out.println(showMap(map,"d"));
// String ss=show();//把map中parameter对应的内容拿出来
// String sss=getPhone(ss,"phone");//在parameter中查看,是否有关键字
// System.out.println("sss="+sss+"==");
// if(sss==null){
// System.out.println("等于空");
// }
// if(sss.equals("")){
// System.out.println("等于空字符串");
// }
}
//查找map中是否有这个建
public static boolean showMap(Map<String, String> data,String key){
Set<Map.Entry<String,String>> set=data.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Map.Entry<String,String> me=it.next();
if(me.getKey().equals(key)){
return true;
}
}
return false;
}
public static String getPhone(String parameter,String phone){
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(phone)){
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();
}
//查看二维数组
public static String show() throws Exception{
//查看二维数组
ReadExcels readExcels = new ReadExcels("DataAll.xls","TestCase");
Object[][] arrmap= readExcels.readExcels_return();
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();
}
// HashMap<String, Object> hm=new HashMap<String, Object>();
// hm=(HashMap<String, Object>) arrmap[0][0];
String s=MapUtil.getValue("parameter",(HashMap<String, Object>) arrmap[38][0]);
System.out.println("s="+s);
return s;
}
}
package Practice_test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.offcn.TestUnti.MapUtil;
public class map_show {
public static void main(String[] args) throws Exception {
Map<String,String> map=new HashMap<String,String>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
System.out.println(showMap(map,"d"));
// String ss=show();//把map中parameter对应的内容拿出来
// String sss=getPhone(ss,"phone");//在parameter中查看,是否有关键字
// System.out.println("sss="+sss+"==");
// if(sss==null){
// System.out.println("等于空");
// }
// if(sss.equals("")){
// System.out.println("等于空字符串");
// }
}
//查找map中是否有这个建
public static boolean showMap(Map<String, String> data,String key){
Set<Map.Entry<String,String>> set=data.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Map.Entry<String,String> me=it.next();
if(me.getKey().equals(key)){
return true;
}
}
return false;
}
public static String getPhone(String parameter,String phone){
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(phone)){
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();
}
//查看二维数组
public static String show() throws Exception{
//查看二维数组
ReadExcels readExcels = new ReadExcels("DataAll.xls","TestCase");
Object[][] arrmap= readExcels.readExcels_return();
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();
}
// HashMap<String, Object> hm=new HashMap<String, Object>();
// hm=(HashMap<String, Object>) arrmap[0][0];
String s=MapUtil.getValue("parameter",(HashMap<String, Object>) arrmap[38][0]);
System.out.println("s="+s);
return s;
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class maxiao implements Runnable{
public String JSESSIONID;
public String StatusCode;
public String time;
public maxiao(String jSESSIONID) {
JSESSIONID = jSESSIONID;
}
@Override
public void run() {
// RestAssured ra_VerifyCode = new RestAssured();
// ra_VerifyCode.baseURI = "http://10.10.197.245";
// ra_VerifyCode.port = 8888;
// ra_VerifyCode.basePath = "/puhui-lend-pre/page/lendRepay/repayList.jsp";
//
// Long start=System.currentTimeMillis();
// Response re2 = ra_VerifyCode.given().given().
// headers("Cookie", JSESSIONID,
// "Referer","http://10.10.197.245:8888/puhui-lend-pre/main",
// "Upgrade-Insecure-Requests","1"
// ).get();
// Long end=System.currentTimeMillis();
//
// time=(end-start)+"";
// System.out.println();
// StatusCode=re2.getStatusCode()+"";
// System.out.println(re2.getBody().asString());
// System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list ";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(JSON).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
time=(end-start)+"";
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
}
public static void main(String[] args) {
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body("billDate=2016-12-25&page=1&rows=20").when().post();
Long end=System.currentTimeMillis();
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class maxiao implements Runnable{
public String JSESSIONID;
public String StatusCode;
public String time;
public maxiao(String jSESSIONID) {
JSESSIONID = jSESSIONID;
}
@Override
public void run() {
// RestAssured ra_VerifyCode = new RestAssured();
// ra_VerifyCode.baseURI = "http://10.10.197.245";
// ra_VerifyCode.port = 8888;
// ra_VerifyCode.basePath = "/puhui-lend-pre/page/lendRepay/repayList.jsp";
//
// Long start=System.currentTimeMillis();
// Response re2 = ra_VerifyCode.given().given().
// headers("Cookie", JSESSIONID,
// "Referer","http://10.10.197.245:8888/puhui-lend-pre/main",
// "Upgrade-Insecure-Requests","1"
// ).get();
// Long end=System.currentTimeMillis();
//
// time=(end-start)+"";
// System.out.println();
// StatusCode=re2.getStatusCode()+"";
// System.out.println(re2.getBody().asString());
// System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list ";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(JSON).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
time=(end-start)+"";
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
}
public static void main(String[] args) {
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body("billDate=2016-12-25&page=1&rows=20").when().post();
Long end=System.currentTimeMillis();
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
}
}
package Practice_test;
import java.util.Arrays;
public class panduanshifushishuzi {
public static void main(String[] args) {
String p="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":codeown";
System.out.println(getChar(p,"verifyCode"));
}
//判断数字
public static void shuzipanduan(){
String str="12345uu7";
for (int i =0;i< str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
System.out.println(str.charAt(i));
}
}
}
//判断字母
public static String getChar(String parameter,String Letter){
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+1,str_strcomma.length()-1));
}
}
return sb.toString();
}
}
package Practice_test;
import java.util.Arrays;
public class panduanshifushishuzi {
public static void main(String[] args) {
String p="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":codeown";
System.out.println(getChar(p,"verifyCode"));
}
//判断数字
public static void shuzipanduan(){
String str="12345uu7";
for (int i =0;i< str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
System.out.println(str.charAt(i));
}
}
}
//判断字母
public static String getChar(String parameter,String Letter){
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+1,str_strcomma.length()-1));
}
}
return sb.toString();
}
}
package Practice_test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class properties_test {
public static void main(String[] args) throws Exception{
test3();
// ClearProperty();
}
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 void test3() throws Exception{
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
System.out.println(prop.isEmpty());
fis.close();// 关闭流
}
public static void test2() throws Exception {
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
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("password", "heihei");
// 文件输出流
FileOutputStream fos = new FileOutputStream("src/resources/information.properties");
// 将Properties集合保存到流中
prop.store(fos, "Copyright (c) Boxcode Studio");
fos.close();// 关闭流
System.out.println("获取修改后的属性值:password=" + prop.getProperty("password"));
}
public static String test1(){
Properties prop = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"xyzb.properties";
FileOutputStream oFile = new FileOutputStream(sourceFile, true);//true表示追加打开
prop.setProperty("phone", "10086");
prop.store(oFile, "The New properties file");
oFile.close();
return "";
}catch (IOException e) {
return null;
}
}
}
package Practice_test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class properties_test {
public static void main(String[] args) throws Exception{
test3();
// ClearProperty();
}
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 void test3() throws Exception{
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
System.out.println(prop.isEmpty());
fis.close();// 关闭流
}
public static void test2() throws Exception {
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
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("password", "heihei");
// 文件输出流
FileOutputStream fos = new FileOutputStream("src/resources/information.properties");
// 将Properties集合保存到流中
prop.store(fos, "Copyright (c) Boxcode Studio");
fos.close();// 关闭流
System.out.println("获取修改后的属性值:password=" + prop.getProperty("password"));
}
public static String test1(){
Properties prop = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"xyzb.properties";
FileOutputStream oFile = new FileOutputStream(sourceFile, true);//true表示追加打开
prop.setProperty("phone", "10086");
prop.store(oFile, "The New properties file");
oFile.close();
return "";
}catch (IOException e) {
return null;
}
}
}
package Practice_test;
import java.util.Iterator;
import java.util.Set;
import com.beust.jcommander.Parameter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class t1 {
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();
}
public static void main(String[] args) {
String parameter = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo4NTgxOCwiYXJlYV9jb2RlIjoiODYiLCJwaG9uZSI6IjE4MzM5OTcwOTI1IiwiY3JlYXRlX3RpbWUiOjE1NDMxOTYyMjIsInVwZGF0ZV90aW1lIjoxNTQ1MDI1Mjk0LCJzeXN0ZW0iOiJCTEEtQUwwMEhVQVdFSSIsInBsYXRmb3JtIjoiQW5kcm9pZCIsImlwIjoiNjEuMTQ5LjIwLjExNCIsInZlcnNpb24iOiIxIiwiZGV2aWNlX2lkIjoiODY2MjE3MDM3MjkxNzk5IiwicGFzc3dkIjoiM2I1MDY1ZGRiYzhiMWRjMDM2ZmZkMzg4NDYzZTRlYmIiLCJuaWNrbmFtZSI6Ilx1OTUyNi4iLCJhdmF0YXIiOiJodHRwOlwvXC90aGlyZHFxLnFsb2dvLmNuXC9xcWFwcFwvMTEwNjc3MzY4MVwvNjFDQkEwNzhBMTdCMjVERjk4MENEMDFBMjNGQjdBNDZcLzEwMCIsImdlbmRlciI6ImYiLCJxcV9pZCI6IjYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2Iiwid2VpYm9faWQiOiIiLCJ3ZWl4aW5faWQiOiIiLCJ1bmlvbl9pZCI6IiIsIndlaWJvX25pY2tuYW1lIjoiIiwicXFfbmlja25hbWUiOiJcdTk1MjYuIiwid2VpeGluX25pY2tuYW1lIjoiIiwid2VpYm9fYXZhdGFyIjoiIiwicXFfYXZhdGFyIjoiaHR0cDpcL1wvdGhpcmRxcS5xbG9nby5jblwvcXFhcHBcLzExMDY3NzM2ODFcLzYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2XC8xMDAiLCJ3ZWl4aW5fYXZhdGFyIjoiIiwibG9naW5fdHlwZSI6InFxIiwicGhvbmVfbmFtZSI6IiIsInBob25lX2F2YXRhciI6IiIsInN0b3JlIjoib2ZmY24iLCJpZl9kZWxldGUiOjAsImV4YW1faWQiOjcxLCJpdGVtX2lkIjoxMTIsImV4YW1fYXJlYSI6Ilx1NTZmZFx1NWJiNlx1NTE2Y1x1NTJhMVx1NTQ1OFx1ODAwM1x1OGJkNSIsImlhdCI6MTU0NTAyNTMwMCwibmJmIjoxNTQ1MDI1MzAwLCJleHAiOjE1NzY1NjEzMDB9.Y-6ZSY2Tqr8xdIvKR4ThenzYt17-0vFMBN3RBFATmj8";
String sb = killQuotes(parameter, "\"");
System.out.println(sb);
/*
String str="{\"houseBasicInfo\": {\"address\": \"***&*&*&87\",\"area\": \"北京市\",\"cardPic\": \"cardpiccardpiccardpic\",\"city\": \"北京市\",\"contract\": \"contract\",\"contractNo\": \"100000004\",\"idNo\": \"11022119811222061X\",\"name\": \"姚帅\",\"payAmount\": 10000,\"phone\": \"13910960649\",\"rentBegin\": \"2017-07-21\",\"rentEnd\": \"2018-07-21\",\"rental\": 5000,\"rentalType\": 1,\"roomId\": \"11\",\"roomNum\": \"1101室\",\"suiteId\": \"111\",\"termNum\": 12,\"thirdUserId\": \"1\",\"timeStamp\": \"123123123\"},\"merchantName\": \"蛋壳第一商户\",\"receiveContractInfo\": {\"area\": \"北京\",\"attachment\": \"attachment\",\"city\": \"北京\",\"contractNo\": \"0000001231231231\",\"endTime\": \"2017-07-21\",\"personIdNo\": \"110102198907132328\",\"personName\": \"小五\",\"rentalAddress\": \"北京市朝阳区银河SOHO1101室\",\"startTime\": \"2018-07-21\",\"subCompany\": \"蛋壳租房\"},\"source\": 0}";
JSONObject jo = JSONObject.fromObject(str);
System.out.println(jo.getString("houseBasicInfo"));
JSONObject j1 = JSONObject.fromObject(jo.getString("houseBasicInfo"));
System.out.println(j1.getString("address"));
System.out.println(j1.getString("area"));
System.out.println(j1.getString("cardPic"));
System.out.println("====================================");
System.out.println(jo.getString("merchantName"));
System.out.println(jo.getString("receiveContractInfo"));
System.out.println(jo.getString("source"));*/
// Iterator it=jo.keys();
// String key=null;
// String value=null;
// while(it.hasNext()){
// key=(String)it.next();
// value=jo.getString(key);
// System.out.println(value);
// }
// JSONObject obj = JSONObject.fromObject(str);
// String showapi=obj.getString("showapi_res_body");
// JSONObject obj1 = JSONObject.fromObject(showapi);
// System.out.println(obj1.get("Result"));
// JSONArray transitListArray = obj.getJSONArray("showapi_res_body");
// System.out.println(transitListArray.getString("Result"));
// for (int i = 0; i < transitListArray.size(); i++) {
// System.out.print("Array:" + transitListArray.getString(i) + " ");
// }
// System.out.println(jo.getString("Result"));
// System.out.println(jo.get("list"));
// JSONObject jo1 = (JSONObject)jo.get("list");
// System.out.println(jo1.get("phone"));
}
}
package Practice_test;
import java.util.Iterator;
import java.util.Set;
import com.beust.jcommander.Parameter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class t1 {
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();
}
public static void main(String[] args) {
String parameter = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo4NTgxOCwiYXJlYV9jb2RlIjoiODYiLCJwaG9uZSI6IjE4MzM5OTcwOTI1IiwiY3JlYXRlX3RpbWUiOjE1NDMxOTYyMjIsInVwZGF0ZV90aW1lIjoxNTQ1MDI1Mjk0LCJzeXN0ZW0iOiJCTEEtQUwwMEhVQVdFSSIsInBsYXRmb3JtIjoiQW5kcm9pZCIsImlwIjoiNjEuMTQ5LjIwLjExNCIsInZlcnNpb24iOiIxIiwiZGV2aWNlX2lkIjoiODY2MjE3MDM3MjkxNzk5IiwicGFzc3dkIjoiM2I1MDY1ZGRiYzhiMWRjMDM2ZmZkMzg4NDYzZTRlYmIiLCJuaWNrbmFtZSI6Ilx1OTUyNi4iLCJhdmF0YXIiOiJodHRwOlwvXC90aGlyZHFxLnFsb2dvLmNuXC9xcWFwcFwvMTEwNjc3MzY4MVwvNjFDQkEwNzhBMTdCMjVERjk4MENEMDFBMjNGQjdBNDZcLzEwMCIsImdlbmRlciI6ImYiLCJxcV9pZCI6IjYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2Iiwid2VpYm9faWQiOiIiLCJ3ZWl4aW5faWQiOiIiLCJ1bmlvbl9pZCI6IiIsIndlaWJvX25pY2tuYW1lIjoiIiwicXFfbmlja25hbWUiOiJcdTk1MjYuIiwid2VpeGluX25pY2tuYW1lIjoiIiwid2VpYm9fYXZhdGFyIjoiIiwicXFfYXZhdGFyIjoiaHR0cDpcL1wvdGhpcmRxcS5xbG9nby5jblwvcXFhcHBcLzExMDY3NzM2ODFcLzYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2XC8xMDAiLCJ3ZWl4aW5fYXZhdGFyIjoiIiwibG9naW5fdHlwZSI6InFxIiwicGhvbmVfbmFtZSI6IiIsInBob25lX2F2YXRhciI6IiIsInN0b3JlIjoib2ZmY24iLCJpZl9kZWxldGUiOjAsImV4YW1faWQiOjcxLCJpdGVtX2lkIjoxMTIsImV4YW1fYXJlYSI6Ilx1NTZmZFx1NWJiNlx1NTE2Y1x1NTJhMVx1NTQ1OFx1ODAwM1x1OGJkNSIsImlhdCI6MTU0NTAyNTMwMCwibmJmIjoxNTQ1MDI1MzAwLCJleHAiOjE1NzY1NjEzMDB9.Y-6ZSY2Tqr8xdIvKR4ThenzYt17-0vFMBN3RBFATmj8";
String sb = killQuotes(parameter, "\"");
System.out.println(sb);
/*
String str="{\"houseBasicInfo\": {\"address\": \"***&*&*&87\",\"area\": \"北京市\",\"cardPic\": \"cardpiccardpiccardpic\",\"city\": \"北京市\",\"contract\": \"contract\",\"contractNo\": \"100000004\",\"idNo\": \"11022119811222061X\",\"name\": \"姚帅\",\"payAmount\": 10000,\"phone\": \"13910960649\",\"rentBegin\": \"2017-07-21\",\"rentEnd\": \"2018-07-21\",\"rental\": 5000,\"rentalType\": 1,\"roomId\": \"11\",\"roomNum\": \"1101室\",\"suiteId\": \"111\",\"termNum\": 12,\"thirdUserId\": \"1\",\"timeStamp\": \"123123123\"},\"merchantName\": \"蛋壳第一商户\",\"receiveContractInfo\": {\"area\": \"北京\",\"attachment\": \"attachment\",\"city\": \"北京\",\"contractNo\": \"0000001231231231\",\"endTime\": \"2017-07-21\",\"personIdNo\": \"110102198907132328\",\"personName\": \"小五\",\"rentalAddress\": \"北京市朝阳区银河SOHO1101室\",\"startTime\": \"2018-07-21\",\"subCompany\": \"蛋壳租房\"},\"source\": 0}";
JSONObject jo = JSONObject.fromObject(str);
System.out.println(jo.getString("houseBasicInfo"));
JSONObject j1 = JSONObject.fromObject(jo.getString("houseBasicInfo"));
System.out.println(j1.getString("address"));
System.out.println(j1.getString("area"));
System.out.println(j1.getString("cardPic"));
System.out.println("====================================");
System.out.println(jo.getString("merchantName"));
System.out.println(jo.getString("receiveContractInfo"));
System.out.println(jo.getString("source"));*/
// Iterator it=jo.keys();
// String key=null;
// String value=null;
// while(it.hasNext()){
// key=(String)it.next();
// value=jo.getString(key);
// System.out.println(value);
// }
// JSONObject obj = JSONObject.fromObject(str);
// String showapi=obj.getString("showapi_res_body");
// JSONObject obj1 = JSONObject.fromObject(showapi);
// System.out.println(obj1.get("Result"));
// JSONArray transitListArray = obj.getJSONArray("showapi_res_body");
// System.out.println(transitListArray.getString("Result"));
// for (int i = 0; i < transitListArray.size(); i++) {
// System.out.print("Array:" + transitListArray.getString(i) + " ");
// }
// System.out.println(jo.getString("Result"));
// System.out.println(jo.get("list"));
// JSONObject jo1 = (JSONObject)jo.get("list");
// System.out.println(jo1.get("phone"));
}
}
package Practice_test;
import java.util.Arrays;
public class test {
public static void main (String[] args) {
String res1 = "page=1&size=10&username=code&phone=code&card_no=code&status=1";
String sss=getParameter_get(res1,"size");
System.out.println(sss);
}
//在parameter中获取get请求中的参数
public static String getParameter_get(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=strcomma[k];
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf('=');
sb.append(str_strcomma.substring(start+1,str_strcomma.length()));
return sb.toString();
}
}
return sb.toString();
}
}
package Practice_test;
import java.util.Arrays;
public class test {
public static void main (String[] args) {
String res1 = "page=1&size=10&username=code&phone=code&card_no=code&status=1";
String sss=getParameter_get(res1,"size");
System.out.println(sss);
}
//在parameter中获取get请求中的参数
public static String getParameter_get(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=strcomma[k];
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf('=');
sb.append(str_strcomma.substring(start+1,str_strcomma.length()));
return sb.toString();
}
}
return sb.toString();
}
}
package Practice_test;
import java.text.SimpleDateFormat;
import java.util.Random;
import sun.net.www.http.HttpClient;
public class test1 {
public static void main(String[] args) {
String a1=null;
String a2="";
if("0".equals(a1)){
System.out.println(1);
}else{
System.out.println(2);
}
}
}
//SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
//String dateStr = dateformat.format(System.currentTimeMillis());
//System.out.println(dateStr);
//System.out.println(new Random().nextInt(90000000)+ 10000000);
package Practice_test;
import java.text.SimpleDateFormat;
import java.util.Random;
import sun.net.www.http.HttpClient;
public class test1 {
public static void main(String[] args) {
String a1=null;
String a2="";
if("0".equals(a1)){
System.out.println(1);
}else{
System.out.println(2);
}
}
}
//SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
//String dateStr = dateformat.format(System.currentTimeMillis());
//System.out.println(dateStr);
//System.out.println(new Random().nextInt(90000000)+ 10000000);
package Practice_test;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class testng1 {
@DataProvider(name = "user")
public Object[][] createUser(Method m) {
System.out.println(m.getName());
return new Object[][] { { "root", "root" }, { "test", "root" }, };
}
@Test(groups = "login", dependsOnGroups = "launch", dataProvider = "user")
public void verifyUser(String username, String password) {
System.out.println("Verify User : " + username + ":" + password);
assert username.equals(password);
}
}
package Practice_test;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class testng1 {
@DataProvider(name = "user")
public Object[][] createUser(Method m) {
System.out.println(m.getName());
return new Object[][] { { "root", "root" }, { "test", "root" }, };
}
@Test(groups = "login", dependsOnGroups = "launch", dataProvider = "user")
public void verifyUser(String username, String password) {
System.out.println("Verify User : " + username + ":" + password);
assert username.equals(password);
}
}
package Practice_test;
import com.offcn.TestUnti.MyDateUtil;
public class time_test {
public static void main(String[] args) {
System.out.println("rile1111222");
System.out.println(MyDateUtil.getTime(0, -10, 0));
}
}
package Practice_test;
import com.offcn.TestUnti.MyDateUtil;
public class time_test {
public static void main(String[] args) {
System.out.println("rile1111222");
System.out.println(MyDateUtil.getTime(0, -10, 0));
}
}
package Practice_test;
import net.sf.json.JSONObject;
import com.offcn.TestUnti.SheetUtils;
import com.offcn.TestUnti.StringUtils;
public class w_excel {
public static void main(String[] args) {
SheetUtils sheet = new SheetUtils("a1.xls", "Output");
sheet.writeExcel(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
);
}
}
package Practice_test;
import net.sf.json.JSONObject;
import com.offcn.TestUnti.SheetUtils;
import com.offcn.TestUnti.StringUtils;
public class w_excel {
public static void main(String[] args) {
SheetUtils sheet = new SheetUtils("a1.xls", "Output");
sheet.writeExcel(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
);
}
}
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.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.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 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;
import com.offcn.TestUnti.ReadProperties;
public class offcn_api_testData {
@DataProvider(name="renmai")
public static Object[][] dp(){
String xls=ReadProperties.GetTestPropertyByKey("xls");
String sheet=ReadProperties.GetTestPropertyByKey("sheet");
ReadExcels readExcels = new ReadExcels(xls,sheet);
try {
return readExcels.readExcels_return();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.offcn.TestData;
import org.testng.annotations.DataProvider;
import com.offcn.TestUnti.ReadExcels;
import com.offcn.TestUnti.ReadProperties;
public class offcn_api_testData {
@DataProvider(name="renmai")
public static Object[][] dp(){
String xls=ReadProperties.GetTestPropertyByKey("xls");
String sheet=ReadProperties.GetTestPropertyByKey("sheet");
ReadExcels readExcels = new ReadExcels(xls,sheet);
try {
return readExcels.readExcels_return();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
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 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 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.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.json.JSONObject;
public class ListUtil {
public static void main(String[] args) {
// HashMap<String, Object> newhm=Expect(hm);
// System.out.println("@AfterClass_data_ext="+JSONObject.fromObject(newhm).toString());
}
//此方法获取首位和非首位数值,CornerMark=0返回首位,CornerMark!=0返回非首位
public static String getListValue(List<String> list, int CornerMark){
if(list.size()>CornerMark){
return list.get(list.size()-1);
}else{
return "";
}
}
//清除list第一个位置
public static List<String> cleann_no_List(List<String> list) {
if(list.size()>0){
list.remove(0);
}
return list;
}
}
package com.offcn.TestUnti;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sf.json.JSONObject;
public class ListUtil {
public static void main(String[] args) {
// HashMap<String, Object> newhm=Expect(hm);
// System.out.println("@AfterClass_data_ext="+JSONObject.fromObject(newhm).toString());
}
//此方法获取首位和非首位数值,CornerMark=0返回首位,CornerMark!=0返回非首位
public static String getListValue(List<String> list, int CornerMark){
if(list.size()>CornerMark){
return list.get(list.size()-1);
}else{
return "";
}
}
//清除list第一个位置
public static List<String> cleann_no_List(List<String> list) {
if(list.size()>0){
list.remove(0);
}
return list;
}
}
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;
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("appid=tiku&nickname=wangzhipeng&user_id=16&123456"));
}
}
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("appid=tiku&nickname=wangzhipeng&user_id=16&123456"));
}
}
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 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 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.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.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
}
//将JDBC ResultSet结果集转成List
public static List<Map<String, Object>> ResultSetToList(ResultSet rs) throws Exception {
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
int columnCount = md.getColumnCount(); //获得列数
while (rs.next()) {
Map<String,Object> rowData = new HashMap<String,Object>();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}
}
package com.offcn.TestUnti;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
}
//将JDBC ResultSet结果集转成List
public static List<Map<String, Object>> ResultSetToList(ResultSet rs) throws Exception {
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
int columnCount = md.getColumnCount(); //获得列数
while (rs.next()) {
Map<String,Object> rowData = new HashMap<String,Object>();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}
}
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.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.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.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadHtml {
public static void main(String[] args) {
try {
readFile_("overview.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String readFile_(String htmlfilename)throws IOException{
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"test-output"+File.separator+"html"+File.separator+htmlfilename;
FileInputStream fis = new FileInputStream(sourceFile);
byte[] buf = new byte[1024];
int len = 0;
StringBuffer sb=new StringBuffer();
while((len=fis.read(buf))!=-1)
{
sb.append(new String(buf,0,len));
// System.out.println(new String(buf,0,len));
}
fis.close();
// System.out.println(sb);
return sb.toString();
}
}
package com.offcn.TestUnti;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadHtml {
public static void main(String[] args) {
try {
readFile_("overview.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String readFile_(String htmlfilename)throws IOException{
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"test-output"+File.separator+"html"+File.separator+htmlfilename;
FileInputStream fis = new FileInputStream(sourceFile);
byte[] buf = new byte[1024];
int len = 0;
StringBuffer sb=new StringBuffer();
while((len=fis.read(buf))!=-1)
{
sb.append(new String(buf,0,len));
// System.out.println(new String(buf,0,len));
}
fis.close();
// System.out.println(sb);
return sb.toString();
}
}
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 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);
// classRoute=StringUtils.getPathName(classRoute);
ClassName=classRoute+"process."+CalssName_new;
// 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){
Log.logError("Reflect_api,ReflexClass Error,Classname=" + ClassName);
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("study".equals(system)){
String classReflectName = ReadProperties.GetPropertyByClassName(serviceUrl);
if ( classReflectName!=null ) {
return classRoute+ classReflectName;
}
}
return classRoute+CalssName;
}
}
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);
// classRoute=StringUtils.getPathName(classRoute);
ClassName=classRoute+"process."+CalssName_new;
// 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){
Log.logError("Reflect_api,ReflexClass Error,Classname=" + ClassName);
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("study".equals(system)){
String classReflectName = ReadProperties.GetPropertyByClassName(serviceUrl);
if ( classReflectName!=null ) {
return classRoute+ classReflectName;
}
}
return classRoute+CalssName;
}
}
package com.offcn.TestUnti;
import java.util.ArrayList;
public class StringUtils {
public static void main(String[] args) {
String str="\\u623f\\u95f4\\u53e3\\u4ee4\\u751f\\u6210\\u5931\\u8d25";
System.out.println(decodeUnicode(str));
}
public static String getPathName(String path){
String p=path.substring(0, path.length()-2);
int end=p.lastIndexOf(".");
p=p.substring(0, end+1);
return p;
}
//字符串按符号分隔
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;
if(theString==null){
return "";
}
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.util.ArrayList;
public class StringUtils {
public static void main(String[] args) {
String str="\\u623f\\u95f4\\u53e3\\u4ee4\\u751f\\u6210\\u5931\\u8d25";
System.out.println(decodeUnicode(str));
}
public static String getPathName(String path){
String p=path.substring(0, path.length()-2);
int end=p.lastIndexOf(".");
p=p.substring(0, end+1);
return p;
}
//字符串按符号分隔
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;
if(theString==null){
return "";
}
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();
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
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