当前位置:   article > 正文

testng框架优化+centos服务器下搭建java自动化环境(centos8.5)_远程testng

远程testng

前2篇见

httpclient+testng接口自动化整体框架设计

httpclient+testng接口自动化框架二次封装Java

总站在黑盒的角度提需求提问题谁都会,要能写出代码解决才是真正的会。高T不会写代码???

推荐巨好的网址:maven中央仓库 

https://mvnrepository.com/
 

服务器自动化结果地址

http://10.xx.xx.xx/testresultHtml/tcicommon430_autoRun.html

2022.8.3 每次存储自动化测试报告的运行结果 最新的报告单独存储 发邮箱

修改CaseUtil类

  1. // 20220703存入case运行的html结果
  2. String writetoHtml = pathAll + "testresultHtml/" + genedReportName + ".html";
  3. //20220802 把测试报告放到每次运行的jobid文件夹下
  4. String writetoHtmlnew = pathAll + "testresultHtml/every/" + DictGene.dictGene(job_id) + "/" + genedReportName + ".html";
  5. // 48开会讨论保留历史报告,加时间戳
  6. // String writetoHtml = "testresultHtml/" + TimeTransfer.TimeStamp2Date(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "_" + genedReportName + ".html";
  7. ReportUtil report = new ReportUtil(writetoHtml);
  8. ReportUtil reportnew = new ReportUtil(writetoHtmlnew);
  9. // 20220802新增 保留2份测试报告
  10. reportnew.head(genedReportName, usedTime, caseArray.length, pass, ignore);
  11. reportnew.sb.append(caselog.toString());
  12. reportnew.end();

新增类:每次运行自动化,在测试报告html文件夹下生成唯一的jobid文件夹,在自动化报告历史记录展示时,根据数据库的jobid创建时间去拼url路径 获取报告

  1. package com.httpclient.fileOperate;
  2. import com.interfaceframe.util.RandomJobid;
  3. import java.io.File;
  4. public class DictGene {
  5. public static String dictGene(String jobid) {
  6. // 本地路径
  7. String pathAll = "/Users/qa/Desktop/2021/code/cloudtestng/src/main/java/";
  8. // 远程服务器路径
  9. // String pathAll = "/www/data/cloudtestng/src/main/java/";
  10. String jobidHtml = pathAll + "testresultHtml/every/";
  11. try {
  12. File file = new File(jobidHtml, jobid);
  13. if (!file.exists()) {
  14. file.mkdir();
  15. System.out.println("创建jobid文件夹成功");
  16. }
  17. } catch (RuntimeException e) {
  18. throw new RuntimeException(e);
  19. }
  20. return jobid;
  21. }
  22. public static void dictGene() {
  23. // 本地路径
  24. String pathAll = "/Users/qa/Desktop/2021/code/cloudtestng/src/main/java/";
  25. // 远程服务器路径
  26. // String pathAll = "/www/data/cloudtestng/src/main/java/";
  27. String jobidHtml = pathAll + "testresultHtml/";
  28. try {
  29. File file = new File(jobidHtml, RandomJobid.getId());
  30. if (!file.exists()) {
  31. file.mkdir();
  32. System.out.println("创建jobid文件夹成功");
  33. }
  34. } catch (RuntimeException e) {
  35. throw new RuntimeException(e);
  36. }
  37. }
  38. public static void main(String[] args) {
  39. dictGene();
  40. }
  41. }

2022.8.1 java使用javax.mail向公司内部outlook发送邮箱完整代码

  1. package com.interfaceframe.mail;
  2. import com.interfaceframe.util.TimeTransfer;
  3. import javax.activation.DataHandler;
  4. import javax.mail.*;
  5. import javax.mail.internet.InternetAddress;
  6. import javax.mail.internet.MimeBodyPart;
  7. import javax.mail.internet.MimeMessage;
  8. import javax.mail.internet.MimeMultipart;
  9. import javax.mail.util.ByteArrayDataSource;
  10. import java.io.*;
  11. import java.util.Properties;
  12. public class SendSMTPMail {
  13. /**
  14. * 读取本地html文件里的html代码
  15. * 20220719
  16. *
  17. * @return
  18. */
  19. public static String toHtmlString(File file) {
  20. // 获取HTML文件流
  21. StringBuffer htmlSb = new StringBuffer();
  22. try {
  23. BufferedReader br = new BufferedReader(new InputStreamReader(
  24. new FileInputStream(file), "utf-8"));
  25. while (br.ready()) {
  26. htmlSb.append(br.readLine());
  27. }
  28. br.close();
  29. // 删除临时文件
  30. //file.delete();
  31. } catch (FileNotFoundException e) {
  32. e.printStackTrace();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. // HTML文件字符串
  37. String htmlStr = htmlSb.toString();
  38. // 返回经过清洁的html文本
  39. return htmlStr;
  40. }
  41. // public static void main(String[] args) {
  42. public static void sendMail() {
  43. String to = "xx@xx.com";
  44. // 发件人邮箱,不需要改动
  45. String from = "cloudtest@xx.com";
  46. final String username = "xx";//change accordingly
  47. final String password = "xx";//change accordingly
  48. // 注册好的公司的邮件服务,不需要改动
  49. String host = "smtpinternal.xx.com";
  50. Properties props = new Properties();
  51. props.put("mail.smtp.auth", "true");
  52. props.put("mail.smtp.starttls.enable", "true");
  53. props.put("mail.smtp.host", host);
  54. props.put("mail.smtp.port", "25");
  55. // ehlo被设置为false的时候连接邮件服务器不需要验证
  56. props.setProperty("mail.smtp.ehlo", "false");
  57. Session session = Session.getInstance(props,
  58. new javax.mail.Authenticator() {
  59. protected PasswordAuthentication getPasswordAuthentication() {
  60. return new PasswordAuthentication(username, password);
  61. }
  62. });
  63. try {
  64. // 创建一个默认的message对象
  65. Message message = new MimeMessage(session);
  66. // 设置头部信息
  67. message.setFrom(new InternetAddress(from));
  68. // 设置发件人信息
  69. message.setFrom(new InternetAddress(from));
  70. // 发送给
  71. message.setRecipients(Message.RecipientType.TO,
  72. InternetAddress.parse(to));
  73. // 抄送给
  74. // String[] cclist = {"xx@xx.com","xx@xx.com", "xx@xx.com"};
  75. String[] cclist = {"xx@xx.com", "xx@xx.com"};
  76. if (cclist.length > 0) {
  77. // 遍历抄送人
  78. Address[] addressCC = new InternetAddress[cclist.length];
  79. for (int j = 0; j < cclist.length; j++) {
  80. addressCC[j] = new InternetAddress(cclist[j]);
  81. }
  82. message.setRecipients(Message.RecipientType.CC, addressCC);
  83. }
  84. // 设置邮件主题
  85. String title = "[hce430 API Report] Build Version: hce430_" + TimeTransfer.TimeStamp2Date();
  86. message.setSubject(title);
  87. // 本地服务器html路径
  88. // String reportPath = "/Users/qa/Desktop/2021/code/cloudtestng/src/main/java/testresultHtml/tcicommon430_autoRun.html";
  89. // 远程服务器html路径
  90. String reportPath = "/www/data/cloudtestng/src/main/java/testresultHtml/hcecommon430_autoRun.html";
  91. //读取.html文件为字符串
  92. String htmlStr = toHtmlString(new File(reportPath));
  93. String url = "http://10.121.216.37/testresultHtml/hcecommon430_autoRun.html";
  94. String mailContent = "Dear ALL," +
  95. "\n" +
  96. "\n" +
  97. "\tPlease find hce430 automation test report for this build : hce430_" + TimeTransfer.TimeStamp2Date() + " below.\n" +
  98. "\n" +
  99. "\tURL:" + url +
  100. "\n" +
  101. "\n" +
  102. "\thce430 Automation Test Summary";
  103. // String mailContent="<html>\n" +
  104. // "<head>\n" +
  105. // "<meta charset=\"utf-8\">\n" +
  106. // "<title>JOB REPORT</title>\n" +
  107. // "</head>\n" +
  108. // "<body>\n" +
  109. // "\n" +
  110. // "<h3>Please find hce650 Automation API Test Result</h3>\n" +
  111. // " <h4 >Summary</h4>\n" +
  112. // " <table border=\"1\">\n" +
  113. // " % for product_version, casename, result, passed, failed, errors, test_total_time, time_start, time_end, logdir in items:\n" +
  114. // " <tr>\n" +
  115. // " <td>Product Version</td><td><tt>{{product_version}}</tt></td>\n" +
  116. // " </tr>\n" +
  117. // " <tr>\n" +
  118. // " <td>Test Plan Name</td><td><tt>{{casename}}</tt></td>\n" +
  119. // " </tr>\n" +
  120. // " <tr>\n" +
  121. // " <td>Result</td><td><tt>{{result}} (Passed: {{passed}}; Failed: {{failed}}; Errors: {{errors}})</tt></td>\n" +
  122. // " </tr>\n" +
  123. // " <tr>\n" +
  124. // " <td>Start Time</td><td><tt>{{time_start}}</tt></td>\n" +
  125. // " </tr>\n" +
  126. // " <tr>\n" +
  127. // " <td>End Time</td><td><tt>{{time_end}}</tt></td>\n" +
  128. // " </tr>\n" +
  129. // " <tr>\n" +
  130. // " <td>Cumulative Time</td><td><tt>{{test_total_time}}</tt></td>\n" +
  131. // " </tr>\n" +
  132. // " <tr>\n" +
  133. // " <td>Result Link</td><td><tt>{{url}}</tt></td>\n" +
  134. // " </tr>\n" +
  135. // " %end\n" +
  136. // " </table>\n" +
  137. // " </html>";
  138. // alternative
  139. MimeMultipart content = new MimeMultipart("multipart_subtype_alternative");
  140. MimeBodyPart text = new MimeBodyPart();
  141. MimeBodyPart html = new MimeBodyPart();
  142. html.setHeader("MIME-Version", "1.0");
  143. html.setHeader("Content-Type", html.getContentType());
  144. html.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlStr, "text/html; charset=utf-8")));
  145. text.setText(mailContent);
  146. text.setHeader("MIME-Version", "1.0");
  147. text.setHeader("Content-Type", text.getContentType());
  148. content.addBodyPart(text, 0);
  149. content.addBodyPart(html, 1);
  150. message.setContent(content);
  151. // 发送邮件
  152. Transport.send(message);
  153. System.err.println("---------------发送邮件成功 successfully---------------");
  154. } catch (MessagingException e) {
  155. throw new RuntimeException(e);
  156. } catch (IOException e) {
  157. throw new RuntimeException(e);
  158. }
  159. }
  160. }

