1
0
mirror of https://github.com/chatopera/cosin.git synced 2025-06-25 02:47:10 +08:00

fix: try with resource ensure resource close

1. 通过 try with resource 语法糖保证资源关闭
2. 修复 ACDAgentService#notifyAgentUserProcessResult 中有问题的空指针判断
This commit is contained in:
renxb 2022-03-31 18:34:09 +08:00
parent f3db1de4b0
commit 8b6c6dec18
7 changed files with 113 additions and 144 deletions

View File

@ -42,6 +42,7 @@ import org.springframework.stereotype.Component;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
@Component @Component
public class ACDAgentService { public class ACDAgentService {
@ -93,8 +94,11 @@ public class ACDAgentService {
* @param ctx * @param ctx
*/ */
public void notifyAgentUserProcessResult(final ACDComposeContext ctx) { public void notifyAgentUserProcessResult(final ACDComposeContext ctx) {
if (ctx != null && StringUtils.isNotBlank( Objects.requireNonNull(ctx,"ctx can not be null");
ctx.getMessage())) { if (StringUtils.isBlank(ctx.getMessage())) {
logger.info("[onConnect] can not find available agent for user {}", ctx.getOnlineUserId());
return;
}
logger.info("[onConnect] find available agent for onlineUser id {}", ctx.getOnlineUserId()); logger.info("[onConnect] find available agent for onlineUser id {}", ctx.getOnlineUserId());
/** /**
@ -132,10 +136,6 @@ public class ACDAgentService {
ctx.getAppid(), ctx.getAppid(),
MainContext.MessageType.NEW, ctx.getOnlineUserId(), outMessage, true); MainContext.MessageType.NEW, ctx.getOnlineUserId(), outMessage, true);
} else {
logger.info("[onConnect] can not find available agent for user {}", ctx.getOnlineUserId());
}
} }
/** /**

View File

@ -302,11 +302,10 @@ public class RedisCommand {
public List<String> getSet(final String key) { public List<String> getSet(final String key) {
Set<String> s = redisSetOps.members(key); Set<String> s = redisSetOps.members(key);
if (s != null & s.size() > 0) { if (CollectionUtils.isEmpty(s)) {
return new ArrayList<>(s);
} else {
return new ArrayList<>(); return new ArrayList<>();
} }
return new ArrayList<>(s);
} }
} }

View File

@ -82,9 +82,10 @@ public class MessagingServerConfigure {
File sslFile = new File(path, "ssl/https.properties"); File sslFile = new File(path, "ssl/https.properties");
if (sslFile.exists()) { if (sslFile.exists()) {
Properties sslProperties = new Properties(); Properties sslProperties = new Properties();
FileInputStream in = new FileInputStream(sslFile);
try (FileInputStream in = new FileInputStream(sslFile)) {
sslProperties.load(in); sslProperties.load(in);
in.close(); }
if (StringUtils.isNotBlank(sslProperties.getProperty("key-store")) && StringUtils.isNotBlank( if (StringUtils.isNotBlank(sslProperties.getProperty("key-store")) && StringUtils.isNotBlank(
sslProperties.getProperty("key-store-password"))) { sslProperties.getProperty("key-store-password"))) {
config.setKeyStorePassword(MainUtils.decryption(sslProperties.getProperty("key-store-password"))); config.setKeyStorePassword(MainUtils.decryption(sslProperties.getProperty("key-store-password")));

View File

@ -22,12 +22,10 @@ import com.chatopera.cc.controller.Handler;
import com.chatopera.cc.controller.api.request.RestUtils; import com.chatopera.cc.controller.api.request.RestUtils;
import com.chatopera.cc.model.AttachmentFile; import com.chatopera.cc.model.AttachmentFile;
import com.chatopera.cc.model.StreamingFile; import com.chatopera.cc.model.StreamingFile;
import com.chatopera.cc.model.UploadStatus;
import com.chatopera.cc.persistence.blob.JpaBlobHelper; import com.chatopera.cc.persistence.blob.JpaBlobHelper;
import com.chatopera.cc.persistence.repository.AttachmentRepository; import com.chatopera.cc.persistence.repository.AttachmentRepository;
import com.chatopera.cc.persistence.repository.StreamingFileRepository; import com.chatopera.cc.persistence.repository.StreamingFileRepository;
import com.chatopera.cc.util.Menu; import com.chatopera.cc.util.Menu;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils; import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -42,7 +40,6 @@ import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -100,16 +97,18 @@ public class MediaController extends Handler {
@RequestMapping("/url") @RequestMapping("/url")
@Menu(type = "resouce", subtype = "image", access = true) @Menu(type = "resouce", subtype = "image", access = true)
public void url(HttpServletResponse response, @Valid String url) throws IOException { public void url(HttpServletResponse response, @Valid String url) throws IOException {
if (StringUtils.isBlank(url)) {
return;
}
byte[] data = new byte[1024]; byte[] data = new byte[1024];
int length = 0; int length = 0;
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
if (StringUtils.isNotBlank(url)) { try (InputStream input = new URL(url).openStream()) {
InputStream input = new URL(url).openStream();
while ((length = input.read(data)) > 0) { while ((length = input.read(data)) > 0) {
out.write(data, 0, length); out.write(data, 0, length);
} }
input.close();
} }
} }
@RequestMapping("/image/upload") @RequestMapping("/image/upload")

View File

@ -147,9 +147,9 @@ public class UKResultMapper extends AbstractResultMapper {
private String buildJSONFromFields(Collection<SearchHitField> values) { private String buildJSONFromFields(Collection<SearchHitField> values) {
JsonFactory nodeFactory = new JsonFactory(); JsonFactory nodeFactory = new JsonFactory();
try { try (ByteArrayOutputStream stream = new ByteArrayOutputStream();
ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);) {
JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
generator.writeStartObject(); generator.writeStartObject();
for (SearchHitField value : values) { for (SearchHitField value : values) {
if (value.getValues().size() > 1) { if (value.getValues().size() > 1) {

View File

@ -147,9 +147,9 @@ public class XiaoEUKResultMapper extends AbstractResultMapper {
private String buildJSONFromFields(Collection<SearchHitField> values) { private String buildJSONFromFields(Collection<SearchHitField> values) {
JsonFactory nodeFactory = new JsonFactory(); JsonFactory nodeFactory = new JsonFactory();
try { try (ByteArrayOutputStream stream = new ByteArrayOutputStream();
ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);) {
JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8);
generator.writeStartObject(); generator.writeStartObject();
for (SearchHitField value : values) { for (SearchHitField value : values) {
if (value.getValues().size() > 1) { if (value.getValues().size() > 1) {

View File

@ -18,7 +18,6 @@ package com.chatopera.cc.util;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
@ -44,6 +43,7 @@ import javax.net.ssl.SSLSocket;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
@ -114,22 +114,14 @@ public class HttpClientUtil {
} }
apiUrl += param; apiUrl += param;
String result = null; String result = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpPost = new HttpGet(apiUrl);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity(); HttpGet httpPost = new HttpGet(apiUrl);
if (entity != null) { try (CloseableHttpClient httpclient = HttpClients.createDefault();
InputStream instream = entity.getContent(); CloseableHttpResponse response = httpclient.execute(httpPost);
result = IOUtils.toString(instream, "UTF-8"); InputStream inputStream = response.getEntity().getContent();) {
} result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
}finally {
if(httpclient!=null) {
httpclient.close();
}
} }
return result; return result;
} }
@ -141,12 +133,8 @@ public class HttpClientUtil {
* @return * @return
*/ */
public static String doPost(String apiUrl, Map<String, Object> params) { public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try { HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size()); List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) { for (Map.Entry<String, Object> entry : params.entrySet()) {
@ -154,20 +142,15 @@ public class HttpClientUtil {
.getValue().toString()); .getValue().toString());
pairList.add(pair); pairList.add(pair);
} }
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); httpPost.setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
response = httpClient.execute(httpPost); String httpStr = null;
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);) {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8"); httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
} }
return httpStr; return httpStr;
} }
@ -180,37 +163,24 @@ public class HttpClientUtil {
* @throws IOException * @throws IOException
*/ */
public static String doPost(String apiUrl, String json) throws IOException { public static String doPost(String apiUrl, String json) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl); HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig); httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json,"UTF-8");//解决中文乱码问题 StringEntity stringEntity = new StringEntity(json, "UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json"); stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity); httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);) {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8"); return EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return null;
} }
} }
if(httpClient!=null) {
httpClient.close();
}
}
return httpStr;
}
/** /**
* 发送 POST 请求HTTPdoPostToSkype形式 * 发送 POST 请求HTTPdoPostToSkype形式