fix: repair shadow candidate planning and site runtime errors
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
package com.ruoyi.Dzp;
|
||||
|
||||
|
||||
import com.ruoyi.Dzp.domain.basLed;
|
||||
import com.ruoyi.Dzp.mapper.BasLedMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -9,7 +8,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api2dzp")
|
||||
@@ -17,104 +16,46 @@ public class DzpSend {
|
||||
@Autowired
|
||||
private BasLedMapper mapper;
|
||||
|
||||
// Both scheduled tasks use the device's existing local port. A busy port is retried next tick.
|
||||
private final ReentrantLock portOwner = new ReentrantLock();
|
||||
|
||||
@Scheduled(fixedDelay = 1000)
|
||||
public void InLed() throws IOException {
|
||||
basLed basLed = new basLed();
|
||||
basLed.setSendFlag("0");
|
||||
basLed.setId(1);
|
||||
List<com.ruoyi.Dzp.domain.basLed> basLeds = mapper.selectBasLedList(basLed);
|
||||
if (basLeds != null && basLeds.size() > 0 && (basLeds.get(0).getModel().equals("1") || basLeds.get(0).getModel().equals("2"))) {
|
||||
MyUdpSocket myUdpSocket = new MyUdpSocket(6666);
|
||||
ProtocolDemo.my_udp = myUdpSocket;
|
||||
String ip = basLeds.get(0).getIpAddress();
|
||||
String msgProductTitle = "物资编码:";
|
||||
String msgProduct = basLeds.get(0).getProduct_id();
|
||||
String msgSpecTitle = "物资规格:";
|
||||
String msgSpec = basLeds.get(0).getSpec();
|
||||
String msg3 = "托盘条码:" + basLeds.get(0).getTrayCode();
|
||||
String msg4 = null;
|
||||
if (basLeds.get(0).getModel().equals("1")) {
|
||||
msg4 = "入库数量:";
|
||||
} else {
|
||||
msg4 = "出库数量:";
|
||||
}
|
||||
String ms7 = "物资名称:";
|
||||
String msg8 = basLeds.get(0).getProductName();
|
||||
String msgQuantity = basLeds.get(0).getQuantity();
|
||||
if (ProtocolDemo.demo_play_chapterschedule4(ip, msgProductTitle, msgSpecTitle, msg4, msg3, msgSpec, msgProduct, ms7, msg8, msgQuantity)) {
|
||||
basLeds.get(0).setSendFlag("1");
|
||||
mapper.updateBasLed(basLeds.get(0));
|
||||
}
|
||||
myUdpSocket.close();
|
||||
|
||||
}
|
||||
basLed basLed2 = new basLed();
|
||||
basLed2.setSendFlag("0");
|
||||
basLed2.setId(2);
|
||||
List<com.ruoyi.Dzp.domain.basLed> basLeds2 = mapper.selectBasLedList(basLed2);
|
||||
if (basLeds2 != null && basLeds2.size() > 0 && (basLeds2.get(0).getModel().equals("1") || basLeds2.get(0).getModel().equals("2"))) {
|
||||
MyUdpSocket myUdpSocket = new MyUdpSocket(6666);
|
||||
ProtocolDemo.my_udp = myUdpSocket;
|
||||
|
||||
String ip = basLeds2.get(0).getIpAddress();
|
||||
String msgProductTitle = "物资编码:";
|
||||
String msgProduct = basLeds2.get(0).getProduct_id();
|
||||
String msgSpecTitle = "物资规格:";
|
||||
String msgSpec = basLeds2.get(0).getSpec();
|
||||
String msg3 = "托盘条码:" + basLeds2.get(0).getTrayCode();
|
||||
String msg4 = null;
|
||||
if (basLeds2.get(0).getModel().equals("1")) {
|
||||
msg4 = "入库数量:";
|
||||
} else {
|
||||
msg4 = "出库数量:";
|
||||
}
|
||||
String ms7 = "物资名称:";
|
||||
String msg8 = basLeds2.get(0).getProductName();
|
||||
String msgQuantity = basLeds2.get(0).getQuantity();
|
||||
if (ProtocolDemo.demo_play_chapterschedule4(ip, msgProductTitle, msgSpecTitle, msg4, msg3, msgSpec, msgProduct, ms7, msg8, msgQuantity)) {
|
||||
basLeds2.get(0).setSendFlag("1");
|
||||
mapper.updateBasLed(basLeds2.get(0));
|
||||
}
|
||||
|
||||
myUdpSocket.close();
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void InLed() throws IOException { sendPending(false); }
|
||||
|
||||
@Scheduled(fixedDelay = 1000)
|
||||
public void ErrorLed() throws IOException {
|
||||
basLed basLed = new basLed();
|
||||
basLed.setSendFlag("0");
|
||||
basLed.setId(1);
|
||||
List<com.ruoyi.Dzp.domain.basLed> basLeds = mapper.selectBasLedList(basLed);
|
||||
if (basLeds != null && basLeds.size() > 0 && basLeds.get(0).getModel().equals("3")) {
|
||||
MyUdpSocket myUdpSocket = new MyUdpSocket(6666);
|
||||
ProtocolDemo.my_udp = myUdpSocket;
|
||||
String ip = basLeds.get(0).getIpAddress();
|
||||
if (ProtocolDemo.demo_play_chapterschedule2(ip, "报警信息", basLeds.get(0).getErrorMsg())) {
|
||||
basLeds.get(0).setSendFlag("1");
|
||||
mapper.updateBasLed(basLeds.get(0));
|
||||
}
|
||||
myUdpSocket.close();
|
||||
public void ErrorLed() throws IOException { sendPending(true); }
|
||||
|
||||
}
|
||||
basLed basLed2 = new basLed();
|
||||
basLed2.setSendFlag("0");
|
||||
basLed2.setId(2);
|
||||
List<com.ruoyi.Dzp.domain.basLed> basLeds2 = mapper.selectBasLedList(basLed2);
|
||||
if (basLeds2 != null && basLeds2.size() > 0 && basLeds2.get(0).getModel().equals("3")) {
|
||||
MyUdpSocket myUdpSocket = new MyUdpSocket(6666);
|
||||
ProtocolDemo.my_udp = myUdpSocket;
|
||||
String ip = basLeds2.get(0).getIpAddress();
|
||||
if (ProtocolDemo.demo_play_chapterschedule2(ip, "报警信息", basLeds2.get(0).getErrorMsg())) {
|
||||
basLeds2.get(0).setSendFlag("1");
|
||||
mapper.updateBasLed(basLeds2.get(0));
|
||||
private void sendPending(boolean alarm) throws IOException {
|
||||
if (!portOwner.tryLock()) return;
|
||||
try {
|
||||
for (int id = 1; id <= 2; id++) {
|
||||
basLed query = new basLed();
|
||||
query.setId(id);
|
||||
query.setSendFlag("0");
|
||||
var records = mapper.selectBasLedList(query);
|
||||
if (records == null || records.isEmpty()) continue;
|
||||
basLed record = records.get(0);
|
||||
boolean matchingModel = alarm ? "3".equals(record.getModel())
|
||||
: "1".equals(record.getModel()) || "2".equals(record.getModel());
|
||||
if (!matchingModel) continue;
|
||||
boolean sent;
|
||||
try (MyUdpSocket socket = openSocket()) {
|
||||
sent = alarm
|
||||
? ProtocolDemo.demo_play_chapterschedule2(socket, record.getIpAddress(), "报警信息", record.getErrorMsg())
|
||||
: ProtocolDemo.demo_play_chapterschedule4(socket, record.getIpAddress(), "物资编码:", "物资规格:",
|
||||
"1".equals(record.getModel()) ? "入库数量:" : "出库数量:",
|
||||
"托盘条码:" + record.getTrayCode(), record.getSpec(), record.getProduct_id(),
|
||||
"物资名称:", record.getProductName(), record.getQuantity());
|
||||
}
|
||||
if (sent) {
|
||||
record.setSendFlag("1");
|
||||
mapper.updateBasLed(record);
|
||||
}
|
||||
}
|
||||
myUdpSocket.close();
|
||||
} finally {
|
||||
portOwner.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
MyUdpSocket openSocket() throws IOException { return new MyUdpSocket(6666); }
|
||||
}
|
||||
|
||||
@@ -6,88 +6,73 @@ import java.nio.ByteBuffer;
|
||||
import java.nio.channels.DatagramChannel;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.util.Set;
|
||||
|
||||
public class MyUdpSocket {
|
||||
private DatagramChannel channel;
|
||||
private Selector selector;
|
||||
private final int MAX_SIZE = 1280;
|
||||
private static int client_port;
|
||||
private static String client_ip;
|
||||
ByteBuffer receive_buffer = ByteBuffer.allocate(MAX_SIZE);
|
||||
/** One exchange owns its channel, selector, receive buffer and peer address. */
|
||||
public class MyUdpSocket implements AutoCloseable {
|
||||
private final DatagramChannel channel;
|
||||
private final Selector selector;
|
||||
private int clientPort;
|
||||
private String clientIp;
|
||||
private final ByteBuffer receiveBuffer = ByteBuffer.allocate(1280);
|
||||
|
||||
public MyUdpSocket(int port) throws IOException {
|
||||
channel = DatagramChannel.open();
|
||||
selector = Selector.open();
|
||||
Selector opened = null;
|
||||
try {
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͨ<EFBFBD><CDA8>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģʽ
|
||||
opened = Selector.open();
|
||||
channel.configureBlocking(false);
|
||||
//<2F><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><D7BD><EFBFBD>ͨ<EFBFBD><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><D7BD>֣<EFBFBD><D6A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><D7BD>ְ<D6B0><F3B6A8B5><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD>˿<EFBFBD>
|
||||
channel.socket().bind(new InetSocketAddress(port));
|
||||
//Ϊͨ<CEAA><CDA8>ѡ<EFBFBD><D1A1><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>ͨ<EFBFBD><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1><EFBFBD><EFBFBD><EFBFBD>
|
||||
channel.register(selector, SelectionKey.OP_READ);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
channel.bind(new InetSocketAddress(port));
|
||||
channel.register(opened, SelectionKey.OP_READ);
|
||||
selector = opened;
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
if (opened != null) {
|
||||
try { opened.close(); } catch (IOException close) { failure.addSuppressed(close); }
|
||||
}
|
||||
try { channel.close(); } catch (IOException close) { failure.addSuppressed(close); }
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
public final void send(String ip, int port, byte[] buffer, int size) throws IOException {
|
||||
InetSocketAddress client = new InetSocketAddress(ip, port);
|
||||
channel.send(ByteBuffer.wrap(buffer, 0, size), client); //<2F><>EchoClient<6E>ظ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>ݱ<EFBFBD>
|
||||
channel.send(ByteBuffer.wrap(buffer, 0, size), new InetSocketAddress(ip, port));
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void close() throws IOException {
|
||||
selector.close();
|
||||
channel.close();
|
||||
try { selector.close(); } finally { channel.close(); }
|
||||
}
|
||||
|
||||
public final int get_client_port() {
|
||||
return client_port;
|
||||
}
|
||||
|
||||
public final String get_client_ip() {
|
||||
return client_ip;
|
||||
}
|
||||
public final int get_client_port() { return clientPort; }
|
||||
public final String get_client_ip() { return clientIp; }
|
||||
|
||||
public final void get_receive_buffer(byte[] buffer) {
|
||||
receive_buffer.get(buffer);
|
||||
get_receive_packet(buffer, buffer.length);
|
||||
}
|
||||
|
||||
public final int receive() {
|
||||
try {
|
||||
receive_buffer.clear();
|
||||
receiveBuffer.clear();
|
||||
if (selector.select(10) != 0) {
|
||||
Set<SelectionKey> readyKeys = selector.selectedKeys();
|
||||
for (SelectionKey key : readyKeys) {
|
||||
readyKeys.remove(key);
|
||||
if (key.isReadable()) {
|
||||
DatagramChannel dc = (DatagramChannel) key.channel();
|
||||
InetSocketAddress client = (InetSocketAddress) dc.receive(receive_buffer); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>Client<6E><74><EFBFBD><EFBFBD><EFBFBD>ݱ<EFBFBD>
|
||||
if (client != null) {
|
||||
client_ip = client.getAddress().getHostAddress();
|
||||
client_port = client.getPort();
|
||||
//System.out.println(client_ip+":"+client_port+" size="+receive_buffer.position());
|
||||
key.interestOps(SelectionKey.OP_READ);
|
||||
return receive_buffer.position();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
return 0;
|
||||
var keys = selector.selectedKeys().iterator();
|
||||
while (keys.hasNext()) {
|
||||
SelectionKey key = keys.next();
|
||||
keys.remove();
|
||||
if (!key.isValid() || !key.isReadable()) continue;
|
||||
InetSocketAddress peer = (InetSocketAddress) channel.receive(receiveBuffer);
|
||||
if (peer != null) {
|
||||
clientIp = peer.getAddress().getHostAddress();
|
||||
clientPort = peer.getPort();
|
||||
return receiveBuffer.position();
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new java.io.UncheckedIOException("LED receive failed", e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public final void get_receive_packet(byte[] packet, int size) {
|
||||
int i;
|
||||
for (i = 0; i < size; i++) {
|
||||
packet[i] = receive_buffer.array()[i];
|
||||
}
|
||||
System.arraycopy(receiveBuffer.array(), 0, packet, 0, size);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.awt.*;
|
||||
//import java.util.Calendar;
|
||||
|
||||
public class ProtocolDemo {
|
||||
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ProtocolDemo.class);
|
||||
|
||||
// ====<3D><><EFBFBD>붯<EFBFBD><EBB6AF><EFBFBD><EFBFBD>ʽ<EFBFBD>б<EFBFBD>(<28><>ֵ<EFBFBD><D6B5>0<EFBFBD><30>ʼ)====
|
||||
// 0 = '<27><><EFBFBD>',
|
||||
@@ -101,10 +102,19 @@ public class ProtocolDemo {
|
||||
|
||||
//<2F><><EFBFBD><EFBFBD>UDP<44><50><EFBFBD><EFBFBD>bufferΪ<72><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݣ<EFBFBD>sizeΪ<65><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݳ<EFBFBD><DDB3><EFBFBD>
|
||||
public static int udp_receive(byte[] buffer) {
|
||||
return udp_receive(my_udp, buffer);
|
||||
}
|
||||
|
||||
private static int udp_receive(MyUdpSocket socket, byte[] buffer) {
|
||||
int size = 0;
|
||||
size = my_udp.receive();
|
||||
try {
|
||||
size = socket.receive();
|
||||
} catch (java.io.UncheckedIOException e) {
|
||||
log.debug("LED receive attempt failed; the bounded exchange will retry", e);
|
||||
return 0;
|
||||
}
|
||||
if (size > 0) {
|
||||
my_udp.get_receive_packet(buffer, size);
|
||||
socket.get_receive_packet(buffer, size);
|
||||
}
|
||||
return size;
|
||||
}
|
||||
@@ -415,6 +425,20 @@ public class ProtocolDemo {
|
||||
}
|
||||
|
||||
public static boolean send_data1(String ip) {
|
||||
return send_data1(my_udp, ledsender, ip);
|
||||
}
|
||||
|
||||
private static boolean udp_send1(MyUdpSocket socket, String ip, byte[] buffer, int size) {
|
||||
try {
|
||||
socket.send(ip, ledport, buffer, size);
|
||||
return true;
|
||||
} catch (java.io.IOException e) {
|
||||
log.debug("LED send attempt failed; the bounded exchange will retry", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean send_data1(MyUdpSocket socket, LEDSender2010 ledsender, String ip) {
|
||||
int size = 0;
|
||||
byte[] packet = new byte[1280];
|
||||
int i, j, k, x, r;
|
||||
@@ -435,9 +459,9 @@ public class ProtocolDemo {
|
||||
ok = false;
|
||||
for (tx = 0; tx < tx_repeat; tx++) {
|
||||
size = ledsender.pkg_begin(packet, addr);
|
||||
udp_send1(ip, packet, size);
|
||||
if (!udp_send1(socket, ip, packet, size)) continue;
|
||||
for (x = 0; x < 50; x++) {
|
||||
size = udp_receive(packet);
|
||||
size = udp_receive(socket, packet);
|
||||
if (size > 0 && ledsender.parse_trans_respond(packet, size, LEDSender2010.PKC_BEGIN, 0) > 0) {
|
||||
ok = true;
|
||||
break;
|
||||
@@ -459,9 +483,9 @@ public class ProtocolDemo {
|
||||
for (tx = 0; tx < tx_repeat; tx++) {
|
||||
j = i;
|
||||
size = ledsender.pkg_data(packet, addr, i, 512);
|
||||
udp_send1(ip, packet, size);
|
||||
if (!udp_send1(socket, ip, packet, size)) continue;
|
||||
for (x = 0; x < 50; x++) {
|
||||
size = udp_receive(packet);
|
||||
size = udp_receive(socket, packet);
|
||||
if (size > 0) {
|
||||
r = ledsender.parse_trans_respond(packet, size,LEDSender2010.PKC_DATA, i);
|
||||
switch (r) {
|
||||
@@ -490,9 +514,9 @@ public class ProtocolDemo {
|
||||
ok = false;
|
||||
for (tx = 0; tx < tx_repeat; tx++) {
|
||||
size = ledsender.pkg_end(packet, addr, i);
|
||||
udp_send1(ip, packet, size);
|
||||
if (!udp_send1(socket, ip, packet, size)) continue;
|
||||
for (x = 0; x < 50; x++) {
|
||||
size = udp_receive(packet);
|
||||
size = udp_receive(socket, packet);
|
||||
if (size > 0 && ledsender.parse_trans_respond(packet, size, LEDSender2010.PKC_END, i) > 0) {
|
||||
ok = true;
|
||||
break;
|
||||
@@ -870,6 +894,11 @@ public class ProtocolDemo {
|
||||
|
||||
//<2F>Զ<EFBFBD><D4B6>巽<EFBFBD><E5B7BD> <20><>̬<EFBFBD><CCAC>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ
|
||||
public static boolean demo_play_chapterschedule2(String ip, String msg1, String msg2) {
|
||||
return demo_play_chapterschedule2(my_udp, ip, msg1, msg2);
|
||||
}
|
||||
|
||||
public static boolean demo_play_chapterschedule2(MyUdpSocket socket, String ip, String msg1, String msg2) {
|
||||
LEDSender2010 ledsender = new LEDSender2010();
|
||||
|
||||
//<2F><><EFBFBD>ɽ<EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD>
|
||||
ledsender.MakeRoot(LEDSender2010.ROOT_PLAY,LEDSender2010.COLOR_TYPE_DOUBLE);
|
||||
@@ -882,7 +911,7 @@ public class ProtocolDemo {
|
||||
ledsender.AddText(0, 11, 192, 32, msg1, "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", 16, Color.BLACK, Color.YELLOW, 0, 2, false, 1, 0, 2, 0, 0, 5, 10000);
|
||||
ledsender.AddText(0, 37, 192, 32, msg2, "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", 16, Color.BLACK, Color.YELLOW, 0, 2, false, 1, 0, 2, 0, 0, 5, 10000);
|
||||
|
||||
return send_data1(ip);
|
||||
return send_data1(socket, ledsender, ip);
|
||||
}
|
||||
|
||||
//<2F>Զ<EFBFBD><D4B6>巽<EFBFBD><E5B7BD><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
@@ -931,6 +960,11 @@ public class ProtocolDemo {
|
||||
|
||||
|
||||
public static boolean demo_play_chapterschedule4(String ip, String msg1, String msg2, String msg3, String msg,String msg5,String msg6,String msg7,String msg8, String msgQuantity) {
|
||||
return demo_play_chapterschedule4(my_udp, ip, msg1, msg2, msg3, msg, msg5, msg6, msg7, msg8, msgQuantity);
|
||||
}
|
||||
|
||||
public static boolean demo_play_chapterschedule4(MyUdpSocket socket, String ip, String msg1, String msg2, String msg3, String msg, String msg5, String msg6, String msg7, String msg8, String msgQuantity) {
|
||||
LEDSender2010 ledsender = new LEDSender2010();
|
||||
|
||||
//<2F><><EFBFBD>ɽ<EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD>
|
||||
ledsender.MakeRoot(LEDSender2010.ROOT_PLAY,LEDSender2010.COLOR_TYPE_DOUBLE);
|
||||
@@ -951,7 +985,7 @@ public class ProtocolDemo {
|
||||
ledsender.AddText(65, 60, 192, 21, msg8, "<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", 13, Color.BLACK, Color.YELLOW, 0, 2, false, 1, 0, 7, 0, 0, 5, 3000);
|
||||
|
||||
|
||||
return send_data1(ip);
|
||||
return send_data1(socket, ledsender, ip);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ruoyi.algorithm.shadow;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
/** Bounded evidence in the existing decision reason; no live business reads or extra DB writes. */
|
||||
final class ShadowCandidateEvidence {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
static String describe(List<ShadowStockReference> candidates) {
|
||||
var rows = candidates.stream().map(c -> new Candidate(c.getStockId(), c.getSpaceId(), c.getTrayNo(),
|
||||
c.getProjectNo(), c.getProductId(), c.getAvailableQuantity(), c.getTrayItemCount(), c.getTrayJobCount(),
|
||||
c.getSpare1(), c.getSpare2(), c.getSpare3(), c.getVoltage(), c.getPhase())).toList();
|
||||
try {
|
||||
String hash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JSON.writeValueAsBytes(rows)));
|
||||
List<Candidate> retained = new ArrayList<>();
|
||||
String detail = "[]";
|
||||
for (Candidate row : rows) {
|
||||
retained.add(row);
|
||||
String proposed = JSON.writeValueAsString(retained);
|
||||
if (proposed.length() > 1100) { retained.remove(retained.size() - 1); break; }
|
||||
detail = proposed;
|
||||
}
|
||||
return "candidateCount=" + rows.size() + "; candidateSha256=" + hash
|
||||
+ "; candidateEvidenceComplete=" + (retained.size() == rows.size())
|
||||
+ "; candidateEvidence=" + detail;
|
||||
} catch (JsonProcessingException | NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("Could not capture outbound candidate evidence", e);
|
||||
}
|
||||
}
|
||||
|
||||
private record Candidate(String stock, String space, String tray, String project, String product,
|
||||
BigDecimal availableQuantity, Integer trayItems, Integer trayJobs,
|
||||
String spare1, String spare2, String spare3, String voltage, String phase) { }
|
||||
}
|
||||
@@ -99,6 +99,13 @@ public class ShadowPlanningEngine {
|
||||
}
|
||||
List<ShadowStockReference> candidates = inputMapper.selectProjectOutboundCandidates(
|
||||
warehouseId, snapshot.generation(), stockoutDetailId);
|
||||
return withCandidateEvidence(planProjectCandidates(snapshot, stockoutDetailId, reference, candidates), candidates);
|
||||
});
|
||||
}
|
||||
|
||||
private OutboundShadowObservation planProjectCandidates(PublishedShadowSnapshot snapshot, String stockoutDetailId,
|
||||
ShadowStockReference reference, List<ShadowStockReference> candidates) {
|
||||
String warehouseId = snapshot.warehouseId();
|
||||
if (candidates.size() > MAX_OUTBOUND_CANDIDATES) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_CANDIDATE_LIMIT", "Eligible candidate set exceeds 200 rows");
|
||||
@@ -117,16 +124,33 @@ public class ShadowPlanningEngine {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_UNSUPPORTED_PRODUCT_SCOPE", "Planner requires one nonblank candidate product");
|
||||
}
|
||||
// The shared planner is single-source and does not apply the site's optional predicates.
|
||||
// Keep it unchanged; validate its proposal against the generation-qualified candidate set.
|
||||
List<ShadowStockReference> idle = candidates.stream()
|
||||
.filter(candidate -> Integer.valueOf(0).equals(candidate.getTrayJobCount())).toList();
|
||||
if (idle.isEmpty()) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_EXISTING_TRAY_JOB", "Existing tray jobs require unsupported delivery compatibility checks");
|
||||
}
|
||||
List<ShadowStockReference> sufficient = idle.stream().filter(candidate -> candidate.getAvailableQuantity() != null
|
||||
&& candidate.getAvailableQuantity().compareTo(reference.getRequestedQuantity()) >= 0).toList();
|
||||
if (sufficient.isEmpty()) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_MULTI_STOCK_REQUEST", "No single eligible stock row covers the remaining quantity");
|
||||
}
|
||||
if (sufficient.stream().anyMatch(candidate -> isBlank(candidate.getStockId()) || isBlank(candidate.getSpaceId())
|
||||
|| isBlank(candidate.getTrayNo()) || candidate.getTrayItemCount() == null || candidate.getTrayItemCount() < 1)
|
||||
|| sufficient.stream().map(ShadowStockReference::getSpaceId).distinct().count() != sufficient.size()) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_AMBIGUOUS_STOCK_SCOPE", "Each eligible source must identify exactly one sufficient stock row");
|
||||
}
|
||||
OutboundRequest request = new OutboundRequest(stockoutDetailId, null,
|
||||
projects.get(0), products.get(0), null, null, null, false);
|
||||
OutboundPlan plan = schedulingFacade.planOutboundFromPublishedSnapshot(warehouseId, request);
|
||||
OutboundPlan plan = schedulingFacade.planShadowOutboundCandidates(warehouseId, request,
|
||||
sufficient.stream().map(ShadowStockReference::getStockId).collect(java.util.stream.Collectors.toSet()));
|
||||
if (plan.assignment().isEmpty()) {
|
||||
return toOutboundObservation(snapshot, stockoutDetailId, reference, plan);
|
||||
}
|
||||
var assignment = plan.assignment().orElseThrow();
|
||||
var selected = candidates.stream().filter(candidate ->
|
||||
var selected = sufficient.stream().filter(candidate ->
|
||||
Objects.equals(candidate.getSpaceId(), assignment.sourceSpaceId())
|
||||
&& Objects.equals(candidate.getTrayNo(), assignment.trayNo())
|
||||
&& Objects.equals(candidate.getProjectNo(), assignment.projectNo())
|
||||
@@ -140,10 +164,6 @@ public class ShadowPlanningEngine {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_EXISTING_TRAY_JOB", "Existing tray jobs require unsupported delivery compatibility checks");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(stock.getTrayItemCount())) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
"SKIPPED_MULTI_STOCK_TRAY", "Selected tray does not contain exactly one inventory row");
|
||||
}
|
||||
if (stock.getAvailableQuantity() == null
|
||||
|| stock.getAvailableQuantity().compareTo(reference.getRequestedQuantity()) < 0) {
|
||||
return unavailableProject(snapshot, stockoutDetailId, reference,
|
||||
@@ -157,7 +177,14 @@ public class ShadowPlanningEngine {
|
||||
return new OutboundShadowObservation(true, snapshot.generation(), warehouseId,
|
||||
snapshot.synchronizedAt(), snapshot.sourceSignature(), stockoutDetailId,
|
||||
"READY", stock.getStockId(), stock.getSpaceId(), reason.toString());
|
||||
});
|
||||
}
|
||||
|
||||
private OutboundShadowObservation withCandidateEvidence(OutboundShadowObservation observation,
|
||||
List<ShadowStockReference> candidates) {
|
||||
return new OutboundShadowObservation(observation.observed(), observation.snapshotGeneration(),
|
||||
observation.warehouseId(), observation.snapshotSynchronizedAt(), observation.sourceSignature(),
|
||||
observation.requestId(), observation.resultCode(), observation.proposedStockId(), observation.proposedSpaceId(),
|
||||
abbreviate(observation.reason(), 1900) + "; " + ShadowCandidateEvidence.describe(candidates));
|
||||
}
|
||||
|
||||
private OutboundShadowObservation unavailableProject(PublishedShadowSnapshot snapshot, String requestId,
|
||||
@@ -195,8 +222,7 @@ public class ShadowPlanningEngine {
|
||||
UUID.randomUUID().toString(), observation.warehouseId(), "INBOUND_COMPARE",
|
||||
observation.snapshotGeneration(), observation.snapshotSynchronizedAt(),
|
||||
observation.sourceSignature(),
|
||||
observation.observed() && "READY".equals(observation.resultCode()) && "10".equals(legacyResultCode)
|
||||
? comparisonCode(observation.proposedSpaceId(), legacySpaceId) : "NOT_COMPARABLE",
|
||||
inboundComparisonCode(observation, legacyResultCode, legacySpaceId),
|
||||
inboundComparisonReason(observation, legacyResultCode, legacySpaceId));
|
||||
requireComparisonInserted(inserted);
|
||||
});
|
||||
@@ -244,22 +270,29 @@ public class ShadowPlanningEngine {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_MISSING_TASK_DETAILS",
|
||||
"Job was captured but has no task details");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(reference.getFieldGroupCount())) {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_AMBIGUOUS_LEGACY_FIELDS",
|
||||
"Legacy TOP (1) has no ordering and task details have different spare1/2/3 values");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(reference.getProductScopeCount()) || isBlank(reference.getProductId())) {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_MULTI_PRODUCT_INPUT",
|
||||
"Single-product planner cannot represent this task product/lot scope");
|
||||
if (reference.getFieldGroupCount() == null || reference.getFieldGroupCount() < 1
|
||||
|| reference.getProductScopeCount() == null || reference.getProductScopeCount() < 1) {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_MISSING_PREDICATE_INPUT",
|
||||
"Task field or product scope counts are missing");
|
||||
}
|
||||
if (isBlank(reference.getProjectNo()) || "999".equals(reference.getProjectNo().trim())
|
||||
|| "COMMON".equalsIgnoreCase(reference.getProjectNo().trim())) {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_UNSUPPORTED_COMMON_PROJECT",
|
||||
"Common-project mapping and pool policy require separate validation");
|
||||
}
|
||||
boolean ambiguousFields = reference.getFieldGroupCount() > 1;
|
||||
boolean multipleProducts = reference.getProductScopeCount() > 1;
|
||||
List<String> eligibleSpaces = inputMapper.selectInboundEligibleSpaces(warehouseId,
|
||||
snapshot.generation(), taskNo, trayNo);
|
||||
if (eligibleSpaces.isEmpty()) {
|
||||
return unavailableInbound(snapshot, taskNo, trayNo, reference, "SKIPPED_NO_CONSERVATIVE_SPACE",
|
||||
ambiguousFields ? "No fully empty lane; Legacy TOP (1) field choice remains unknown"
|
||||
: "No space satisfies the captured conservative Legacy predicates");
|
||||
}
|
||||
InboundRequest request = new InboundRequest(reference.getRequestId(), reference.getTrayNo(),
|
||||
reference.getProjectNo(), reference.getProductId(), reference.getLotNo(),
|
||||
null, null, null, Set.of(), null);
|
||||
reference.getProjectNo(), multipleProducts ? null : reference.getProductId(),
|
||||
multipleProducts ? null : reference.getLotNo(),
|
||||
null, null, null, Set.of(), null, Set.copyOf(eligibleSpaces));
|
||||
InboundPlanningResult result = schedulingFacade.planInboundFromPublishedSnapshot(warehouseId, request);
|
||||
InboundPlan plan = result.plan();
|
||||
if (plan.assignment().isPresent()) {
|
||||
@@ -272,9 +305,11 @@ public class ShadowPlanningEngine {
|
||||
}
|
||||
return new InboundShadowObservation(true, snapshot.generation(), warehouseId,
|
||||
snapshot.synchronizedAt(), snapshot.sourceSignature(),
|
||||
reference.getRequestId(), "READY", assignment.spaceId(),
|
||||
reference.getRequestId(), ambiguousFields ? "READY_CONSERVATIVE" : "READY", assignment.spaceId(),
|
||||
inboundDiagnostic(snapshot, taskNo, trayNo, reference,
|
||||
"legacyEligibility=STRICT_GROUP_OR_EMPTY; " + assignment.reason()));
|
||||
"legacyEligibility=" + (ambiguousFields ? "EMPTY_LANE_ONLY" : "STRICT_GROUP_OR_EMPTY")
|
||||
+ "; inputScope=" + (multipleProducts ? "PROJECT_MULTI_ITEM_OPEN" : "SINGLE_ITEM")
|
||||
+ "; eligibleSpaceCount=" + eligibleSpaces.size() + "; " + assignment.reason()));
|
||||
}
|
||||
var rejection = plan.rejection().orElseThrow();
|
||||
return InboundShadowObservation.unavailable(snapshot,
|
||||
@@ -555,6 +590,16 @@ public class ShadowPlanningEngine {
|
||||
return shadowSpaceId.equals(legacySpaceId) ? "MATCH" : "DIFFERENT";
|
||||
}
|
||||
|
||||
private String inboundComparisonCode(InboundShadowObservation observation, String legacyCode, String legacySpace) {
|
||||
if (!observation.observed() || !"10".equals(legacyCode)) return "NOT_COMPARABLE";
|
||||
if (!"READY".equals(observation.resultCode()) && !"READY_CONSERVATIVE".equals(observation.resultCode())) {
|
||||
return "NOT_COMPARABLE";
|
||||
}
|
||||
String result = comparisonCode(observation.proposedSpaceId(), legacySpace);
|
||||
return "READY_CONSERVATIVE".equals(observation.resultCode()) && !"NOT_COMPARABLE".equals(result)
|
||||
? result + "_CONSERVATIVE" : result;
|
||||
}
|
||||
|
||||
private boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
@@ -19,6 +19,10 @@ public interface ShadowInputMapper {
|
||||
@Param("generation") long generation, @Param("taskNo") String taskNo,
|
||||
@Param("trayNo") String trayNo, @Param("spaceId") String spaceId);
|
||||
|
||||
List<String> selectInboundEligibleSpaces(@Param("warehouseId") String warehouseId,
|
||||
@Param("generation") long generation, @Param("taskNo") String taskNo,
|
||||
@Param("trayNo") String trayNo);
|
||||
|
||||
ShadowStockReference selectProjectOutboundReference(@Param("warehouseId") String warehouseId,
|
||||
@Param("generation") long generation,
|
||||
@Param("stockoutDetailId") String stockoutDetailId);
|
||||
|
||||
@@ -32,6 +32,17 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<!-- Conservative subset valid in either Legacy project-count branch. Ranking remains in the planner. -->
|
||||
<select id="countInboundEligibleSpace" resultType="int">
|
||||
select count(*)
|
||||
<include refid="inboundEligibleSpaces"/>
|
||||
and cargo.space_id = #{spaceId}
|
||||
</select>
|
||||
|
||||
<select id="selectInboundEligibleSpaces" resultType="string">
|
||||
select cargo.space_id
|
||||
<include refid="inboundEligibleSpaces"/>
|
||||
order by cargo.space_id
|
||||
</select>
|
||||
|
||||
<sql id="inboundEligibleSpaces">
|
||||
from alg.shadow_inbound_request_snapshot input
|
||||
join alg.cargo_space_snapshot cargo
|
||||
on cargo.warehouse_id = input.warehouse_id
|
||||
@@ -39,11 +50,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
where input.warehouse_id = #{warehouseId} and input.snapshot_generation = #{generation}
|
||||
and input.task_no = #{taskNo} and input.tray_no = #{trayNo}
|
||||
and input.predicate_version = 1 and input.detail_count > 0
|
||||
and input.field_group_count = 1 and input.product_scope_count = 1
|
||||
and input.field_group_count > 0 and input.product_scope_count > 0
|
||||
and input.tray_job_count = 1 and input.legacy_scope_complete = 1
|
||||
and nullif(ltrim(rtrim(input.project_no)), '') is not null
|
||||
and input.project_no not in ('999', 'COMMON')
|
||||
and cargo.space_id = #{spaceId} and cargo.space_status = '1' and cargo.locked = 'N'
|
||||
and cargo.space_status = '1' and cargo.locked = 'N'
|
||||
and nullif(ltrim(rtrim(cargo.tray_code)), '') is null
|
||||
and cargo.this_cargo_area in ('A', 'C')
|
||||
and nullif(ltrim(rtrim(cargo.lane_code)), '') is not null
|
||||
@@ -68,7 +79,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
or exists (select 1 from alg.inventory_item_snapshot stock
|
||||
where stock.warehouse_id = lane.warehouse_id
|
||||
and stock.snapshot_generation = lane.snapshot_generation and stock.space_id = lane.space_id)))
|
||||
or exists (
|
||||
or (input.field_group_count = 1 and exists (
|
||||
select 1 from alg.cargo_space_snapshot resident
|
||||
join alg.inventory_item_snapshot stock
|
||||
on stock.warehouse_id = resident.warehouse_id and stock.snapshot_generation = resident.snapshot_generation
|
||||
@@ -77,8 +88,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
and resident.lane_code = cargo.lane_code and resident.space_status = '2'
|
||||
and resident.this_cargo_area in ('A', 'C')
|
||||
and stock.project_no = input.project_no
|
||||
and stock.spare1 = input.spare1 and stock.spare2 = input.spare2 and stock.spare3 = input.spare3))
|
||||
</select>
|
||||
and stock.spare1 = input.spare1 and stock.spare2 = input.spare2 and stock.spare3 = input.spare3)))
|
||||
</sql>
|
||||
|
||||
<sql id="outboundCandidatePredicate">
|
||||
item.warehouse_id = #{warehouseId}
|
||||
@@ -130,6 +141,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
select top (201)
|
||||
item.stock_id as stockId, item.tray_code as trayNo, item.space_id as spaceId,
|
||||
item.project_no as projectNo, item.product_no as productId,
|
||||
item.spare1, item.spare2, item.spare3, item.voltage, item.phase,
|
||||
item.tray_job_count as trayJobCount,
|
||||
item.quantity - item.out_quantity as availableQuantity,
|
||||
(select count(*) from alg.inventory_item_snapshot trayItem
|
||||
|
||||
98
ruoyi-admin/src/test/java/com/ruoyi/Dzp/DzpSendTest.java
Normal file
98
ruoyi-admin/src/test/java/com/ruoyi/Dzp/DzpSendTest.java
Normal file
@@ -0,0 +1,98 @@
|
||||
package com.ruoyi.Dzp;
|
||||
|
||||
import com.ruoyi.Dzp.domain.basLed;
|
||||
import com.ruoyi.Dzp.mapper.BasLedMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class DzpSendTest {
|
||||
@Test
|
||||
void failedExchangeClosesItsSocketAndDoesNotAcknowledgeTheDisplay() throws Exception {
|
||||
var socket = mock(MyUdpSocket.class);
|
||||
var sender = new DzpSend() { @Override MyUdpSocket openSocket() { return socket; } };
|
||||
var mapper = mock(BasLedMapper.class);
|
||||
ReflectionTestUtils.setField(sender, "mapper", mapper);
|
||||
var record = new basLed(); record.setModel("3"); record.setSendFlag("0"); record.setIpAddress("127.0.0.1"); record.setErrorMsg("alarm");
|
||||
when(mapper.selectBasLedList(any())).thenAnswer(call -> call.getArgument(0, basLed.class).getId() == 1 ? List.of(record) : List.of());
|
||||
try (var protocol = mockStatic(ProtocolDemo.class)) {
|
||||
protocol.when(() -> ProtocolDemo.demo_play_chapterschedule2(socket, "127.0.0.1", "报警信息", "alarm"))
|
||||
.thenThrow(new IllegalStateException("test send failure")).thenReturn(true);
|
||||
assertThatThrownBy(sender::ErrorLed).hasMessage("test send failure");
|
||||
verify(socket).close();
|
||||
verify(mapper, never()).updateBasLed(any());
|
||||
assertThat(record.getSendFlag()).isEqualTo("0");
|
||||
sender.ErrorLed();
|
||||
verify(socket, times(2)).close();
|
||||
verify(mapper).updateBasLed(record);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void busyLocalPortDefersOtherTimerWithoutBlockingOrChangingRows() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var sender = new DzpSend() {
|
||||
@Override MyUdpSocket openSocket() throws IOException {
|
||||
entered.countDown();
|
||||
try { if (!release.await(3, TimeUnit.SECONDS)) throw new IOException("test timeout"); }
|
||||
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); }
|
||||
throw new IOException("fixture port failure");
|
||||
}
|
||||
};
|
||||
var mapper = mock(BasLedMapper.class);
|
||||
ReflectionTestUtils.setField(sender, "mapper", mapper);
|
||||
var record = new basLed(); record.setModel("1"); record.setSendFlag("0");
|
||||
when(mapper.selectBasLedList(any())).thenReturn(List.of(record));
|
||||
var executor = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
var first = executor.submit(() -> { assertThatThrownBy(sender::InLed).isInstanceOf(IOException.class); });
|
||||
assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue();
|
||||
executor.submit(() -> { sender.ErrorLed(); return null; }).get(1, TimeUnit.SECONDS);
|
||||
verify(mapper, times(1)).selectBasLedList(any());
|
||||
verify(mapper, never()).updateBasLed(any());
|
||||
release.countDown();
|
||||
first.get(2, TimeUnit.SECONDS);
|
||||
} finally { release.countDown(); executor.shutdownNow(); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachScheduledMessageBuildsItsOwnPayload() throws Exception {
|
||||
try (var payloads = mockConstruction(LEDSender2010.class,
|
||||
(sender, context) -> when(sender.GetDataSize()).thenReturn((1 << 21) + 1))) {
|
||||
var socket = mock(MyUdpSocket.class);
|
||||
assertThat(ProtocolDemo.demo_play_chapterschedule2(socket, "127.0.0.1", "title1", "one")).isFalse();
|
||||
assertThat(ProtocolDemo.demo_play_chapterschedule2(socket, "127.0.0.1", "title2", "two")).isFalse();
|
||||
assertThat(payloads.constructed()).hasSize(2);
|
||||
verify(payloads.constructed().get(0)).GetDataSize();
|
||||
verify(payloads.constructed().get(1)).GetDataSize();
|
||||
verifyNoInteractions(socket);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void transientSocketErrorsStayInsideTheBoundedProtocolRetry() throws Exception {
|
||||
var socket = mock(MyUdpSocket.class);
|
||||
var payload = mock(LEDSender2010.class);
|
||||
doThrow(new IOException("transient send")).doNothing().when(socket).send(anyString(), anyInt(), any(), anyInt());
|
||||
when(socket.receive()).thenThrow(new java.io.UncheckedIOException(new IOException("transient receive"))).thenReturn(1);
|
||||
when(payload.parse_trans_respond(any(), anyInt(), anyInt(), anyInt())).thenReturn(1);
|
||||
assertThat(ProtocolDemo.send_data1(socket, payload, "127.0.0.1")).isTrue();
|
||||
verify(socket, times(3)).send(anyString(), anyInt(), any(), anyInt());
|
||||
verify(socket, times(3)).receive();
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistentSendFailureStopsAfterFiveAttempts() throws Exception {
|
||||
var socket = mock(MyUdpSocket.class);
|
||||
doThrow(new IOException("unreachable")).when(socket).send(anyString(), anyInt(), any(), anyInt());
|
||||
assertThat(ProtocolDemo.send_data1(socket, mock(LEDSender2010.class), "127.0.0.1")).isFalse();
|
||||
verify(socket, times(5)).send(anyString(), anyInt(), any(), anyInt());
|
||||
verify(socket, never()).receive();
|
||||
}
|
||||
}
|
||||
50
ruoyi-admin/src/test/java/com/ruoyi/Dzp/MyUdpSocketTest.java
Normal file
50
ruoyi-admin/src/test/java/com/ruoyi/Dzp/MyUdpSocketTest.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.ruoyi.Dzp;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.io.IOException;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class MyUdpSocketTest {
|
||||
@Test
|
||||
void occupiedPortFailsConstructionInsteadOfReturningBrokenSocket() throws Exception {
|
||||
try (var occupied = new DatagramSocket(0)) {
|
||||
assertThatThrownBy(() -> new MyUdpSocket(occupied.getLocalPort()))
|
||||
.isInstanceOf(IOException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void receivedPeerBelongsToItsOwnSocket() throws Exception {
|
||||
MyUdpSocket first = new MyUdpSocket(0);
|
||||
MyUdpSocket second = new MyUdpSocket(0);
|
||||
try (var peerOne = new DatagramSocket(0); var peerTwo = new DatagramSocket(0)) {
|
||||
exchange(first, peerOne, (byte) 11);
|
||||
int firstPeer = first.get_client_port();
|
||||
exchange(second, peerTwo, (byte) 22);
|
||||
assertThat(first.get_client_port()).isEqualTo(firstPeer);
|
||||
assertThat(second.get_client_port()).isEqualTo(peerTwo.getLocalPort());
|
||||
first.close();
|
||||
exchange(second, peerTwo, (byte) 33);
|
||||
} finally {
|
||||
first.close();
|
||||
second.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void exchange(MyUdpSocket socket, DatagramSocket peer, byte value) throws Exception {
|
||||
peer.setSoTimeout(1000);
|
||||
socket.send("127.0.0.1", peer.getLocalPort(), new byte[]{value}, 1);
|
||||
var request = new DatagramPacket(new byte[64], 64);
|
||||
peer.receive(request);
|
||||
peer.send(new DatagramPacket(new byte[]{value}, 1, InetAddress.getLoopbackAddress(), request.getPort()));
|
||||
int size = 0;
|
||||
for (int attempt = 0; attempt < 100 && size == 0; attempt++) size = socket.receive();
|
||||
assertThat(size).isEqualTo(1);
|
||||
byte[] result = new byte[1];
|
||||
socket.get_receive_packet(result, 1);
|
||||
assertThat(result).containsExactly(value);
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,23 @@ class ShadowInboundEligibilityTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleProductsWithOneFieldGroupCanContinueTheMatchingProjectLane() {
|
||||
jdbc.update("update alg.shadow_inbound_request_snapshot set detail_count=5,product_scope_count=5,product_id=null,lot_no=null");
|
||||
space("RESIDENT", "LANE", "1", "2", "N", "OLD", "C");
|
||||
stock("RESIDENT", "OLD");
|
||||
assertThat(eligible()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ambiguousFieldGroupsOnlyAllowEntirelyEmptyLanes() {
|
||||
jdbc.update("update alg.shadow_inbound_request_snapshot set detail_count=5,field_group_count=2,product_scope_count=5");
|
||||
assertThat(eligible()).isEqualTo(1);
|
||||
space("RESIDENT", "LANE", "1", "2", "N", "OLD", "C");
|
||||
stock("RESIDENT", "OLD");
|
||||
assertThat(eligible()).isZero();
|
||||
}
|
||||
|
||||
private void space(String id, String lane, String floor, String status, String locked, String tray, String area) {
|
||||
jdbc.update("insert into alg.cargo_space_snapshot values ('01',42,?,?,?,?,?,?,?,'UNRELATED')",
|
||||
id, lane, floor, status, locked, tray, area);
|
||||
|
||||
@@ -61,6 +61,7 @@ class ShadowInboundValidationTest {
|
||||
reference.setTrayJobCount(1);
|
||||
reference.setLegacyScopeComplete(1);
|
||||
when(mapper.selectInboundInput("01", 42, "31331", "TRAY-1")).thenReturn(reference);
|
||||
when(mapper.selectInboundEligibleSpaces("01", 42, "31331", "TRAY-1")).thenReturn(java.util.List.of("SPACE-9"));
|
||||
when(mapper.countInboundEligibleSpace("01", 42, "31331", "TRAY-1", "SPACE-9")).thenReturn(1);
|
||||
var assignment = new InboundAssignment("HPR-1", "SPACE-9", "LANE", 1, 1,
|
||||
InboundLadderRung.CONTINUE, InboundBorrowType.NONE, null,
|
||||
@@ -87,13 +88,22 @@ class ShadowInboundValidationTest {
|
||||
reference.setDetailCount(45);
|
||||
reference.setFieldGroupCount(2);
|
||||
reference.setProductScopeCount(45);
|
||||
assertSkipped("SKIPPED_AMBIGUOUS_LEGACY_FIELDS");
|
||||
var result = plan();
|
||||
assertThat(result.resultCode()).isEqualTo("READY_CONSERVATIVE");
|
||||
assertThat(result.reason()).contains("legacyEligibility=EMPTY_LANE_ONLY");
|
||||
engine.compareInbound(result, "10", "SPACE-9");
|
||||
verify(mapper).insertComparison(any(), any(), eq("INBOUND_COMPARE"), anyLong(), any(), any(),
|
||||
eq("MATCH_CONSERVATIVE"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiProductTrayDoesNotSilentlyUseOneRepresentativeProduct() {
|
||||
reference.setProductScopeCount(2);
|
||||
assertSkipped("SKIPPED_MULTI_PRODUCT_INPUT");
|
||||
assertThat(plan().resultCode()).isEqualTo("READY");
|
||||
verify(facade).planInboundFromPublishedSnapshot(eq("01"), argThat(request ->
|
||||
request.productId() == null && request.lotNo() == null
|
||||
&& request.batchLaneMode() == com.ruoyi.algorithm.inbound.BatchLaneMode.OPEN
|
||||
&& request.eligibleSpaceIds().equals(java.util.Set.of("SPACE-9"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -148,6 +158,12 @@ class ShadowInboundValidationTest {
|
||||
|
||||
private InboundShadowObservation plan() { return engine.planInbound(snapshot, "31331", "TRAY-1"); }
|
||||
|
||||
@Test
|
||||
void noConservativeSpaceDoesNotInventAnUnrestrictedRequest() {
|
||||
when(mapper.selectInboundEligibleSpaces("01", 42, "31331", "TRAY-1")).thenReturn(java.util.List.of());
|
||||
assertSkipped("SKIPPED_NO_CONSERVATIVE_SPACE");
|
||||
}
|
||||
|
||||
private void assertSkipped(String code) {
|
||||
var result = plan();
|
||||
assertThat(result.resultCode()).isEqualTo(code);
|
||||
|
||||
@@ -59,7 +59,7 @@ class ShadowOutboundValidationTest {
|
||||
candidate.setTrayJobCount(0);
|
||||
when(mapper.selectProjectOutboundReference("01", 459L, "DETAIL")).thenReturn(input);
|
||||
when(mapper.selectProjectOutboundCandidates("01", 459L, "DETAIL")).thenReturn(List.of(candidate));
|
||||
when(facade.planOutboundFromPublishedSnapshot(eq("01"), any())).thenReturn(
|
||||
when(facade.planShadowOutboundCandidates(eq("01"), any(), any())).thenReturn(
|
||||
OutboundPlan.ready(new OutboundAssignment("DETAIL", "TRAY", input.getProjectNo(), "PRODUCT",
|
||||
"SPACE", 1, false, List.of(), List.of(), false, 0, 0, 0,
|
||||
FifoDecision.off(), Optional.empty(), "proposal"), TaskCountEstimate.zero()));
|
||||
@@ -71,7 +71,7 @@ class ShadowOutboundValidationTest {
|
||||
assertThat(result.resultCode()).isEqualTo("READY");
|
||||
assertThat(result.proposedStockId()).isEqualTo("STOCK");
|
||||
assertThat(result.reason()).contains("predicateVersion=1", "requestedQuantity=3", "selectedProject=AD.L-00033.01.01");
|
||||
verify(facade).planOutboundFromPublishedSnapshot(eq("01"), argThat(r -> !r.wholeTrayOrDefault()));
|
||||
verify(facade).planShadowOutboundCandidates(eq("01"), argThat(r -> !r.wholeTrayOrDefault()), eq(java.util.Set.of("STOCK")));
|
||||
verify(mapper, never()).refreshSnapshot(anyString(), anyLong(), anyString());
|
||||
verify(facade, never()).planOutbound(anyString(), any());
|
||||
}
|
||||
@@ -80,7 +80,7 @@ class ShadowOutboundValidationTest {
|
||||
void emptyProjectDerivesOnlyProvenCandidateScope() {
|
||||
input.setProjectNo(null);
|
||||
assertThat(plan().resultCode()).isEqualTo("READY");
|
||||
verify(facade).planOutboundFromPublishedSnapshot(eq("01"), argThat(r -> "AD.L-00033.01.01".equals(r.projectNo())));
|
||||
verify(facade).planShadowOutboundCandidates(eq("01"), argThat(r -> "AD.L-00033.01.01".equals(r.projectNo())), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,9 +134,12 @@ class ShadowOutboundValidationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void multipleRowsOnSelectedTrayAreExplicitlyUnsupported() {
|
||||
void otherRowsOnSelectedTrayDoNotEraseTheEligibleItem() {
|
||||
candidate.setTrayItemCount(2);
|
||||
assertThat(plan().resultCode()).isEqualTo("SKIPPED_MULTI_STOCK_TRAY");
|
||||
var result = plan();
|
||||
assertThat(result.resultCode()).isEqualTo("READY");
|
||||
assertThat(result.proposedStockId()).isEqualTo("STOCK");
|
||||
assertThat(result.reason()).contains("candidateEvidenceComplete=true", "\"trayItems\":2", "\"stock\":\"STOCK\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,4 +158,13 @@ class ShadowOutboundValidationTest {
|
||||
private OutboundShadowObservation plan() {
|
||||
return engine.planProjectOutbound(snapshot, "DETAIL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedDuplicateEligibleRowsRemainExplicitAndKeepEvidence() {
|
||||
when(mapper.selectProjectOutboundCandidates("01", 459L, "DETAIL")).thenReturn(List.of(candidate, candidate));
|
||||
var result = plan();
|
||||
assertThat(result.resultCode()).isEqualTo("SKIPPED_AMBIGUOUS_STOCK_SCOPE");
|
||||
assertThat(result.reason()).contains("candidateCount=2", "candidateSha256=");
|
||||
verifyNoInteractions(facade);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ class ShadowPlanningEngineTest {
|
||||
ShadowInboundReference input = inboundReference("1");
|
||||
input.setShadowCandidateCount(3);
|
||||
when(mapper.selectInboundInput("01", 42L, "TASK-1", "TRAY-1")).thenReturn(input);
|
||||
when(mapper.selectInboundEligibleSpaces("01", 42L, "TASK-1", "TRAY-1")).thenReturn(java.util.List.of("SPACE-9"));
|
||||
when(mapper.countInboundEligibleSpace("01", 42L, "TASK-1", "TRAY-1", "SPACE-9")).thenReturn(1);
|
||||
when(mapper.selectPublishedSnapshot("01")).thenReturn(descriptor(SNAPSHOT));
|
||||
when(facade.planInboundFromPublishedSnapshot(eq("01"), any()))
|
||||
@@ -89,7 +90,7 @@ class ShadowPlanningEngineTest {
|
||||
.thenReturn(java.util.List.of(stockReference("01")));
|
||||
when(mapper.selectProjectOutboundReference("01", 42L, "DETAIL-1")).thenReturn(reference);
|
||||
when(mapper.selectPublishedSnapshot("01")).thenReturn(descriptor(SNAPSHOT));
|
||||
when(facade.planOutboundFromPublishedSnapshot(eq("01"), any()))
|
||||
when(facade.planShadowOutboundCandidates(eq("01"), any(), any()))
|
||||
.thenReturn(OutboundPlan.ready(outboundAssignment(), TaskCountEstimate.zero()));
|
||||
ShadowPlanningEngine engine = engine(facade, mapper);
|
||||
|
||||
@@ -104,7 +105,7 @@ class ShadowPlanningEngineTest {
|
||||
"sourceSignature=ABC123", "detail=DETAIL-1", "rawWarehouse=W02",
|
||||
"project=PROJECT-1", "product=PRODUCT-1", "shadowMatches=1");
|
||||
verify(mapper).selectProjectOutboundReference("01", 42L, "DETAIL-1");
|
||||
verify(facade).planOutboundFromPublishedSnapshot(eq("01"), any());
|
||||
verify(facade).planShadowOutboundCandidates(eq("01"), any(), eq(java.util.Set.of("STOCK-1")));
|
||||
verify(facade, never()).planOutbound(any(), any());
|
||||
}
|
||||
|
||||
@@ -359,6 +360,8 @@ class ShadowPlanningEngineTest {
|
||||
}
|
||||
|
||||
private static ShadowPlanningEngine engine(SchedulingFacade facade, ShadowInputMapper mapper) {
|
||||
when(mapper.selectInboundEligibleSpaces(any(), any(Long.class), any(), any()))
|
||||
.thenReturn(java.util.List.of("SPACE-9"));
|
||||
return new ShadowPlanningEngine(facade, mapper, properties(), new CapturingTransactionManager());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ruoyi.in.stockindetail.controller;
|
||||
|
||||
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
|
||||
import com.ruoyi.in.stockindetail.service.IInStockinDetailService;
|
||||
import com.ruoyi.in.stockindetailfinish.service.IInStockinDetailFinishService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
class InStockinDetailBindingTest {
|
||||
@org.springframework.web.bind.annotation.RestController
|
||||
static class BrokenServer {
|
||||
@org.springframework.web.bind.annotation.GetMapping("/fixture/server-failure")
|
||||
Object get() { throw new org.springframework.beans.InvalidPropertyException(BrokenServer.class,
|
||||
"stockinId[limit]", "server property failure"); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPropertyFailureIsNotRelabeledAsBadClientInput() throws Exception {
|
||||
MockMvcBuilders.standaloneSetup(new BrokenServer()).setControllerAdvice(new GlobalExceptionHandler()).build()
|
||||
.perform(get("/fixture/server-failure").param("stockinId[limit]", "20"))
|
||||
.andExpect(jsonPath("$.code").value(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedOrderNumberIsRejectedBeforeEitherDatabaseQuery() throws Exception {
|
||||
var controller = new InStockinDetailController();
|
||||
var active = mock(IInStockinDetailService.class);
|
||||
var finished = mock(IInStockinDetailFinishService.class);
|
||||
ReflectionTestUtils.setField(controller, "inStockinDetailService", active);
|
||||
ReflectionTestUtils.setField(controller, "inStockinDetailFinishService", finished);
|
||||
var mvc = MockMvcBuilders.standaloneSetup(controller)
|
||||
.setControllerAdvice(new GlobalExceptionHandler()).build();
|
||||
|
||||
mvc.perform(get("/in/stockInDetail/list").param("stockinId[limit]", "20"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(400))
|
||||
.andExpect(jsonPath("$.msg").value("请求参数格式不正确,单号等普通字段请传单个值,不要传对象或数组"));
|
||||
verifyNoInteractions(active, finished);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user