2022.7.11-7.12 java使用javax.mail向公司内部outlook发送邮箱

第一步,申请邮箱smtp服务,走工单申请--SMTP Service 需要把开发服务器ip添加上

本地无法像outlook发邮件

第二步,审批通过,在开发服务器执行安装telnet

telnet smtpinternal.xx.com 25

执行 cd /www/data

python3 mail_utils.py 查看outlook收到邮件

邮箱错误状态码

SMTP 发送邮件错误码和解决方法

如遇

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo false, useAuth true
DEBUG SMTP: trying to connect to host "smtpinternal.xx.com", port 25, isSSL false
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtpinternal.xx.com, 25; timeout -1;
  nested exception is:

解决办法:在开发服务器运行成功,在本地运行失败

如遇

DEBUG SMTP: IOException while sending, closing, THROW:

java.io.IOException: No MimeBodyPart content

at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:116)

at javax.activation.DataHandler.writeTo(DataHandler.java:305)

javax.mail.MessagingException: IOException while sending message;

  nested exception is:

java.io.IOException: No MimeBodyPart content

发送失败

解决办法:换个代码写法 参考

发送简单邮件(Send simple email)_学习JavaMail API|WIKI教程


如遇

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo false, useAuth true
DEBUG SMTP: trying to connect to host "smtpinternal.xx.com", port 25, isSSL false
220 peklppfpool2.xx.com ESMTP xx

, For Authorized Business Use Only
DEBUG SMTP: connected to host "smtpinternal.xx.com", port: 25
HELO localhost
250 peklppfpool2.xx.com
DEBUG SMTP: use8bit false
MAIL FROM:<cloudtest@xx.com>
250 2.1.0 Ok
RCPT TO:<receiver@xx.com>
554 5.7.1 <unknown[10.xx.xx.xx]>: Client host rejected: Access denied
DEBUG SMTP: Invalid Addresses
DEBUG SMTP:   receiver@xx.com
DEBUG SMTP: Sending failed because of invalid destination addresses
RSET
250 2.0.0 Ok
DEBUG SMTP: MessagingException while sending, THROW: 
javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <unknown[10.112.60.120]>: Client host rejected: Access denied

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2079)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1301)
    at com.interfaceframe.mail.sendSMTPMail.SendEmail(sendSMTPMail.java:78)
    at com.interfaceframe.mail.sendSMTPMail.main(sendSMTPMail.java:115)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <unknown[10.112.60.120]>: Client host rejected: Access denied

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1979)
    ... 3 more
发送失败
javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <unknown[10.112.60.120]>: Client host rejected: Access denied

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2079)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1301)
    at com.interfaceframe.mail.sendSMTPMail.SendEmail(sendSMTPMail.java:78)
    at com.interfaceframe.mail.sendSMTPMail.main(sendSMTPMail.java:115)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 <unknown[10.112.60.120]>: Client host rejected: Access denied

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1979)
    ... 3 more

Process finished with exit code 0


如遇

javax.mail.AuthenticationFailedException: 535 5.7.139 Authentication unsuccessful, the user credentials were incorrect. [SGBP274CA0017.SGPP274.PROD.OUTLOOK.COM]

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:267)
    at com.interfaceframe.mail.sentmail.SendEmail(sentmail.java:76)
    at com.interfaceframe.mail.sentmail.main(sentmail.java:113)

解决办法:

// ehlo被设置为false的时候连接邮件服务器不需要验证
props.setProperty("mail.smtp.ehlo", "false");

2022.7.4-7.5 自动化case运行结果入库以及解决奇奇怪怪的问题。。。。醉了

IDEA文件列表无法显示.log文件

idea运行完程序,在ide项目目录下不展示txt日志文件 log日志文件,在访达查看本地的文件发现确实存在txt文件,但却在idea列表中看不见,要首先考虑是否被隐藏、此格式是否允许显示
如图所示,无论怎么生成log txt文件,idea文件列表始终不展示

 IDEA文件列表无法显示.log 部分.txt文件。。。idea版本问题

打开Preference - Editor - File Types 在Recognized File Types 选择文本文档Text,添加后缀*.log 保存即可看到效果

➜  .ssh git:(master) ✗ ssh -v root@xx.xx.xx.xx

OpenSSH_8.1p1, LibreSSL 2.7.3

debug1: Reading configuration data /Users/qa/.ssh/config

debug1: /Users/qa/.ssh/config line 32: Applying options for *

debug1: Reading configuration data /etc/ssh/ssh_config

debug1: /etc/ssh/ssh_config line 47: Applying options for *

debug1: auto-mux: Trying existing master

ssh 远程服务器无反应

个人开发某服务器主机出现如下问题:今天上午开始ssh连接不上了,可以ping通

解决方法:进入cd ~/.ssh 删除有问题的 master-root@10.121.xx.xx:22  ip即可

 再次尝试:

➜  .ssh git:(master) ✗ ssh -v root@10.121.xx.xx

OpenSSH_8.1p1, LibreSSL 2.7.3

debug1: Reading configuration data /Users/qa/.ssh/config

debug1: /Users/qa/.ssh/config line 32: Applying options for *

debug1: Reading configuration data /etc/ssh/ssh_config

debug1: /etc/ssh/ssh_config line 47: Applying options for *

debug1: auto-mux: Trying existing master

debug1: Control socket "/Users/qa/.ssh/master-root@10.121.xx.xx:22" does not exist

debug1: Connecting to 10.121.xx.xx [10.121.xx.xx] port 22.

debug1: Connection established.

debug1: identity file /Users/qa/.ssh/id_rsa type 0

debug1: identity file /Users/qa/.ssh/id_rsa-cert type -1

debug1: identity file /Users/qa/.ssh/id_dsa type -1

debug1: identity file /Users/qa/.ssh/id_dsa-cert type -1

debug1: identity file /Users/qa/.ssh/id_ecdsa type -1

debug1: identity file /Users/qa/.ssh/id_ecdsa-cert type -1

debug1: identity file /Users/qa/.ssh/id_ed25519 type -1

debug1: identity file /Users/qa/.ssh/id_ed25519-cert type -1

debug1: identity file /Users/qa/.ssh/id_xmss type -1

debug1: identity file /Users/qa/.ssh/id_xmss-cert type -1

debug1: Local version string SSH-2.0-OpenSSH_8.1

debug1: Remote protocol version 2.0, remote software version OpenSSH_8.0

debug1: match: OpenSSH_8.0 pat OpenSSH* compat 0x04000000

debug1: Authenticating to 10.121.xx.xx:22 as 'root'

debug1: SSH2_MSG_KEXINIT sent

debug1: SSH2_MSG_KEXINIT received

debug1: kex: algorithm: curve25519-sha256

debug1: kex: host key algorithm: ecdsa-sha2-nistp256

debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

debug1: expecting SSH2_MSG_KEX_ECDH_REPLY

debug1: Server host key: ecdsa-sha2-nistp256 SHA256:bKzcAVLHBakgx6Z/aRlmqD/onljlxwk8UviUA/6kXqo

debug1: Host '10.121.xx.xx' is known and matches the ECDSA host key.

debug1: Found key in /Users/qa/.ssh/known_hosts:1

debug1: rekey out after 134217728 blocks

debug1: SSH2_MSG_NEWKEYS sent

debug1: expecting SSH2_MSG_NEWKEYS

debug1: SSH2_MSG_NEWKEYS received

debug1: rekey in after 134217728 blocks

debug1: Will attempt key: /Users/qa/.ssh/id_rsa RSA SHA256:6d80+XpqX0pzCpVY/mO2TnEdYIsfU03osVDyQrlKQD8

debug1: Will attempt key: /Users/qa/.ssh/id_dsa

debug1: Will attempt key: /Users/qa/.ssh/id_ecdsa

debug1: Will attempt key: /Users/qa/.ssh/id_ed25519

debug1: Will attempt key: /Users/qa/.ssh/id_xmss

debug1: SSH2_MSG_EXT_INFO received

debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>

debug1: SSH2_MSG_SERVICE_ACCEPT received

debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password

debug1: Next authentication method: publickey

debug1: Offering public key: /Users/qa/.ssh/id_rsa RSA SHA256:6d80+XpqX0pzCpVY/mO2TnEdYIsfU03osVDyQrlKQD8

debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password

debug1: Trying private key: /Users/qa/.ssh/id_dsa

debug1: Trying private key: /Users/qa/.ssh/id_ecdsa

debug1: Trying private key: /Users/qa/.ssh/id_ed25519

debug1: Trying private key: /Users/qa/.ssh/id_xmss

debug1: Next authentication method: password

root@10.121.xx.xx's password:

如上ssh -v 说明正常了

问题2:

如遇git@gitlab.xx.com: Permission denied

私钥验证错误

永久解决:在~/.ssh/config文件中(没有则新建),指定对应git服务使用的认证秘钥文件即可

vim ~/.ssh/config

添加

Host gitlab.xx.com

  Preferredauthentications publickey

  IdentityFile ~/.ssh/id_rsa

                    

  1. // System.out.println("$$$$$$$$$$$$$: " + errorResult_KEYVALUE);
  2. // 实际结果和期望结果的key value不相等 ,共有 1 处!具体差异请看下面:*********请注意\n\nkey: xx value: {id:,name:admin,real:管理员,xx@xx.com,role:管理员},不在实际结果\n\n
  3. // 20220703入库的fail_reason做解析,去掉*********,把\n换成空
  4. if (errorResult_KEYVALUE.contains("*********")) {
  5. fail_reason_db = errorResult_KEYVALUE.replace("*********", "").replace("\\n\\n", "").
  6. replace("\n\n", "");
  7. // System.out.println("fail_reason_db" + fail_reason_db);
  8. }
  1. /**
  2. * 20220704新增所有case运行总结果入库api_job,插入数据库--开始
  3. * 在for循环外面,对总的case运行结果汇总成一条summary入库
  4. */
  5. String start_time_all = TimeTransfer.TimeStamp2Date(start_time);
  6. long end_time = System.currentTimeMillis();
  7. float duration_time = (end_time - start_time) / 1000;
  8. ReportToDBApiJob.reportToApiJob(build_number, job_id, pass, fail,
  9. 0, ignore, total, start_time_all, duration_time);
  10. /**
  11. * 20220704新增所有case运行总结果入库api_job,插入数据库--结束
  12. *
  13. */

执行结果

2022.7.1-7.3 CentOS 7 环境下安装Maven、设计java运行的shell脚本、配置定时任务

前提:centos安装好了java环境 见 2022.6.24  Linux(centos8)搭建java环境详细步骤

1.下载JDK

JDK官网下载链接

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

选中Java SE Development Kit 8u144中的Accept License Agreement

选择适合自己操作系统的版本点击链接下载 
选择x64 Compressed Archive  下载版本jdk-8u333-linux-x64.tar.gz

配置jdk环境变量 vim /etc/profile

#20220701 new

export JAVA_HOME=/www/data/soft/jdk1.8.0_333

export CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar

export PATH=$PATH:$JAVA_HOME/bin

使用yum查找jdk   

yum search java|grep jdk

2. 下载安装maven文件

wget http://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz

如果下载不下来,则在浏览器下载下来tar包再scp到服务器

scp ./apache-maven-3.5.4-bin.tar.gz root@remoteip:/www/data/soft

3. 解压安装

tar -zxvf apache-maven-3.5.4-bin.tar.gz

参考CentOS 7 环境下安装Maven

4. 配置环境变量
使用vim编辑/etc/profile文件  vim /etc/profile
在/etc/profile文件末尾增加以下3行配置:

#20220701新增maven环境变量 M2_HOME为maven的安装路径

M2_HOME=/www/data/soft/apache-maven-3.5.4

export PATH=${M2_HOME}/bin:${PATH}

重载/etc/profile这个文件 source /etc/profile

5. 检验maven是否安装成功

[root@localhost jdk1.8.0_333]# mvn -version

Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00)

Maven home: /www/data/soft/apache-maven-3.5.4

Java version: 1.8.0_333, vendor: Oracle Corporation, runtime: /www/data/soft/jdk1.8.0_333/jre

Default locale: zh_CN, platform encoding: UTF-8

OS name: "linux", version: "4.18.0-348.2.1.el8_5.x86_64", arch: "amd64", family: "unix"

6. 由于代码目录变了,修改nginx配置文件

查看防火墙是否开启了80端口

firewall-cmd --zone=public --list-port

要先确保需要关闭的端口已经关闭。如果已开放则关闭端口。public区域开放的端口,是所有IP都可以进行访问的

firewall-cmd --zone=public --list-ports   #查询开放的端口有那些

firewall-cmd --zone=public --list-port

netstat -antlp | grep 80  查看端口号占用情况

ps -ef|grep nginx

  

[root@localhost ~]# vim /etc/nginx/nginx.conf

server {

        listen       80 default_server;

        #listen       8081 default_server;

        listen       [::]:80 default_server;

        #listen       [::]:8081 default_server;

        server_name  _;

        #root         /usr/share/nginx/html;

       # root         /home/test/www/data/testng/testresultHtml;

        root         /www/data/cloudtestng/src/main/java;

        #index index.html index.htm tcicommon430_autoRun.html;

        # Load configuration files for the default server block.

        include /etc/nginx/default.d/*.conf;

修改/etc/nginx/nginx.conf 配置文件后,需要重启nginx

sudo systemctl restart nginx

服务器自动化结果地址

http://10.xx.xx.xx/testresultHtml/tcicommon430_autoRun.html

7. 在centos服务器下git clone最新自动化代码

在pom.xml文件目录下执行

[root@localhost ~]# cd /www/data/cloudtestng/

[root@localhost cloudtestng]# ll

总用量 32

-rw-r--r-- 1 root root 20069 7月   1 15:48 pom.xml

-rw-r--r-- 1 root root   186 6月  30 21:04 remote.sh

drwxr-xr-x 3 root root  4096 6月  30 21:04 src

drwxr-xr-x 6 root root  4096 6月  30 21:04 target

[root@localhost cloudtestng]# mvn clean   清理缓存

[root@localhost cloudtestng]# mvn compile   输入mvn compile后,maven会自动下载依赖jar,为代码生成字节码文件等,即编译,一定要在 /www/data/cloudtestng/ 目录下执行,pom.xml在此目录下

[root@localhost cloudtestng]# mvn test   一次性执行所有的用例

[root@localhost cloudtestng]# mvn package   打包

 编译通过

mvn exec:java -Dexec.mainClass="com.interfaceframe.testcase.tcirun"   

8. 配置shell脚本(后续慢慢完善)

[root@localhost script]# cat run.sh

cd /www/data/cloudtestng

git pull origin master

mvn compile

mvn exec:java -Dexec.mainClass="com.interfaceframe.testcase.tcirun"

9. crontab配置定时任务

如果提示未安装,就需要自行安装(crontabs)

[root@localhost data]# yum install crontabs

[root@localhost data]# yum list crontabs

定时任务规则
时间格式参数有5位,分表表示:

分钟0-59,小时0-23,日1-31,月1-12,星期0-6

*/2 * * * * /www/data/script/run.sh & >> /www/data/logs/auto.log 

每2分钟执行一次shell脚本

[root@localhost data]# service crond status

[root@localhost data]# service crond start

Redirecting to /bin/systemctl start crond.service

服务启动/关闭和查看,使用crond关键词

systemctl status crond

systemctl start crond

systemctl stop crond

systemctl reload crond

systemctl restart crond

crontab常用命令:
crontab -l

查看当前任务列表

crontab -e

编辑任务列表,添加删除新任务。执行命令后会打开文件,vim操作编辑保存文件,文件中每一行代表一条任务

9. 8写的crontab未生效

[root@localhost script]# crontab -l

*/10 * * * * cd /www/data/script && ./run.sh >> /www/data/logs/auto.log

*/1 * * * * echo 123 >> /www/data/logs/echo.log

查看cron的日志   

[root@localhost script]# cat /var/log/cron

Jul  1 17:45:02 localhost CROND[133915]: (root) CMDOUT (./run.sh: line 3: mvn: command not found)

Jul  1 17:45:02 localhost CROND[133915]: (root) CMDOUT (./run.sh: line 4: mvn: command not found)

原因找到了:crontab执行shell脚本时,不执行mvn命令,需要在shell脚本添加java_home 和mvn_home。重新执行定时任务,ok了

解决方法:修改run.sh运行脚本

[root@localhost script]# cat run.sh

  1. [root@localhost script]# cat run.sh
  2. git_dir=/www/data/cloudtestng
  3. cd $git_dir
  4. #if [ -f "pom.xml" ];
  5. #then
  6. # git pull origin master
  7. #else
  8. # git init
  9. # git clone git@gitlab.xx.com:username/cloudtestng.git
  10. #fi
  11. git pull origin master
  12. # java env 20220701
  13. export JAVA_HOME=/www/data/soft/jdk1.8.0_333
  14. export CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
  15. export PATH=$PATH:$JAVA_HOME/bin
  16. # maven env 20220701
  17. M2_HOME=/www/data/soft/apache-maven-3.5.4
  18. export PATH=${M2_HOME}/bin:${PATH}
  19. mvn compile
  20. mvn exec:java -Dexec.mainClass="com.interfaceframe.testcase.tcirun"

重启crontab :systemctl restart crond

查看crontab的运行日志

[root@localhost logs]# tail -f /www/data/logs/auto.log

[root@localhost script]# crontab -l

* */12 * * * cd /www/data/script && ./run.sh >> /www/data/logs/auto.log

#* * * */1 * echo "123: >> /www/data/logs/echo.log

[root@localhost script]# tail -f /www/data/logs/auto.log

2022.6.28-6.30

1. 如遇 [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:java (default-cli) on project testng: An exception occured while executing the Java class. com.interfaceframe.bg.testcase.hello -> [Help 1]

到本地maven仓库删除 /Users/qa/.m2/repository/org/codehaus/mojo/eec-maven-plugin/3.0.0

pom文件改为1.6.0 ,3.0.0版本可能太高了。。。然后重新加载maven真的就好了。。。。。

  1. <plugin>
  2. <groupId>org.codehaus.mojo</groupId>
  3. <artifactId>exec-maven-plugin</artifactId>
  4. <version>1.6.0</version>
  5. <executions>
  6. <execution>
  7. <goals>
  8. <goal>java</goal>
  9. </goals>
  10. </execution>
  11. </executions>
  12. <configuration>
  13. <classpathScope>test</classpathScope>
  14. </configuration>
  15. </plugin>

点击maven-Testng-Lifecycle,分别点击maven的clean compile test package 

最后在终端执行

 ➜  testng git:(master) ✗

mvn exec:java -Dexec.mainClass="com.interfaceframe.bg.testcase.tcirun"

tcirun为主函数 入口函数

20220701修改目录结构 改为

mvn exec:java -Dexec.mainClass="com.interfaceframe.testcase.tcirun"   

如遇报错 java.lang.ClassNotFoundException: com.interfaceframe.bg.testcase.xx

可能是类名不规范或者是运行的类里无main函数,需要改为如下方式调junit的方法函数

  1. public class hello {
  2. public static void main(String[] args) {
  3. new tcicommon430().autoRun();
  4. }
  5. }

发现要先本地右击Run之后再mvn命令行的方式运行代码才可以过,想了很久决定重新新建maven工程。。。然后真的非常顺利的跑起来了。心得:配置pom时,有的插件/dependency版本很重要,不是所有的最新版本就行

重新整成maven工程后,pom配置的exec-maven-plugin可以为3.0.0版本了

  1. <plugin>
  2. <groupId>org.codehaus.mojo</groupId>
  3. <artifactId>exec-maven-plugin</artifactId>
  4. <version>3.0.0</version>
  5. <executions>
  6. <execution>
  7. <goals>
  8. <goal>java</goal>
  9. </goals>
  10. </execution>
  11. </executions>
  12. <configuration>
  13. <classpathScope>test</classpathScope>
  14. </configuration>
  15. </plugin>

如遇

[WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=com.interfaceframe.testcase.tcirun,maxpri=10]
java.lang.IllegalThreadStateException
    at java.lang.ThreadGroup.destroy (ThreadGroup.java:778)
    at org.codehaus.mojo.exec.ExecJavaMojo.execute (ExecJavaMojo.java:293)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
暂不解决

2. 查看centos的版本

[root@localhost ~]# cat /etc/redhat-release

CentOS Linux release 8.5.2111

拷贝本地文件到远程机器

scp xx.sh root@xxx:/www/data/script

拷贝远程文件到本地机器

scp -r root@xx:/opt/xx/xx/xx.img /Users/qa/Desktop

Permission denied, please try again.

SSH连接报错:Permission denied, please try again.的解决方法

2022.6.27  jar包升级为maven

问题1:

如遇Cannot resolve plugin org.apache.maven.pluginsmaven-war-plugin 

IDEA日常填坑:Cannot resolve plugin org.apache.maven.pluginsmaven-war-plugin

同时检查Preference-Maven 的Maven home path 和 User settings file。 User settings file的setting.xml要放在Maven home path下面的conf(没有则新建目录)

Maven home path:选择 /usr/local/Cellar/maven/3.5.4/libexec

User settings file:/usr/local/Cellar/maven/3.5.4/conf/settings_20210913.xml

Maven home path填写 /usr/local/Cellar/maven/3.5.4/libexec

User settings file填写 /usr/local/Cellar/maven/3.5.4/conf/settings_20210913.xml

问题2:

UnsupportedOperationException之Collections$UnmodifiableList异常

报错内容如下:

java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.sort(Collections.java:1331)
这个报错,牵扯到个unmodifiablerandomaccesslist这个list集合

具体解决方法:把methods添加到result

那就把返回的集合,再新弄个集合装起来

List<Calendar> result = Lists.newArrayList(calendars);
新弄个集合,就可以随心所欲的操作啦

至于,他为什么返回个不可编辑的集合,就是不想让你修改这个集合的内容

具体怎么个不想让你修改法,再说吧。反正就是不想让你修改

UnsupportedOperationException之Collections$UnmodifiableList异常

  1. @Override
  2. protected List<FrameworkMethod> computeTestMethods() {
  3. List<FrameworkMethod> methods = super.computeTestMethods();
  4. // 20220627新增
  5. List<FrameworkMethod> result = Lists.newArrayList(methods);
  6. Collections.sort(result, new Comparator<FrameworkMethod>() {
  7. public int compare(FrameworkMethod method1, FrameworkMethod method2) {
  8. Case order1 = method1.getAnnotation(Case.class);
  9. Case order2 = method2.getAnnotation(Case.class);
  10. int orderNum1 = (order1 != null) ? order1.order() : DEFAULT_ORDER;
  11. int orderNum2 = (order2 != null) ? order2.order() : DEFAULT_ORDER;
  12. return orderNum1 - orderNum2;
  13. }
  14. });
  15. // 20220627删除如下2行
  16. // List<FrameworkMethod> methods_v2 = super.computeTestMethods();
  17. // methods_v2.addAll(methods);
  18. // 20220627新增return
  19. return result;
  20. }

2022.6.25-6.26  jar包升级为maven

问题1:

由于jar包方式在centos一直运行失败,改为maven方式。

解决包冲突

maven的junit test omitted for conflict with

pom的dependency添加排除依赖

我们可以使用exclusions标记从项目依赖项中排除JUnit 4 JAR。 必须将其添加到负责拉出它的依赖项中,参考博客maven依赖冲突解决_Maven依赖树

  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <version>4.12</version>
  5. <scope>test</scope>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.hamcrest</groupId>
  9. <artifactId>hamcrest-core</artifactId>
  10. </exclusion>
  11. </exclusions>
  12. </dependency>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit-dep</artifactId>
  16. <version>4.11</version>
  17. <scope>test</scope>
  18. <exclusions>
  19. <exclusion>
  20. <groupId>org.hamcrest</groupId>
  21. <artifactId>hamcrest-core</artifactId>
  22. </exclusion>
  23. </exclusions>
  24. </dependency>

问题2:

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(OverrideRunner.class)

找不到包,右击Runwith, add ClassPath

问题3:

maven的omitted for duplicate

maven所引用的依赖包重复,就会出现(omitted for duplicate)字样,虽然不影响使用,但是作为强迫症患者还是很不舒服的

其实删除重复的dependency配置就好

问题4:

/Users/qa/Desktop/APInterfaceFrame/src/com/interfaceframe/bg/xmlutil/XmlUnit2.java:5:18
java: 无法访问org.testng.Assert
  错误的类文件: /Users/qa/.m2/repository/org/testng/testng/7.6.0/testng-7.6.0.jar!/org/testng/Assert.class
    类文件具有错误的版本 55.0, 应为 52.0
    请删除该文件或确保该文件位于正确的类路径子目录中。 

1. 本地通过create-react-app创建一个react项目
2. gitlab上创建一个仓库 需要在设置-SSH公钥-添加本地/Users/qa/.ssh/id_rsa.pub的文本内容

生成/添加SSH公钥 - Gitee.com

3. // 查看本地代码git 分支

git branch

// 查看本地代码关联的git仓库地址
git remote -v

// 删除远程关联的git仓库地址
git remote rm origin

git remote rm origine

// 本地代码关联新的仓库地址
git remote add origin 新地址(ssh)

// 再次查看本地代码关联的git仓库地址
git remote -v

4. 提交代码

git add *

git commit -m 'update'
把本地的项目代码提交到远程仓库:本地有几个分支提交几个

git push --set-upstream origin master

git push --set-upstream origin branchA

git push --set-upstream origin branchB

或者 git push origin master
如果提交失败,先更新代码:git pull origin master --allow-unrelated-histories
如果出现冲突,先解决代码里面的冲突, 然后再git add .和git commit -m 'xxx'
把本地的修改都提交到远程仓库上面:git push origin master

2022.6.24  Linux(centos8)搭建java环境详细步骤

1. 查看本地centos的版本

[root@localhost usr]# cat /etc/redhat-release
CentOS Linux release 8.5.2111

2. java官网下载jdk

Java Downloads | Oracle

3. 上传到centos8的服务器

rz jdk-18_linux-aarch64_bin.tar.gz

解压缩 tar -zxvf jdk-18_linux-aarch64_bin.tar.gz

mv jdk-18.0.1.1 /usr/local/soft/

cd /usr/local/soft/

修改配置文件,添加java环境变量

  1. export JAVA_HOME=/usr/bin/java
  2. export JRE_HOME=${JAVA_HOME}/jre
  3. export CLASS_PATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
  4. export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

[root@localhost soft]# vi /etc/profile

使配置生效:

[root@localhost soft]# source /etc/profile

查看java的版本,测试安装是否成功

  1. [root@localhost soft]# java -version
  2. openjdk version "1.8.0_312"
  3. OpenJDK Runtime Environment (build 1.8.0_312-b07)
  4. OpenJDK 64-Bit Server VM (build 25.312-b07, mixed mode)

参考博客centos8安装java jdk 13

在编译时应使用javac命令加-d选项,会自动生成包的目录,注意-d后面的'.',代表当前目录(test.java所在的目录)

javac -d . test.java

javac -d . tcicommon430.java


而在运行时的用java命令加包的路径,其中com.abc为package打包的目录

java com.abc.test
 

IDEA打包jar包详尽流程

centos查找已安装的jdk路径的方法_Centos_服务器之家

2022.6.22-06.23  Linux(centos8)安装nginx详细步骤

安装nginx如遇

Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist

首先,进入到 yum 的 repos 目录
cd /etc/yum.repos.d/
其次,修改 centos 文件内容
sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
然后,生成缓存更新(第一次更新,速度稍微有点慢,耐心等待两分钟左右)
yum makecache
最后,运行 yum update 并重新安装 vim
yum update -y
 

从CentOS 8开始,Nginx软件包在默认的CentOS存储库中可用。
在CentOS 8上安装Nginx只需输入以下内容即可:

sudo yum install nginx


安装完成后,使用以下命令启用并启动Nginx服务:

sudo systemctl enable nginx 
sudo systemctl start nginx


要验证服务是否正在运行,请检查其状态:

sudo systemctl status nginx

 或者ps -ef|grep nginx

nginx安装成功,在浏览器访问你服务器的ip即可

一、查看nginx安装目录

ps -ef|grep nginx

[root@localhost testresultHtml]# ps -ef|grep nginx
root       78245       1  0 17:39 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx      78246   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78247   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78248   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78249   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78250   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78251   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78252   78245  0 17:39 ?        00:00:00 nginx: worker process
nginx      78253   78245  0 17:39 ?        00:00:00 nginx: worker process
root       78285   77771  0 18:25 pts/1    00:00:00 grep --color=auto nginx

二、查看配置文件nginxconf路径
nginx -t

[root@localhost testresultHtml]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
这条命令也可以用于检查配置文件是否正确。

当然也可以使用find命令进行文件查找
#从/根目录下查找文件名为nginxconf的文件 find / -name nginx.conf

[root@localhost testresultHtml]# find / -name nginx.conf
/etc/nginx/nginx.conf
#从/etc目录下查找文件名为nginxconf的文件 find /etc -name nginx.conf

查看nginx完整配置

  1. # For more information on configuration, see:
  2. # * Official English Documentation: http://nginx.org/en/docs/
  3. # * Official Russian Documentation: http://nginx.org/ru/docs/
  4. user nginx;
  5. worker_processes auto;
  6. error_log /var/log/nginx/error.log;
  7. pid /run/nginx.pid;
  8. # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
  9. include /usr/share/nginx/modules/*.conf;
  10. events {
  11. worker_connections 1024;
  12. }
  13. http {
  14. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  15. '$status $body_bytes_sent "$http_referer" '
  16. '"$http_user_agent" "$http_x_forwarded_for"';
  17. access_log /var/log/nginx/access.log main;
  18. sendfile on;
  19. tcp_nopush on;
  20. tcp_nodelay on;
  21. keepalive_timeout 65;
  22. types_hash_max_size 2048;
  23. include /etc/nginx/mime.types;
  24. default_type application/octet-stream;
  25. autoindex on;
  26. charset utf-8,gbk,utf-16,utf-32;
  27. # Load modular configuration files from the /etc/nginx/conf.d directory.
  28. # See http://nginx.org/en/docs/ngx_core_module.html#include
  29. # for more information.
  30. include /etc/nginx/conf.d/*.conf;
  31. server {
  32. listen 80 default_server;
  33. listen [::]:80 default_server;
  34. server_name _;
  35. #root /usr/share/nginx/html;
  36. #root /home/test;
  37. # root /home/test/www/data/testng/testresultHtml;
  38. root /home/test/www/data/testng;
  39. #index index.html index.htm tcicommon430_autoRun.html;
  40. # Load configuration files for the default server block.
  41. include /etc/nginx/default.d/*.conf;
  42. location / {
  43. }
  44. error_page 404 /404.html;
  45. location = /40x.html {
  46. }
  47. error_page 500 502 503 504 /50x.html;
  48. location = /50x.html {
  49. }
  50. }
  51. # Settings for a TLS enabled server.
  52. #
  53. # server {
  54. # listen 443 ssl http2 default_server;
  55. # listen [::]:443 ssl http2 default_server;
  56. # server_name _;
  57. # root /usr/share/nginx/html;
  58. #
  59. # ssl_certificate "/etc/pki/nginx/server.crt";
  60. # ssl_certificate_key "/etc/pki/nginx/private/server.key";
  61. # ssl_session_cache shared:SSL:1m;
  62. # ssl_session_timeout 10m;
  63. # ssl_ciphers PROFILE=SYSTEM;
  64. # ssl_prefer_server_ciphers on;
  65. #
  66. # # Load configuration files for the default server block.
  67. # include /etc/nginx/default.d/*.conf;
  68. #
  69. # location / {
  70. # }
  71. #
  72. # error_page 404 /404.html;
  73. # location = /40x.html {
  74. # }
  75. #
  76. # error_page 500 502 503 504 /50x.html;
  77. # location = /50x.html {
  78. # }
  79. # }
  80. }

修改/etc/nginx/nginx.conf 配置文件后,需要重启nginx

sudo systemctl restart nginx

重启成功 nginx的进程时间变了

[root@localhost etc]# ps -ef|grep nginx
root       78312       1  0 18:31 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx      78313   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78314   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78315   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78316   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78317   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78318   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78319   78312  0 18:31 ?        00:00:00 nginx: worker process
nginx      78320   78312  0 18:31 ?        00:00:00 nginx: worker process

三、指定配置文件并启动nginx服务
nginx安装目录-cnginxconf配置文件目录
其中:参数“-c”指定了配置文件的路径,如果不加“-c”参数,Nainx会默认加载其安装目录的conf子目录中的nainxconf文件。

四、命令参数
/usr/ocal/nginx/sbin/nginx参数
Nginx的参数包括:
-C<path to config>:使用指定的配置文件而不是conf目录下的nginxconf。
-t:测试配置文件是否正确,在运行时需要重新加载配置的时候,此命令非常重要,用来检测所修改的配置文件是否有语法错误。 -v:显示nginx版本号。
-V:显示nginx的版本号以及编译环境信息以及编译时的参数。
检测新的配置文件:
/usr/local/nginx/conf#/usr/local/nginx/sbin/nginx-t-c/usr/local/nginx/conf/nginx.conf

2022.6.21 服务器部署java运行环境

把git仓库的代码拉到服务器

出现如下报错:

git@gitlab.xx.com's password:
Permission denied, please try again.
git@gitlab.xx.com's password:
s
git@gitlab.xx.com: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
fatal: Could not read from remote repository.

 因为是纯净的服务器

  Virtualization: kvm
  Operating System: CentOS Linux 8
  CPE OS Name: cpe:/o:centos:centos:8
  Kernel: Linux 4.18.0-348.2.1.el8_5.x86_64
  Architecture: x86-64

所以需要配置git

1.1 设置信息

git config --global user.name "username"

git config --global user.email "your@email.com"

//yourname是 gitlab的用户名,your@email是gitlab的邮箱

1.2 紧接着生成ssh

ssh-keygen -t rsa -C "your@email.com"(输入自己的邮箱)

后面出现的直接回车就可以

1.3 查看公钥
在/root/.ssh  (~/.ssh/)找到id_rsa.pub
打开id_rsa.pub,复制全部内容拷贝到git的User setting - SSH Keys

2022.5.25封装工具类-delete请求方法

测试报告展示调整,英文的一目了然?自动化展示结果改为中文标题的了。。。。。。。

新增/Users/qa/Desktop/2021/code/APInterfaceFrame/src/com/interfaceframe/bg/method/Delete.java

  1. package com.interfaceframe.bg.method;
  2. import com.httpclient.GetToken;
  3. import com.interfaceframe.bg.util.MySSLSocketFactory;
  4. import org.apache.commons.httpclient.Header;
  5. import org.apache.commons.httpclient.HttpClient;
  6. import org.apache.commons.httpclient.NameValuePair;
  7. import org.apache.commons.httpclient.methods.DeleteMethod;
  8. import org.apache.commons.httpclient.protocol.Protocol;
  9. import org.apache.commons.httpclient.util.EncodingUtil;
  10. import java.util.ArrayList;
  11. import java.util.Iterator;
  12. import java.util.List;
  13. import java.util.Map;
  14. public class Delete {
  15. public static String delete(String method, String url, Map<String, String> paramter) {
  16. try {
  17. // 20220525 解决javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
  18. // 增加下面两行代码
  19. Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
  20. Protocol.registerProtocol("https", myhttps);
  21. // header必传参数Content-type
  22. Header header = new Header("Content-type", "application/json; charset=utf-8");
  23. String response = "";
  24. // HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
  25. // HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
  26. // 使用HttpClient发送请求、接收响应
  27. HttpClient httpClient = new HttpClient();
  28. if (url != null) {
  29. // NameValuePair是简单名称值对节点类型。多用于Java像url发送Post请求。在发送post请求时用该list来存放参数
  30. // getParamsList(url_online, params, count);
  31. // 预发环境value替换线上环境value
  32. List<NameValuePair> qparams_pre = getParamsList_pre(paramter);
  33. if (qparams_pre != null && qparams_pre.size() > 0) {
  34. String formatParams = EncodingUtil.formUrlEncode(qparams_pre.toArray(new org.apache.commons.httpclient.NameValuePair[qparams_pre.size()]),
  35. "utf-8");
  36. url = url.indexOf("?") < 0 ? url + "?" + formatParams : url + "&" + formatParams;
  37. }
  38. // requestURL = url;
  39. // System.out.println("第" + (count + 1) + "个请求,预发环境pre请求的url==" + url);
  40. DeleteMethod deleteMethod = new DeleteMethod(url);
  41. deleteMethod.addRequestHeader(header);
  42. // 9月9 header必传参数Accept设置为*/* 绝大数设置为application/json; charset=utf-8都正常,但是OpenStack的network接口会返回406
  43. // deleteMethod.addRequestHeader(new Header("Accept", "application/json; charset=utf-8"));
  44. // 10月22日,兼容不同系统传参
  45. // 11月24日,测试拓扑-mec-mec16的数据{{mec_api_gw}}/mec-engine/api/hosts?allow_anonymous=true 再次出现Accept的问题
  46. deleteMethod.addRequestHeader(new Header("Accept", "application/json, text/plain, */*"));
  47. // deleteMethod.addRequestHeader(new Header("Authorization", "application/json, text/plain, */*"));
  48. // String encoding = DatatypeConverter.printBase64Binary("admin:admin".getBytes("UTF-8")); //username password 自行修改 中间":"不可少
  49. deleteMethod.addRequestHeader(new Header("Authorization", "Bearer " + GetToken.tci2104Token()));
  50. int statusCode = httpClient.executeMethod(deleteMethod);
  51. System.out.println("请求状态码statusCode=" + statusCode + ",如果为204则表示删除成功");
  52. response = new String(deleteMethod.getResponseBody(), "utf-8");
  53. System.out.println("================================" + response);
  54. return response;
  55. }
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. }
  59. return "---------------";
  60. }
  61. // 参数格式化
  62. private static List<NameValuePair> getParamsList_pre(Map<String, String> paramsMap) {
  63. if (paramsMap != null && paramsMap.size() != 0) {
  64. List<NameValuePair> params = new ArrayList();
  65. Iterator var2 = paramsMap.entrySet().iterator();
  66. while (var2.hasNext()) {
  67. Map.Entry<String, String> map = (Map.Entry) var2.next();
  68. // 预发环境最新版本日志回放,请求参数打开以下if else,注释掉最后一行
  69. // 参数格式化,commons-httpclient自带的方法NameValuePair会自动将==转为=,还有特殊符号格式化
  70. // NameValuePair是简单名称值对节点类型。多用于Java像url_test发送Post请求。在发送post请求时用该list来存放参数
  71. params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  72. // params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  73. }
  74. return params;
  75. } else {
  76. return null;
  77. }
  78. }
  79. }

般 HttpPost 对传参 Json 的处理是:

// 中文处理

StringEntity se = new StringEntity(json, Consts.UTF_8);
httppost.setEntity(se);
HttpPost、HttpPut继承了HttpEntityEnclosingRequestBase类,所以有setEntity方法。详情请自行查看源码。

查看httpclient-4.2.3的源码可以发现,methods包下面包含HttpGet, HttpPost, HttpPut, HttpDelete等类来实现http的常用操作。

其中,HttpPost继承自 HttpEntityEnclosingRequestBase,HttpEntityEnclosingRequestBase类又实现了 HttpEntityEnclosingRequest接口,实现了setEntity的方法。

而HttpDelete继承自HttpRequestBase,没有实现setEntity的方法,因此无法设置HttpEntity对象。

而HttpDelete没有对应的setEntity()方法,那么怎么传递呢?

  1. package net.dn.client;
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import org.apache.http.Header;
  5. import org.apache.http.annotation.NotThreadSafe;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.methods.CloseableHttpResponse;
  8. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  9. import org.apache.http.entity.ContentType;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.CloseableHttpClient;
  12. import org.apache.http.impl.client.HttpClients;
  13. import org.apache.http.util.EntityUtils;
  14. @NotThreadSafe
  15. class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
  16. public static final String METHOD_NAME = "DELETE";
  17. public String getMethod() {
  18. return METHOD_NAME;
  19. }
  20. public HttpDeleteWithBody(final String uri) {
  21. super();
  22. setURI(URI.create(uri));
  23. }
  24. public HttpDeleteWithBody(final URI uri) {
  25. super();
  26. setURI(uri);
  27. }
  28. public HttpDeleteWithBody() {
  29. super();
  30. }
  31. }
  32. public class ClientMain {
  33. public static void main(String[] args) throws ClientProtocolException, IOException {
  34. CloseableHttpClient httpclient = HttpClients.createDefault();
  35. String url = "http://localhost:8080/RESTfulDeleteWithBody/rest";
  36. HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
  37. StringEntity input = new StringEntity("John Dow", ContentType.APPLICATION_JSON);
  38. httpDelete.setEntity(input);
  39. System.out.println("****REQUEST***************************************");
  40. System.out.println(url);
  41. Header requestHeaders[] = httpDelete.getAllHeaders();
  42. for (Header h : requestHeaders) {
  43. System.out.println(h.getName() + ": " + h.getValue());
  44. }
  45. CloseableHttpResponse response = httpclient.execute(httpDelete);
  46. System.out.println("****RESPONSE***************************************");
  47. System.out.println("----status:---------------------");
  48. System.out.println(response.getStatusLine());
  49. System.out.println("----header:---------------------");
  50. Header responseHeaders[] = response.getAllHeaders();
  51. for (Header h : responseHeaders) {
  52. System.out.println(h.getName() + ": " + h.getValue());
  53. }
  54. System.out.println("----content:---------------------");
  55. System.out.println(EntityUtils.toString(response.getEntity()));
  56. }
  57. }

代码调用

  1. HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
  2. // json 处理
  3. httpdelete.setHeader("Content-Type", "application/json; charset=UTF-8");//or addHeader();
  4. httpdelete.setHeader("X-Requested-With", "XMLHttpRequest");
  5. //设置HttpDelete的请求参数
  6. httpdelete.setEntity(new StringEntity(paramsJsonStr));
  7. httpDelete.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
  8. httpdelete.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
  9. HttpResponse response = client.execute(httpdelete);

2022.5.24解决ssl证书报错(get请求)

/Users/qa/Desktop/2021/code/APInterfaceFrame/src/com/interfaceframe/bg/method/Get.java

  1. /**
  2. * get 请求,只需将变动的参数传入params中即可
  3. *
  4. * @param url
  5. * @return
  6. */
  7. public static String get(String method, String url, Map<String, String> paramter) {
  8. try {
  9. // 2021.7.13 解决javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
  10. // 增加下面两行代码
  11. Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
  12. Protocol.registerProtocol("https", myhttps);
  13. // header必传参数Content-type
  14. Header header = new Header("Content-type", "application/json; charset=utf-8");
  15. String response = "";
  16. // HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
  17. // HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
  18. // 使用HttpClient发送请求、接收响应
  19. HttpClient httpClient = new HttpClient();
  20. if (url != null) {
  21. // NameValuePair是简单名称值对节点类型。多用于Java像url发送Post请求。在发送post请求时用该list来存放参数
  22. // getParamsList(url_online, params, count);
  23. // 预发环境value替换线上环境value
  24. List<org.apache.commons.httpclient.NameValuePair> qparams_pre = getParamsList_pre(paramter);
  25. if (qparams_pre != null && qparams_pre.size() > 0) {
  26. String formatParams = EncodingUtil.formUrlEncode(qparams_pre.toArray(new org.apache.commons.httpclient.NameValuePair[qparams_pre.size()]),
  27. "utf-8");
  28. url = url.indexOf("?") < 0 ? url + "?" + formatParams : url + "&" + formatParams;
  29. }
  30. // requestURL = url;
  31. // System.out.println("第" + (count + 1) + "个请求,预发环境pre请求的url==" + url);
  32. GetMethod getMethod = new GetMethod(url);
  33. getMethod.addRequestHeader(header);
  34. // 9月9 header必传参数Accept设置为*/* 绝大数设置为application/json; charset=utf-8都正常,但是OpenStack的network接口会返回406
  35. // getMethod.addRequestHeader(new Header("Accept", "application/json; charset=utf-8"));
  36. // 10月22日,兼容不同系统传参
  37. // 11月24日,测试拓扑-mec-mec16的数据{{mec_api_gw}}/mec-engine/api/hosts?allow_anonymous=true 再次出现Accept的问题
  38. getMethod.addRequestHeader(new Header("Accept", "application/json, text/plain, */*"));
  39. int statusCode = httpClient.executeMethod(getMethod);
  40. System.out.println("请求状态码statusCode=" + statusCode);
  41. response = new String(getMethod.getResponseBody(), "utf-8");
  42. System.out.println("================================" + response);
  43. return response;
  44. }
  45. }catch(Exception e){
  46. e.printStackTrace();
  47. }
  48. return "---------------";
  49. }
  50. // 参数格式化
  51. private static List<NameValuePair> getParamsList_pre(Map<String, String> paramsMap) {
  52. if (paramsMap != null && paramsMap.size() != 0) {
  53. List<NameValuePair> params = new ArrayList();
  54. Iterator var2 = paramsMap.entrySet().iterator();
  55. while (var2.hasNext()) {
  56. Map.Entry<String, String> map = (Map.Entry) var2.next();
  57. // 预发环境最新版本日志回放,请求参数打开以下if else,注释掉最后一行
  58. // 参数格式化,commons-httpclient自带的方法NameValuePair会自动将==转为=,还有特殊符号格式化
  59. // NameValuePair是简单名称值对节点类型。多用于Java像url_test发送Post请求。在发送post请求时用该list来存放参数
  60. params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  61. // params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  62. }
  63. return params;
  64. } else {
  65. return null;
  66. }
  67. }
  68. }

新增 /Users/qa/Desktop/2021/code/APInterfaceFrame/src/com/interfaceframe/bg/util/MySSLSocketFactory.java

  1. package com.interfaceframe.bg.util;
  2. import org.apache.commons.httpclient.ConnectTimeoutException;
  3. import org.apache.commons.httpclient.params.HttpConnectionParams;
  4. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
  5. import javax.net.SocketFactory;
  6. import javax.net.ssl.SSLContext;
  7. import javax.net.ssl.TrustManager;
  8. import javax.net.ssl.X509TrustManager;
  9. import java.io.IOException;
  10. import java.net.*;
  11. import java.security.KeyManagementException;
  12. import java.security.NoSuchAlgorithmException;
  13. import java.security.cert.CertificateException;
  14. import java.security.cert.X509Certificate;
  15. public class MySSLSocketFactory implements ProtocolSocketFactory {
  16. static {
  17. System.out.println(">>>>in MySSLSocketFactory>>");
  18. }
  19. private SSLContext sslcontext = null;
  20. private SSLContext createSSLContext() {
  21. SSLContext sslcontext = null;
  22. try {
  23. sslcontext = SSLContext.getInstance("SSL");
  24. sslcontext.init(null,
  25. new TrustManager[]{new TrustAnyTrustManager()},
  26. new java.security.SecureRandom());
  27. } catch (NoSuchAlgorithmException e) {
  28. e.printStackTrace();
  29. } catch (KeyManagementException e) {
  30. e.printStackTrace();
  31. }
  32. return sslcontext;
  33. }
  34. private SSLContext getSSLContext() {
  35. if (this.sslcontext == null) {
  36. this.sslcontext = createSSLContext();
  37. }
  38. return this.sslcontext;
  39. }
  40. public Socket createSocket(Socket socket, String host, int port,
  41. boolean autoClose) throws IOException, UnknownHostException {
  42. return getSSLContext().getSocketFactory().createSocket(socket, host,
  43. port, autoClose);
  44. }
  45. public Socket createSocket(String host, int port) throws IOException,
  46. UnknownHostException {
  47. return getSSLContext().getSocketFactory().createSocket(host, port);
  48. }
  49. public Socket createSocket(String host, int port, InetAddress clientHost,
  50. int clientPort) throws IOException, UnknownHostException {
  51. return getSSLContext().getSocketFactory().createSocket(host, port,
  52. clientHost, clientPort);
  53. }
  54. public Socket createSocket(String host, int port, InetAddress localAddress,
  55. int localPort, HttpConnectionParams params) throws IOException,
  56. UnknownHostException, ConnectTimeoutException {
  57. if (params == null) {
  58. throw new IllegalArgumentException("Parameters may not be null");
  59. }
  60. int timeout = params.getConnectionTimeout();
  61. SocketFactory socketfactory = getSSLContext().getSocketFactory();
  62. if (timeout == 0) {
  63. return socketfactory.createSocket(host, port, localAddress,
  64. localPort);
  65. } else {
  66. Socket socket = socketfactory.createSocket();
  67. SocketAddress localaddr = new InetSocketAddress(localAddress,
  68. localPort);
  69. SocketAddress remoteaddr = new InetSocketAddress(host, port);
  70. socket.bind(localaddr);
  71. socket.connect(remoteaddr, timeout);
  72. return socket;
  73. }
  74. }
  75. private static class TrustAnyTrustManager implements X509TrustManager {
  76. public void checkClientTrusted(X509Certificate[] chain, String authType)
  77. throws CertificateException {
  78. }
  79. public void checkServerTrusted(X509Certificate[] chain, String authType)
  80. throws CertificateException {
  81. }
  82. public X509Certificate[] getAcceptedIssuers() {
  83. return new X509Certificate[]{};
  84. }
  85. }
  86. }

2022.5.19解决ssl证书报错(post请求)

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

虽然以下博客没用 但我觉得不错

javax.net.ssl.SSLHandshakeException的解决办法

解决 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path buildin

javax.net.ssl.SSLPeerUnverifiedException: Host name '10.121.140.30' does not match the certificate subject provided by the peer (OU=MyUnit, O=MyOrg, L=NY, ST=NY, C=US, EMAILADDRESS=none@none.com, CN=localhost)
解决办法:搜索SSL证书校验Java Client 忽略对服务端的SSL证书校验

参考【SSL证书校验】Java Client 忽略对服务端的SSL证书校验

代码如下

在/Users/qa/Desktop/2021/code/APInterfaceFrame/src/com/interfaceframe/bg/util/HttpXmlClient.java 修改postJsonStr方法。添加如下内容

  1. SSLContext sslContext = null;
  2. try {
  3. sslContext = SSLContextBuilder.create().loadTrustMaterial((chain, authType) -> true).build();
  4. } catch (KeyManagementException e) {
  5. e.printStackTrace();
  6. }
  7. HttpClientBuilder custom = HttpClients.custom();
  8. custom.setSSLContext(sslContext);
  9. custom.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
  10. CloseableHttpClient httpclient = custom.build();

2022.5.18新增 对https的封装-post请求

  1. /**
  2. * 2022.5.18新增 对https接口请求的证书封装。post请求,https
  3. */
  4. public static String sendHttps(String json, String URL) {
  5. StringBuilder stringBuilder = new StringBuilder();
  6. try {
  7. HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
  8. connection.setHostnameVerifier(
  9. (urlHostName, session) -> true);
  10. connection.setRequestMethod("POST");
  11. connection.setDoOutput(true);
  12. //write header
  13. connection.setRequestProperty("Content-type", "application/json; charset=utf-8");
  14. connection.setRequestProperty("Accept", "application/json, text/plain, */*");
  15. //write body
  16. try (PrintWriter writer = new PrintWriter(connection.getOutputStream())) {
  17. // Map<String, String> foo = new HashMap<>();
  18. // foo.put("name", "HTTP");
  19. // foo.put("age", "18");
  20. // writer.write(JSONObject.toJSONString(foo));
  21. writer.write(json);
  22. writer.flush();
  23. }
  24. //read response
  25. try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
  26. String line = "";
  27. while ((line = reader.readLine()) != null) {
  28. stringBuilder.append(line);
  29. }
  30. // System.out.println("debug-https返回结果==" + line);
  31. } finally {
  32. connection.disconnect();
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. // System.out.println("https登录接口返回结果===" + stringBuilder.toString());
  38. return stringBuilder.toString();
  39. }
  40. static {
  41. try {
  42. trustAllHttpsCertificates();
  43. HttpsURLConnection.setDefaultHostnameVerifier
  44. (
  45. (urlHostName, session) -> true
  46. );
  47. } catch (Exception e) {
  48. }
  49. }
  50. private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
  51. TrustManager[] trustAllCerts = new TrustManager[1];
  52. trustAllCerts[0] = new TrustAllManager();
  53. SSLContext sc = SSLContext.getInstance("SSL");
  54. sc.init(null, trustAllCerts, null);
  55. HttpsURLConnection.setDefaultSSLSocketFactory(
  56. sc.getSocketFactory());
  57. }
  58. private static class TrustAllManager implements X509TrustManager {
  59. public X509Certificate[] getAcceptedIssuers() {
  60. return null;
  61. }
  62. public void checkServerTrusted(X509Certificate[] certs, String authType) {
  63. }
  64. public void checkClientTrusted(X509Certificate[] certs, String authType) {
  65. }
  66. }
  67. /**
  68. * post请求,http
  69. */
  70. public static String doPost(String json, String URL) throws IOException {
  71. //json:请求url的参数
  72. String obj = null;
  73. // 创建默认的httpClient实例
  74. CloseableHttpClient httpclient = HttpClients.createDefault();
  75. // 创建httppost
  76. HttpPost httppost = new HttpPost(URL);
  77. // header必传参数Content-type、Accept
  78. // httppost.addHeader("Content-type", "application/json; charset=utf-8");
  79. // httppost.setHeader("Accept", "application/json");
  80. httppost.addHeader("Content-type", "application/json; charset=utf-8");
  81. httppost.setHeader("Accept", "application/json, text/plain, */*");
  82. System.out.println("URL==" + URL);
  83. //20220517新增 tci2104测试环境
  84. // if (URL.contains("10.121.140.30:8002")) {
  85. // httppost.addHeader("Authorization", "Bearer" + GetToken.tci2104Token());
  86. // System.out.println("tci2104带header的请求走到这里了==");
  87. //
  88. // }
  89. //
  90. // // cmo的dev环境
  91. // if (URL.contains("10.121.134.122:31651")) {
  92. // httppost.addHeader("X-Auth-Token", GetToken.devcmoToken());
  93. // System.out.println("mec带header的请求走到这里了==");
  94. //
  95. // }
  96. try {
  97. StringEntity strEntity = new StringEntity(json, Charset.forName("UTF-8")); //对参数进行编码,防止中文乱码
  98. strEntity.setContentEncoding("UTF-8");
  99. httppost.setEntity(strEntity);
  100. CloseableHttpResponse response = httpclient.execute(httppost);
  101. try {
  102. //获取相应实体
  103. HttpEntity entity = response.getEntity();
  104. if (entity != null) {
  105. obj = EntityUtils.toString(entity, "UTF-8");
  106. }
  107. // 获取相应实体Response-Headers
  108. org.apache.http.Header[] allheaders = response.getAllHeaders();
  109. for (int i = 0; i < allheaders.length; i++) {
  110. // System.out.println(allheaders[i]);
  111. if (allheaders[i].getName().contains("X-Subject-Token")) {
  112. String ostoken = allheaders[i].getValue();
  113. // System.err.println("登录OpenStack的Response-Header的token为==" + ostoken);
  114. }
  115. }
  116. } finally {
  117. response.close();
  118. }
  119. } catch (Exception e) {
  120. e.printStackTrace();
  121. } finally {
  122. // 关闭连接,释放资源
  123. httpclient.close();
  124. }
  125. return obj;
  126. }
  127. // 参数格式化
  128. private static List<NameValuePair> getParamsList_pre(Map<String, String> paramsMap) {
  129. if (paramsMap != null && paramsMap.size() != 0) {
  130. List<NameValuePair> params = new ArrayList();
  131. Iterator var2 = paramsMap.entrySet().iterator();
  132. while (var2.hasNext()) {
  133. Map.Entry<String, String> map = (Map.Entry) var2.next();
  134. // 预发环境最新版本日志回放,请求参数打开以下if else,注释掉最后一行
  135. // 参数格式化,commons-httpclient自带的方法NameValuePair会自动将==转为=,还有特殊符号格式化
  136. // NameValuePair是简单名称值对节点类型。多用于Java像url发送Post请求。在发送post请求时用该list来存放参数
  137. params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  138. // params.add(new NameValuePair(map.getKey() + "", map.getValue() + ""));
  139. }
  140. return params;
  141. } else {
  142. return null;
  143. }
  144. }
  145. }

2022.5.11新增

maven仓库地址

​​​​​​https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-failsafe-plugin/3.0.0-M6

5. super-jacoco

滴滴开源Super-jacoco:java代码覆盖率收集平台文档
 

4. jacoco

Jacoco--测试覆盖率工具

IDEA插件

IDEA自带Jacoco单元测试分析工具,操作步骤如下
4-1.选择编辑配置 “Edit Configurations”

4-2.添加单元测试类型,选择被测文件,此处以TestNG为例,测试所有代码(不包含lib)

4-3.选择工具jacoco

4-4.以覆盖率模式运行测试用例,点击第3个图标

 4-5.运行完成后自动生成测试报告

MAVEN

在pom.xml文件中添加以下插件后,运行 mvn test 即可在target/site/jacoco文件夹下生成报告。

如果想要跳过失败的测试用例,请使用 mvn test -Dmaven.test.failure.ignore=true

<plugin>    <groupId>org.jacoco</groupId>    <artifactId>jacoco-maven-plugin</artifactId>    <version>0.8.2-SNAPSHOT</version>    <executions>        <execution>            <id>default-prepare-agent</id>            <goals>                <goal>prepare-agent</goal>            </goals>        </execution>        <execution>            <id>default-report</id>            <phase>test</phase>            <goals>                <goal>report</goal>            </goals>        </execution>        <execution>            <id>default-check</id>            <goals>                <goal>check</goal>            </goals>        </execution>    </executions></plugin>复制代码

运行时测试

jacoco支持程序运行中监控执行情况。下面介绍直接运行和tomcat服务器运行两种监控方式

3. 如遇

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project cloud-api: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

解决办法:​​​​​​mac Big Sur系统 mvn打包报错:No compiler is provided in this environment. Perhaps you are running on a JRE-阿里云开发者社区

macos的jdk下载地址  jdk-8u333-mac.dmg

Java Downloads | Oracle

➜  Home vim ~/.bash_profile     编辑配置文件

➜  Home java -version      查看java版本

java version "1.8.0_333"

Java(TM) SE Runtime Environment (build 1.8.0_333-b02)

Java HotSpot(TM) 64-Bit Server VM (build 25.333-b02, mixed mode)

➜  Home mvn -version      查看mvn版本

Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00)

Maven home: /usr/local/Cellar/maven/3.5.4/libexec

Java version: 1.8.0_333, vendor: Oracle Corporation, runtime: /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

Default locale: zh_CN, platform encoding: UTF-8

OS name: "mac os x", version: "11.2.1", arch: "x86_64", family: "mac"

如上发现

Java version 正确,但是 runtime 值为 /Library/Internet Plug-Ins/JavaAppletPlugin.plugin

进入 /Library/Internet Plug-Ins/ 目录,删除 /Library/Internet Plug-Ins/JavaAppletPlugin.plugin

重新执行 mvn -version runtime 正确,如下图所示(装了JDK9,JDK8也类似)。

cd  /Library/Internet\ Plug-Ins

sudo rm -rf JavaAppletPlugin.plugin

mvn -version runtime

在本地重新执行➜  cloud git:(master) ✗ mvn clean test 

[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? 报错没有了

如遇

错误:找不到或无法加载主类 

cd /Library/Java/JavaVirtualMachines

sudo rm -rf jdk1.8.0_281.jdk     

File - Project Structure - Project 编辑SDK

把/Library/Java/JavaVirtualMachines/jdk1.8.0_281.jdk/Contents/Home

改为

 由于JDK版本升级了,所以这里也需要修改

qa@deMacBook-Pro-10:~$java -version
java version "1.8.0_333"
Java(TM) SE Runtime Environment (build 1.8.0_333-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.333-b02, mixed mode)
qa@deMacBook-Pro-10:~$mvn -version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00)
Maven home: /usr/local/Cellar/maven/3.5.4/libexec
Java version: 1.8.0_333, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_333.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "11.2.1", arch: "x86_64", family: "mac"

如果还是不行 菜单-Build-Rebuild Project

2. jacoco配置

Java单元覆盖率工具JaCoCo详细理解和使用(配置+示例)

1. Intellij IDEA出现错误error:java:⽆效的源发⾏版:11解决⽅法
Preference-Compiler-Java Compiler

module设置为8

 pom文件的source target设置为8

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-compiler-plugin</artifactId>
  4. <configuration>
  5. <source>8</source>
  6. <target>8</target>
  7. <encoding>UTF8</encoding>
  8. </configuration>
  9. </plugin>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/436148?site
推荐阅读
相关标签
  

闽ICP备14008679号