proj_name
stringclasses
132 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.09k
len_input
int64
27
2.01k
len_output
int64
14
1.87k
total
int64
55
2.05k
generated_code
stringlengths
3
9.76k
compiler_feedback
stringlengths
9
23.5k
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidDeviceStatusListener.java
AndroidDeviceStatusListener
send
class AndroidDeviceStatusListener implements AndroidDebugBridge.IDeviceChangeListener { private final Logger logger = LoggerFactory.getLogger(AndroidDeviceStatusListener.class); /** * @param device * @return void * @author ZhouYiXun * @des 发送设备状态 * @date 2021/8/16 19:58 */ private void send(IDevice device) {<FILL_FUNCTION_BODY>} @Override public void deviceConnected(IDevice device) { logger.info("Android device: " + device.getSerialNumber() + " ONLINE!"); AndroidDeviceManagerMap.getStatusMap().remove(device.getSerialNumber()); DevicesBatteryMap.getTempMap().remove(device.getSerialNumber()); send(device); } @Override public void deviceDisconnected(IDevice device) { logger.info("Android device: " + device.getSerialNumber() + " OFFLINE!"); AndroidDeviceManagerMap.getStatusMap().remove(device.getSerialNumber()); DevicesBatteryMap.getTempMap().remove(device.getSerialNumber()); send(device); } @Override public void deviceChanged(IDevice device, int changeMask) { IDevice.DeviceState state = device.getState(); if (state == IDevice.DeviceState.OFFLINE) { return; } send(device); } }
JSONObject deviceDetail = new JSONObject(); deviceDetail.put("msg", "deviceDetail"); deviceDetail.put("udId", device.getSerialNumber()); deviceDetail.put("name", device.getProperty("ro.product.name")); deviceDetail.put("model", device.getProperty(IDevice.PROP_DEVICE_MODEL)); deviceDetail.put("status", device.getState() == null ? null : device.getState().toString()); deviceDetail.put("platform", PlatformType.ANDROID); if (device.getProperty("ro.config.ringtone") != null && device.getProperty("ro.config.ringtone").contains("Harmony")) { deviceDetail.put("version", device.getProperty("hw_sc.build.platform.version")); deviceDetail.put("isHm", IsHMStatus.IS_HM); } else { deviceDetail.put("version", device.getProperty(IDevice.PROP_BUILD_VERSION)); deviceDetail.put("isHm", IsHMStatus.IS_ANDROID); } deviceDetail.put("size", AndroidDeviceBridgeTool.getScreenSize(device)); deviceDetail.put("cpu", device.getProperty(IDevice.PROP_DEVICE_CPU_ABI)); deviceDetail.put("manufacturer", device.getProperty(IDevice.PROP_DEVICE_MANUFACTURER)); TransportWorker.send(deviceDetail);
375
363
738
AndroidDeviceManagerMap.getStatusMap().put(device.getSerialNumber(), device.getState().name()); DevicesBatteryMap.getTempMap().put(device.getSerialNumber(), device.getBattery()); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(device.getSerialNumber(), device); AndroidDeviceManagerMap.getDeviceMap().put(
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidDeviceStatusListener.java<line>67<col>52<err>illegal start of expression
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidSupplyTool.java
AndroidSupplyTool
startPerfmon
class AndroidSupplyTool implements ApplicationListener<ContextRefreshedEvent> { private static File sasBinary = new File("plugins" + File.separator + "sonic-android-supply"); private static String sas = sasBinary.getAbsolutePath(); @Override public void onApplicationEvent(@NonNull ContextRefreshedEvent event) { log.info("Enable sonic-android-supply Module"); } public static void startShare(String udId, Session session) { JSONObject sasJSON = new JSONObject(); sasJSON.put("msg", "sas"); sasJSON.put("isEnable", true); stopShare(udId); String processName = String.format("process-%s-sas", udId); String commandLine = "%s share -s %s --translate-port %d"; try { String system = System.getProperty("os.name").toLowerCase(); Process ps = null; int port = PortTool.getPort(); if (system.contains("win")) { ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, port)}); } else if (system.contains("linux") || system.contains("mac")) { ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, port)}); } GlobalProcessMap.getMap().put(processName, ps); sasJSON.put("port", port); } catch (Exception e) { sasJSON.put("port", 0); e.printStackTrace(); } finally { BytesTool.sendText(session, sasJSON.toJSONString()); } } public static void startShare(String udId, int port) { stopShare(udId); String processName = String.format("process-%s-sas", udId); String commandLine = "%s share -s %s --translate-port %d"; try { String system = System.getProperty("os.name").toLowerCase(); Process ps = null; if (system.contains("win")) { ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, port)}); } else if (system.contains("linux") || system.contains("mac")) { ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, port)}); } GlobalProcessMap.getMap().put(processName, ps); } catch (Exception e) { e.printStackTrace(); } } public static void stopShare(String udId) { String processName = String.format("process-%s-sas", udId); if (GlobalProcessMap.getMap().get(processName) != null) { Process ps = GlobalProcessMap.getMap().get(processName); ps.children().forEach(ProcessHandle::destroy); ps.destroy(); } } public static void stopPerfmon(String udId) { String processName = String.format("process-%s-perfmon", udId); if (GlobalProcessMap.getMap().get(processName) != null) { Process ps = GlobalProcessMap.getMap().get(processName); ps.children().forEach(ProcessHandle::destroy); ps.destroy(); } } public static void startPerfmon(String udId, String pkg, Session session, LogUtil logUtil, int interval) {<FILL_FUNCTION_BODY>} }
stopPerfmon(udId); Process ps = null; String commandLine = "%s perfmon -s %s -r %d %s -j --sys-cpu --sys-mem --sys-network"; String system = System.getProperty("os.name").toLowerCase(); String tail = pkg.length() == 0 ? "" : (" --proc-cpu --proc-fps --proc-mem --proc-threads -p " + pkg); try { if (system.contains("win")) { ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, interval, tail)}); } else if (system.contains("linux") || system.contains("mac")) { ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, interval, tail)}); } } catch (Exception e) { e.printStackTrace(); } InputStreamReader inputStreamReader = new InputStreamReader(ps.getInputStream()); BufferedReader stdInput = new BufferedReader(inputStreamReader); InputStreamReader err = new InputStreamReader(ps.getErrorStream()); BufferedReader stdInputErr = new BufferedReader(err); Thread psErr = new Thread(() -> { String s; while (true) { try { if ((s = stdInputErr.readLine()) == null) break; } catch (IOException e) { log.info(e.getMessage()); break; } log.info(s); } try { stdInputErr.close(); } catch (IOException e) { e.printStackTrace(); } try { err.close(); } catch (IOException e) { e.printStackTrace(); } log.info("perfmon print thread shutdown."); }); psErr.start(); Thread pro = new Thread(() -> { String s; while (true) { try { if ((s = stdInput.readLine()) == null) break; } catch (IOException e) { log.info(e.getMessage()); break; } try { JSONObject perf = JSON.parseObject(s); if (session != null) { JSONObject perfDetail = new JSONObject(); perfDetail.put("msg", "perfDetail"); perfDetail.put("detail", perf); sendText(session, perfDetail.toJSONString()); } if (logUtil != null) { logUtil.sendPerLog(perf.toJSONString()); } } catch (Exception ignored) { } } try { stdInput.close(); } catch (IOException e) { e.printStackTrace(); } try { inputStreamReader.close(); } catch (IOException e) { e.printStackTrace(); } log.info("perfmon print thread shutdown."); }); pro.start(); String processName = String.format("process-%s-perfmon", udId); GlobalProcessMap.getMap().put(processName, ps);
941
807
1,748
stopPerfmon(udId); String processName = String.format("process-%s-perfmon", udId); String commandLine = "%s perfmon -s %s -p %s --interval %d"; try { String system = System.getProperty("os.name").toLowerCase(); Process ps = null; if (system.contains("win")) { ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, pkg, interval)}); } else if (system.contains("linux") || system.contains("mac")) { ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, pkg, interval)}); } GlobalProcessMap.getMap().put(processName, ps); logUtil.setProcess(ps); } catch (Exception e) { e.printStackTrace(); } finally { BytesTool.sendText(session, "start perfmon success"); }
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidSupplyTool.java<line>126<col>20<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/ios/IOSDeviceLocalStatus.java
IOSDeviceLocalStatus
finishError
class IOSDeviceLocalStatus { public static void send(String udId, String status) { JSONObject deviceDetail = new JSONObject(); deviceDetail.put("msg", "deviceDetail"); deviceDetail.put("udId", udId); deviceDetail.put("status", status); TransportWorker.send(deviceDetail); } public static boolean startTest(String udId) { synchronized (IOSDeviceLocalStatus.class) { if (IOSDeviceManagerMap.getMap().get(udId) == null) { send(udId, DeviceStatus.TESTING); IOSDeviceManagerMap.getMap().put(udId, DeviceStatus.TESTING); return true; } else { return false; } } } public static void startDebug(String udId) { send(udId, DeviceStatus.DEBUGGING); IOSDeviceManagerMap.getMap().put(udId, DeviceStatus.DEBUGGING); } public static void finish(String udId) { if (SibTool.getDeviceList().contains(udId) && IOSDeviceManagerMap.getMap().get(udId) != null) { if (IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.DEBUGGING) || IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.TESTING)) { send(udId, DeviceStatus.ONLINE); } } IOSDeviceManagerMap.getMap().remove(udId); } public static void finishError(String udId) {<FILL_FUNCTION_BODY>} }
if (SibTool.getDeviceList().contains(udId) && IOSDeviceManagerMap.getMap().get(udId) != null) { if (IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.DEBUGGING) || IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.TESTING)) { send(udId, DeviceStatus.ERROR); } } IOSDeviceManagerMap.getMap().remove(udId);
423
128
551
if (SibTool.getDeviceList().contains(udId) && IOSDeviceManagerMap.getMap().get(udId) != null) { if (IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.DEBUGGING) || IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.TESTING)) { send(udId, DeviceStatus.ERROR); } } IOSDeviceManagerMap.getMap().remove(udId);
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/common/config/ResourceConfig.java
ResourceConfig
addResourceHandlers
class ResourceConfig extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) {<FILL_FUNCTION_BODY>} }
registry.addResourceHandler("/static/**").addResourceLocations( "classpath:/static/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/download/**") .addResourceLocations("file:///" + System.getProperty("user.dir") + "/plugins/"); super.addResourceHandlers(registry);
45
114
159
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/common/config/RestTemplateConfig.java
RestTemplateConfig
simpleClientHttpRequestFactory
class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() {<FILL_FUNCTION_BODY>} }
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(120000); factory.setConnectTimeout(150000); return factory;
71
54
125
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000); factory.setConnectTimeout(15000); return factory;
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/common/maps/DevicesLockMap.java
DevicesLockMap
lockByUdId
class DevicesLockMap { private final static Logger logger = LoggerFactory.getLogger(DevicesLockMap.class); /** * key: udId(设备序列号) value: Semaphore */ private static Map<String, Semaphore> devicesLockMap = new ConcurrentHashMap<>(); /** * xxx * 用设备序列号上锁(无) * * @see #lockByUdId(String, Long, TimeUnit) */ public static boolean lockByUdId(String udId) throws InterruptedException { return lockByUdId(udId, null, null); } /** * 用设备序列号上锁(可设置超时) * * @param udId 设备序列号 * @param timeOut 获取锁超时时间 此参数必须和 timeUnit 同时存在 * @param timeUnit 时间单位 此参数必须和 timeOut 同时存在 * @return true: 上锁成功 false: 上锁失败 */ public static boolean lockByUdId(String udId, Long timeOut, TimeUnit timeUnit) throws InterruptedException {<FILL_FUNCTION_BODY>} /** * 解锁并从map中移除锁 * * @param udId 设备序列号 */ public static void unlockAndRemoveByUdId(String udId) { Assert.hasText(udId, "udId must not be blank"); Semaphore deviceLock; synchronized (WebSocketSessionMap.class) { deviceLock = devicesLockMap.get(udId); removeLockByUdId(udId); } if (deviceLock != null) { deviceLock.release(); } } public static void removeLockByUdId(String udId) { devicesLockMap.remove(udId); } }
// 校验参数 Assert.hasText(udId, "udId must not be blank"); if (timeOut != null || timeUnit != null) { Assert.isTrue( timeOut != null && timeUnit != null, "timeOut and timeUnit must not be null at the same time" ); } Semaphore deviceLock; // 原子操作,避免put后被别的线程remove造成当前线程lock失效 synchronized (WebSocketSessionMap.class) { Semaphore res = devicesLockMap.get(udId); if (res == null) { deviceLock = new Semaphore(1); devicesLockMap.put(udId, deviceLock); } else { deviceLock = res; } } // 无超时获取锁逻辑,直接锁并返回true if (timeOut == null) { deviceLock.acquire(); return true; } // 如果有超时,则成功返回true,超时返回false try { return deviceLock.tryAcquire(timeOut, timeUnit); } catch (InterruptedException e) { logger.error("获取锁被中断,返回false"); return false; }
504
324
828
Assert.hasText(udId, "udId must not be blank"); Semaphore deviceLock; synchronized (WebSocketSessionMap.class) { deviceLock = devicesLockMap.get(udId); if (deviceLock == null) { deviceLock = new Semaphore(1); devicesLockMap.put(udId, deviceLock); } } if (timeOut != null && timeUnit != null) { return deviceLock.tryAcquire(timeOut, timeUnit); } deviceLock.acquire(); return true;
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/common/models/HandleContext.java
HandleContext
toString
class HandleContext { private String stepDes; private String detail; private Throwable e; public Iterator<BaseElement> iteratorElement; public BaseElement currentIteratorElement; public HandleContext() { this.stepDes = ""; this.detail = ""; this.e = null; } public void clear() { this.stepDes = ""; this.detail = ""; this.e = null; } public String getStepDes() { return stepDes; } public void setStepDes(String stepDes) { this.stepDes = stepDes; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public Throwable getE() { return e; } public void setE(Throwable e) { this.e = e; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "HandleDes{" + "stepDes='" + stepDes + '\'' + ", detail='" + detail + '\'' + ", e=" + e + '}';
274
51
325
return "HandleContext{" + "stepDes='" + stepDes + '\'' + ", detail='" + detail + '\'' + ", e=" + e + '}';
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/controller/CertController.java
CertController
download
class CertController { @Value("${sonic.sgm}") private String version; @RequestMapping("/assets/download") public String download(Model model) {<FILL_FUNCTION_BODY>} }
model.addAttribute("msg", "欢迎来到证书下载页面"); model.addAttribute("pemMsg", "👉 点击下载pem证书"); model.addAttribute("pemName", "sonic-go-mitmproxy-ca-cert.pem"); model.addAttribute("pemUrl", "/download/sonic-go-mitmproxy-ca-cert.pem"); model.addAttribute("tips", "如果pem证书无效,请尝试cer证书"); model.addAttribute("cerMsg", "👉 点击下载cer证书"); model.addAttribute("cerName", "sonic-go-mitmproxy-ca-cert.cer"); model.addAttribute("cerUrl", "/download/sonic-go-mitmproxy-ca-cert.cer"); model.addAttribute("version", "Version: " + version); return "download";
60
222
282
model.addAttribute("version", version); return "download";
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/AgentManagerTool.java
AgentManagerTool
stop
class AgentManagerTool { private final static Logger logger = LoggerFactory.getLogger(AgentManagerTool.class); private static ConfigurableApplicationContext context; @Autowired public void setContext(ConfigurableApplicationContext c) { AgentManagerTool.context = c; } public static void stop() {<FILL_FUNCTION_BODY>} }
try { context.close(); } catch (Exception e) { e.printStackTrace(); } logger.info("Bye!"); System.exit(0);
96
51
147
if (context != null) { context.close(); }
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/BytesTool.java
BytesTool
intToByteArray
class BytesTool { public static int agentId = 0; public static String agentHost = ""; public static int highTemp = 0; public static int highTempTime = 0; public static int remoteTimeout = 480; public static int toInt(byte[] b) { int res = 0; for (int i = 0; i < b.length; i++) { res += (b[i] & 0xff) << (i * 8); } return res; } public static byte[] intToByteArray(int i) {<FILL_FUNCTION_BODY>} public static byte[] subByteArray(byte[] byte1, int start, int end) { byte[] byte2; byte2 = new byte[end - start]; System.arraycopy(byte1, start, byte2, 0, end - start); return byte2; } public static long bytesToLong(byte[] src, int offset) { long value; value = ((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 3] & 0xFF) << 24)); return value; } // java合并两个byte数组 public static byte[] addBytes(byte[] data1, byte[] data2) { byte[] data3 = new byte[data1.length + data2.length]; System.arraycopy(data1, 0, data3, 0, data1.length); System.arraycopy(data2, 0, data3, data1.length, data2.length); return data3; } public static void sendByte(Session session, byte[] message) { if (session == null || !session.isOpen()) { return; } synchronized (session) { try { session.getBasicRemote().sendBinary(ByteBuffer.wrap(message)); } catch (IllegalStateException | IOException e) { log.error("WebSocket send msg error...connection has been closed."); } } } public static void sendByte(Session session, ByteBuffer message) { if (session == null || !session.isOpen()) { return; } synchronized (session) { try { session.getBasicRemote().sendBinary(message); } catch (IllegalStateException | IOException e) { log.error("WebSocket send msg error...connection has been closed."); } } } public static void sendText(Session session, String message) { if (session == null || !session.isOpen()) { return; } synchronized (session) { try { session.getBasicRemote().sendText(message); } catch (IllegalStateException | IOException e) { log.error("WebSocket send msg error...connection has been closed."); } } } public static boolean isInt(String s) { return s.matches("[0-9]+"); } public static int getInt(String a) { String regEx = "[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(a); return Integer.parseInt(m.replaceAll("").trim()); } public static boolean versionCheck(String target, String local) { int[] targetParse = parseVersion(target); int[] localParse = parseVersion(local); if (targetParse[0] < localParse[0]) { return true; } if (targetParse[0] == localParse[0]) { if (targetParse[1] < localParse[1]) { return true; } if (targetParse[1] == localParse[1]) { if (targetParse[2] <= localParse[2]) { return true; } } } return false; } public static int[] parseVersion(String s) { return Arrays.stream(s.split("\\.")).mapToInt(Integer::parseInt).toArray(); } }
byte[] result = new byte[4]; result[0] = (byte) (i & 0xff); result[1] = (byte) (i >> 8 & 0xff); result[2] = (byte) (i >> 16 & 0xff); result[3] = (byte) (i >> 24 & 0xff); return result;
1,068
102
1,170
byte[] b = new byte[4]; for (int j = 0; j < 4; j++) { b[j] = (byte) (i >>> (j * 8)); } return b;
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/LaunchTool.java
LaunchTool
destroy
class LaunchTool implements ApplicationRunner { @Override public void run(ApplicationArguments args) { File testFile = new File("test-output"); if (!testFile.exists()) { testFile.mkdirs(); } ScheduleTool.scheduleAtFixedRate( new TransportConnectionThread(), TransportConnectionThread.DELAY, TransportConnectionThread.DELAY, TransportConnectionThread.TIME_UNIT ); TransportWorker.readQueue(); new Thread(() -> { File file = new File("plugins/sonic-go-mitmproxy-ca-cert.pem"); if (!file.exists()) { log.info("Generating ca file..."); SGMTool.startProxy("init", SGMTool.getCommand()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // 仅生成证书 SGMTool.stopProxy("init"); file = new File("plugins/sonic-go-mitmproxy-ca-cert.pem"); if (!file.exists()) { log.info("init sonic-go-mitmproxy-ca failed!"); } else { log.info("init sonic-go-mitmproxy-ca Successful!"); } } }).start(); } @PreDestroy public void destroy() {<FILL_FUNCTION_BODY>} }
for (String key : GlobalProcessMap.getMap().keySet()) { Process ps = GlobalProcessMap.getMap().get(key); ps.children().forEach(ProcessHandle::destroy); ps.destroy(); } for (String key : IOSProcessMap.getMap().keySet()) { List<Process> ps = IOSProcessMap.getMap().get(key); for (Process p : ps) { p.children().forEach(ProcessHandle::destroy); p.destroy(); } } log.info("Release done!");
373
143
516
TransportWorker.stop();
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/LaunchTool.java<line>74<col>24<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/PHCTool.java
PHCTool
setPosition
class PHCTool { private static String baseUrl = "http://127.0.0.1:7531"; private static RestTemplate restTemplate; @Autowired public void setRestTemplate(RestTemplate restTemplate) { PHCTool.restTemplate = restTemplate; } public static void setPosition(int position, String type) {<FILL_FUNCTION_BODY>} public static boolean isSupport() { try { ResponseEntity<String> responseEntity = restTemplate.getForEntity(baseUrl + "/ping", String.class); if (responseEntity.getStatusCode() == HttpStatus.OK) { if ("pong".equals(responseEntity.getBody())) { log.info("hub is ready."); return true; } } log.info("hub is not ready."); return false; } catch (Exception e) { log.info("hub is not ready. ignore..."); return false; } } }
if (!isSupport()) return; log.info("set hub position: {} {}", position, type); JSONObject re = new JSONObject(); re.put("position", position); re.put("type", type); restTemplate.postForEntity(baseUrl + "/control", re, String.class);
258
80
338
try { restTemplate.postForEntity(baseUrl + "/position", new Position(position, type), String.class); } catch (Exception e) { log.info("hub is not ready. ignore..."); }
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/PHCTool.java<line>42<col>25<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/PortTool.java
PortTool
getBindSocket
class PortTool { public static Integer getPort() { ServerSocket serverSocket; int port = 0; try { serverSocket = new ServerSocket(0); port = serverSocket.getLocalPort(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } return port; } public static Socket getBindSocket() {<FILL_FUNCTION_BODY>} public static int releaseAndGetPort(Socket socket) { int port = socket.getLocalPort(); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } return port; } }
Socket socket = new Socket(); InetSocketAddress inetAddress = new InetSocketAddress(0); try { socket.bind(inetAddress); } catch (IOException e) { e.printStackTrace(); } return socket;
179
68
247
ServerSocket serverSocket; Socket socket = null; try { serverSocket = new ServerSocket(0); socket = serverSocket.accept(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } return socket;
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/ProcessCommandTool.java
ProcessCommandTool
getProcessLocalCommand
class ProcessCommandTool { public static String getProcessLocalCommandStr(String commandLine) { List<String> processLocalCommand = getProcessLocalCommand(commandLine); StringBuilder stringBuilder = new StringBuilder(""); for (String s : processLocalCommand) { stringBuilder.append(s); } return stringBuilder.toString(); } public static List<String> getProcessLocalCommand(String commandLine) {<FILL_FUNCTION_BODY>} }
Process process = null; InputStreamReader inputStreamReader = null; InputStreamReader errorStreamReader; LineNumberReader consoleInput = null; LineNumberReader consoleError = null; String consoleInputLine; String consoleErrorLine; List<String> sdrResult = new ArrayList<String>(); List<String> sdrErrorResult = new ArrayList<String>(); try { String system = System.getProperty("os.name").toLowerCase(); if (system.contains("win")) { process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", commandLine}); } else { process = Runtime.getRuntime().exec(new String[]{"sh", "-c", commandLine}); } inputStreamReader = new InputStreamReader(process.getInputStream()); consoleInput = new LineNumberReader(inputStreamReader); while ((consoleInputLine = consoleInput.readLine()) != null) { sdrResult.add(consoleInputLine); } errorStreamReader = new InputStreamReader(process.getErrorStream()); consoleError = new LineNumberReader(errorStreamReader); while ((consoleErrorLine = consoleError.readLine()) != null) { sdrErrorResult.add(consoleErrorLine); } int resultCode = process.waitFor(); if (resultCode > 0 && sdrErrorResult.size() > 0) { return sdrErrorResult; } else { return sdrResult; } } catch (Exception e) { return new ArrayList<String>(); } finally { try { if (null != consoleInput) { consoleInput.close(); } if (null != consoleError) { consoleError.close(); } if (null != inputStreamReader) { inputStreamReader.close(); } if (null != process) { process.destroy(); } } catch (Exception e) { } }
121
495
616
List<String> processLocalCommand = new ArrayList<>(); String[] commandLineArray = commandLine.split(" "); for (String s : commandLineArray) { if (s.contains("-D")) { processLocalCommand.add(s); } } return processLocalCommand;
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/SGMTool.java
SGMTool
startProxy
class SGMTool { private static final String pFile = new File("plugins").getAbsolutePath(); private static final File sgmBinary = new File(pFile + File.separator + "sonic-go-mitmproxy"); private static final String sgm = sgmBinary.getAbsolutePath(); public static String getCommand(int pPort, int webPort) { return String.format( "%s -cert_path %s -addr :%d -web_addr :%d", sgm, pFile, pPort, webPort); } public static String getCommand() { return String.format( "%s -cert_path %s", sgm, pFile); } public static void startProxy(String udId, String command) {<FILL_FUNCTION_BODY>} public static void stopProxy(String udId) { String processName = String.format("process-%s-proxy", udId); if (GlobalProcessMap.getMap().get(processName) != null) { Process ps = GlobalProcessMap.getMap().get(processName); ps.children().forEach(ProcessHandle::destroy); ps.destroy(); } } }
String processName = String.format("process-%s-proxy", udId); if (GlobalProcessMap.getMap().get(processName) != null) { Process ps = GlobalProcessMap.getMap().get(processName); ps.children().forEach(ProcessHandle::destroy); ps.destroy(); } String system = System.getProperty("os.name").toLowerCase(); Process ps = null; try { if (system.contains("win")) { ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", command}); } else if (system.contains("linux") || system.contains("mac")) { ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", command}); } InputStreamReader inputStreamReader = new InputStreamReader(ps.getInputStream()); BufferedReader stdInput = new BufferedReader(inputStreamReader); Semaphore isFinish = new Semaphore(0); new Thread(() -> { String s; while (true) { try { if ((s = stdInput.readLine()) == null) break; } catch (IOException e) { log.info(e.getMessage()); break; } if (s.contains("Proxy start listen")) { try { Thread.sleep(300); } catch (InterruptedException ignored) { } isFinish.release(); } } try { stdInput.close(); } catch (IOException e) { e.printStackTrace(); } try { inputStreamReader.close(); } catch (IOException e) { e.printStackTrace(); } log.info("{} web proxy done.", udId); }).start(); int wait = 0; while (!isFinish.tryAcquire()) { try { Thread.sleep(500); } catch (InterruptedException ex) { throw new RuntimeException(ex); } wait++; if (wait >= 120) { log.info("{} web proxy start timeout!", udId); return; } } GlobalProcessMap.getMap().put(processName, ps); } catch (Exception e) { e.printStackTrace(); }
311
585
896
Process ps = ProcessUtil.start(command); String processName = String.format("process-%s-proxy", udId); GlobalProcessMap.getMap().put(processName, ps);
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/SGMTool.java<line>48<col>22<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/SpringTool.java
SpringTool
getPropertiesValue
class SpringTool implements ApplicationContextAware, EmbeddedValueResolverAware { private static ApplicationContext applicationContext = null; private static StringValueResolver stringValueResolver = null; @Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { if (SpringTool.applicationContext == null) { SpringTool.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } public static String getPropertiesValue(String name) {<FILL_FUNCTION_BODY>} @Override public void setEmbeddedValueResolver(@NonNull StringValueResolver resolver) { stringValueResolver = resolver; } }
try { name = "${" + name + "}"; return stringValueResolver.resolveStringValue(name); } catch (Exception e) { log.error("{%s} is not found.".formatted(name)); return null; }
249
69
318
return stringValueResolver.resolveStringValue(name);
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/DownloadTool.java
DownloadTool
download
class DownloadTool { public static File download(String urlString) throws IOException {<FILL_FUNCTION_BODY>} }
URL url = new URL(urlString); URLConnection con = url.openConnection(); InputStream is = con.getInputStream(); byte[] bs = new byte[1024]; int len; long time = Calendar.getInstance().getTimeInMillis(); String tail = ""; if (urlString.lastIndexOf(".") != -1) { tail = urlString.substring(urlString.lastIndexOf(".") + 1); } String filename = "test-output" + File.separator + "download-" + time + "." + tail; File file = new File(filename); FileOutputStream os; os = new FileOutputStream(file, true); while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); } os.close(); is.close(); return file;
33
226
259
URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream(); File tempFile = File.createTempFile("temp", ".tmp"); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); inStream.close(); return tempFile;
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/DownloadTool.java<line>31<col>9<err>cannot find symbol <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/DownloadTool.java<line>31<col>35<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/FileTool.java
FileTool
unZipChromeDriver
class FileTool { public static void zip(File result, File inputFile) throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream( result.getAbsoluteFile())); zip(out, inputFile, ""); out.close(); } public static void zip(ZipOutputStream out, File f, String base) throws IOException { if (f.isDirectory()) { File[] fl = f.listFiles(); out.putNextEntry(new ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i]); } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; while ((b = in.read()) != -1) { out.write(b); } in.close(); } } /** * 解压缩下载完成的chromeDriver.zip文件 * * @param source 原始的下载临时文件 * @param version 完整的chrome版本 * @param greaterThen114 是否>=115(大于115的场景下,使用的是google官方Chrome for Testing (CfT)下载路径) * @param systemName 系统类型(大于115的场景下,判断产物文件会使用到) * @return chromeDriver文件 */ public static File unZipChromeDriver(File source, String version, boolean greaterThen114, String systemName) {<FILL_FUNCTION_BODY>} public static void deleteDir(File file) { if (!file.exists()) { return; } File[] files = file.listFiles(); for (File f : files) { if (f.isDirectory()) { deleteDir(f); } else { f.delete(); } } file.delete(); } }
int BUFFER = 2048; File webview = new File("webview"); if (!webview.exists()) { webview.mkdirs(); } String system = System.getProperty("os.name").toLowerCase(); String tail = "chromedriver"; if (system.contains("win")) { tail += ".exe"; } File driver = null; try { ZipFile zipFile = new ZipFile(source); Enumeration emu = zipFile.entries(); while (emu.hasMoreElements()) { ZipEntry entry = (ZipEntry) emu.nextElement(); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); // >=115之后的版本,entry.name字段有变更,带上了系统类型 final String targetFileName = greaterThen114 ? String.format("chromedriver-%s/%s", systemName, tail) : tail; if (entry.getName().equals(targetFileName)) { String fileName = version + "_" + tail; File file = new File(webview + File.separator + fileName); File parent = file.getParentFile(); if (parent != null && (!parent.exists())) { parent.mkdirs(); } FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int count; byte data[] = new byte[BUFFER]; while ((count = bis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); driver = file; } bis.close(); if (driver != null) { break; } } zipFile.close(); } catch (Exception e) { e.printStackTrace(); } if (driver != null) { driver.setExecutable(true); driver.setWritable(true); source.delete(); } return driver;
530
541
1,071
File target = new File(source.getParentFile(), "chromedriver"); if (target.exists()) { deleteDir(target); } target.mkdirs(); try { ZipFile zipFile = new ZipFile(source); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (greaterThen114) { if (name.contains("chromedriver_") && name.contains(version) && name.contains(systemName)) { File file = new File(target, name); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } InputStream inputStream = zipFile.getInputStream(entry); FileOutputStream outputStream = new FileOutputStream(file); int len; byte[] buffer = new byte[1024]; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); } } else { if (name.contains("chromedriver_") && name.contains(version)) { File file = new File(target, name); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } InputStream inputStream = zipFile.getInputStream(entry); FileOutputStream outputStream = new FileOutputStream(file); int len
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/FileTool.java<line>105<col>5<err>illegal start of expression <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/FileTool.java<line>103<col>32<err>';' expected <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/FileTool.java<line>73<col>9<err>'try' without 'catch', 'finally' or resource declarations
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/UploadTools.java
UploadTools
uploadPatchRecord
class UploadTools { private final static Logger logger = LoggerFactory.getLogger(UploadTools.class); @Value("${sonic.server.host}") private String host; @Value("${sonic.server.port}") private String port; private static String baseUrl; private static RestTemplate restTemplate; @Autowired public void setRestTemplate(RestTemplate restTemplate) { UploadTools.restTemplate = restTemplate; baseUrl = ("http://" + host + ":" + port + "/server/api/folder").replace(":80/", "/"); } public static String upload(File uploadFile, String type) { File folder = new File("test-output"); if (!folder.exists()) {//判断文件目录是否存在 folder.mkdirs(); } File transfer; if (type.equals("keepFiles") || type.equals("imageFiles")) { long timeMillis = Calendar.getInstance().getTimeInMillis(); try { Thumbnails.of(uploadFile) .scale(1f) .outputQuality(0.25f).toFile(folder + File.separator + timeMillis + "transfer.jpg"); } catch (IOException e) { logger.error(e.getMessage()); } transfer = new File(folder + File.separator + timeMillis + "transfer.jpg"); } else { transfer = uploadFile; } FileSystemResource resource = new FileSystemResource(transfer); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource); param.add("type", type); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(baseUrl + "/upload/v2", param, JSONObject.class); if (responseEntity.getBody().getInteger("code") == 2000) { if (uploadFile.exists()) { uploadFile.delete(); } if (transfer.exists()) { transfer.delete(); } } else { logger.info("发送失败!" + responseEntity.getBody()); } return baseUrl + "/" + responseEntity.getBody().getString("data"); } public static String uploadPatchRecord(File uploadFile) {<FILL_FUNCTION_BODY>} }
if (uploadFile.length() == 0) { uploadFile.delete(); return null; } String url = ""; long size = 1024 * 1024; int num = (int) (Math.ceil(uploadFile.length() * 1.0 / size)); String uuid = UUID.randomUUID().toString(); File file = new File("test-output/record" + File.separator + uuid); if (!file.exists()) { file.mkdirs(); } try { RandomAccessFile before = new RandomAccessFile(uploadFile, "r"); long beforeSize = uploadFile.length(); byte[] bytes = new byte[1024]; int len; int successNum = 0; for (int i = 0; i < num; i++) { File branchFile = new File(file.getPath() + File.separator + uploadFile.getName()); RandomAccessFile branch = new RandomAccessFile(branchFile, "rw"); while ((len = before.read(bytes)) != -1) { if (beforeSize > len) { branch.write(bytes, 0, len); beforeSize -= len; } else { branch.write(bytes, 0, (int) beforeSize); } if (branch.length() >= size) break; } branch.close(); FileSystemResource resource = new FileSystemResource(branchFile); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource); param.add("uuid", uuid); param.add("index", i + ""); param.add("total", num + ""); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(baseUrl + "/upload/recordFiles", param, JSONObject.class); if (responseEntity.getBody().getInteger("code") == 2000) { successNum++; } if (responseEntity.getBody().getString("data") != null) { url = responseEntity.getBody().getString("data"); } branchFile.delete(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } before.close(); file.delete(); if (successNum == num) { uploadFile.delete(); } else { logger.info("上传缺失!"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return url;
600
673
1,273
File folder = new File("test-output"); if (!folder.exists()) {//判断文件目录是否存在 folder.mkdirs(); } File transfer = new File(folder + File.separator + "transfer.jpg"); try { Thumbnails.of(uploadFile) .scale(1f) .outputQuality(0.25f).toFile(transfer); } catch (IOException e) { logger.error(e.getMessage()); } FileSystemResource resource = new FileSystemResource(transfer); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource); param.add("type", "patchRecord"); ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(baseUrl + "/upload/v2", param, JSONObject.class); if (responseEntity.getBody().getInteger("code") == 2000) { if (uploadFile.exists()) { uploadFile.delete(); } if (transfer.exists()) { transfer.delete(); } } else { logger.info("发送失败!" + responseEntity.getBody()); } return baseUrl + "/" + responseEntity.getBody().getString("data");
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/RoutingDelegate.java
RoutingDelegate
createRequestEntity
class RoutingDelegate { public ResponseEntity<String> redirect(HttpServletRequest request, HttpServletResponse response, String routeUrl, String prefix) { try { String redirectUrl = createPredictUrl(request, routeUrl, prefix); RequestEntity requestEntity = createRequestEntity(request, redirectUrl); return route(requestEntity); } catch (Exception e) { if (e.getMessage().contains("{") && e.getMessage().contains("}")) { return new ResponseEntity(JSON.parseObject(e.getMessage().substring(e.getMessage().indexOf("{"), e.getMessage().lastIndexOf("}") + 1)).toJSONString(), HttpStatus.INTERNAL_SERVER_ERROR); } else { JSONObject err = new JSONObject(); err.put("error", "-1"); err.put("message", "REDIRECT ERROR"); err.put("traceback", "REDIRECT ERROR"); JSONObject base = new JSONObject(); base.put("value", err); base.put("sessionId", ""); return new ResponseEntity(base.toJSONString(), HttpStatus.INTERNAL_SERVER_ERROR); } } } private String createPredictUrl(HttpServletRequest request, String routeUrl, String prefix) { String queryString = request.getQueryString(); return routeUrl + request.getRequestURI().replace(prefix, "") + (queryString != null ? "?" + queryString : ""); } private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws URISyntaxException, IOException {<FILL_FUNCTION_BODY>} private ResponseEntity<String> route(RequestEntity requestEntity) { RestTemplate restTemplate = new RestTemplate(); return restTemplate.exchange(requestEntity, String.class); } private byte[] parseRequestBody(HttpServletRequest request) throws IOException { InputStream inputStream = request.getInputStream(); return StreamUtils.copyToByteArray(inputStream); } private MultiValueMap<String, String> parseRequestHeader(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); List<String> headerNames = Collections.list(request.getHeaderNames()); for (String headerName : headerNames) { List<String> headerValues = Collections.list(request.getHeaders(headerName)); for (String headerValue : headerValues) { headers.add(headerName, headerValue); } } return headers; } }
String method = request.getMethod(); HttpMethod httpMethod = HttpMethod.valueOf(method); MultiValueMap<String, String> headers = parseRequestHeader(request); byte[] body = parseRequestBody(request); return new RequestEntity<>(body, headers, httpMethod, new URI(url));
621
78
699
HttpMethod method = HttpMethod.resolve(request.getMethod()); MultiValueMap<String, String> headers = parseRequestHeader(request); byte[] body = parseRequestBody(request); return new RequestEntity(body, headers, method, new URI(url));
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportConnectionThread.java
TransportConnectionThread
run
class TransportConnectionThread implements Runnable { /** * second */ public static final long DELAY = 10; public static final String THREAD_NAME = "transport-connection-thread"; public static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; String serverHost = String.valueOf(SpringTool.getPropertiesValue("sonic.server.host")); Integer serverPort = Integer.valueOf(SpringTool.getPropertiesValue("sonic.server.port")); String key = String.valueOf(SpringTool.getPropertiesValue("sonic.agent.key")); @Override public void run() {<FILL_FUNCTION_BODY>} }
Thread.currentThread().setName(THREAD_NAME); if (TransportWorker.client == null) { if (!TransportWorker.isKeyAuth) { return; } String url = String.format("ws://%s:%d/server/websockets/agent/%s", serverHost, serverPort, key).replace(":80/", "/"); URI uri = URI.create(url); TransportClient transportClient = new TransportClient(uri); transportClient.connect(); } else { JSONObject ping = new JSONObject(); ping.put("msg", "ping"); TransportWorker.send(ping); }
176
168
344
while (true) { try { SonicClient.connect(serverHost, serverPort, key); break; } catch (Exception e) { log.error("connect sonic server error", e); } try { Thread.sleep(DELAY * 1000); } catch (InterruptedException e) { log.error("sleep error", e); } }
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportConnectionThread.java<line>50<col>17<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportController.java
TransportController
catchAll
class TransportController { public final static String DELEGATE_PREFIX = "/uia"; @Autowired private RoutingDelegate routingDelegate; @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = MediaType.ALL_VALUE) public ResponseEntity catchAll(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
System.out.println(request.getRequestURI()); return routingDelegate.redirect(request, response, "http://localhost:" + request.getRequestURI().replace(DELEGATE_PREFIX + "/", ""), request.getRequestURI());
118
62
180
return routingDelegate.route(request, response);
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportController.java<line>23<col>31<err>method route in class org.cloud.sonic.agent.transport.RoutingDelegate cannot be applied to given types;
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportWorker.java
TransportWorker
readQueue
class TransportWorker { private static LinkedBlockingQueue<JSONObject> dataQueue = new LinkedBlockingQueue<>(); public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); public static TransportClient client = null; public static Boolean isKeyAuth = true; public static void send(JSONObject jsonObject) { dataQueue.offer(jsonObject); } public static void readQueue() {<FILL_FUNCTION_BODY>} }
cachedThreadPool.execute(() -> { while (isKeyAuth) { try { if (client != null && client.isOpen()) { if (!dataQueue.isEmpty()) { JSONObject m = dataQueue.poll(); m.put("agentId", BytesTool.agentId); client.send(m.toJSONString()); } else { Thread.sleep(1000); } } else { Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } } });
121
156
277
while (true) { try { JSONObject jsonObject = dataQueue.take(); if (jsonObject == null) { continue; } String index = jsonObject.getString("index"); String type = jsonObject.getString("type"); String id = jsonObject.getString("id"); JSONObject data = jsonObject.getJSONObject("data"); if (isKeyAuth) { client.prepareIndex(index, type, id).setSource(data).execute().actionGet(); } else { client.prepareIndex(index, type, id).setSource(data).execute().actionGet(); } } catch (Exception e) { e.printStackTrace(); } }
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportWorker.java<line>53<col>27<err>cannot find symbol <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportWorker.java<line>55<col>27<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AndroidScreenWSServer.java
AndroidScreenWSServer
startScreen
class AndroidScreenWSServer implements IAndroidWSServer { @Value("${sonic.agent.key}") private String key; private Map<String, String> typeMap = new ConcurrentHashMap<>(); private Map<String, String> picMap = new ConcurrentHashMap<>(); private AndroidMonitorHandler androidMonitorHandler = new AndroidMonitorHandler(); @OnOpen public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId, @PathParam("token") String token) throws Exception { if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) { log.info("Auth Failed!"); return; } IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId); if (iDevice == null) { log.info("Target device is not connecting, please check the connection."); return; } AndroidDeviceBridgeTool.screen(iDevice, "abort"); session.getUserProperties().put("udId", udId); session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId)); WebSocketSessionMap.addSession(session); saveUdIdMapAndSet(session, iDevice); int wait = 0; boolean isInstall = true; while (AndroidAPKMap.getMap().get(udId) == null || (!AndroidAPKMap.getMap().get(udId))) { Thread.sleep(500); wait++; if (wait >= 40) { isInstall = false; break; } } if (!isInstall) { log.info("Waiting for apk install timeout!"); exit(session); } session.getUserProperties().put("schedule",ScheduleTool.schedule(() -> { log.info("time up!"); if (session.isOpen()) { JSONObject errMsg = new JSONObject(); errMsg.put("msg", "error"); BytesTool.sendText(session, errMsg.toJSONString()); exit(session); } }, BytesTool.remoteTimeout)); } @OnClose public void onClose(Session session) { exit(session); } @OnError public void onError(Session session, Throwable error) { log.error(error.getMessage()); error.printStackTrace(); JSONObject errMsg = new JSONObject(); errMsg.put("msg", "error"); BytesTool.sendText(session, errMsg.toJSONString()); } @OnMessage public void onMessage(String message, Session session) { JSONObject msg = JSON.parseObject(message); log.info("{} send: {}", session.getUserProperties().get("id").toString(), msg); String udId = session.getUserProperties().get("udId").toString(); switch (msg.getString("type")) { case "switch" -> { typeMap.put(udId, msg.getString("detail")); IDevice iDevice = udIdMap.get(session); if (!androidMonitorHandler.isMonitorRunning(iDevice)) { androidMonitorHandler.startMonitor(iDevice, res -> { JSONObject rotationJson = new JSONObject(); rotationJson.put("msg", "rotation"); rotationJson.put("value", Integer.parseInt(res) * 90); BytesTool.sendText(session, rotationJson.toJSONString()); startScreen(session); }); } else { startScreen(session); } } case "pic" -> { picMap.put(udId, msg.getString("detail")); startScreen(session); } } } private void startScreen(Session session) {<FILL_FUNCTION_BODY>} private void exit(Session session) { synchronized (session) { ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule"); future.cancel(true); String udId = session.getUserProperties().get("udId").toString(); androidMonitorHandler.stopMonitor(udIdMap.get(session)); WebSocketSessionMap.removeSession(session); removeUdIdMapAndSet(session); AndroidDeviceManagerMap.getRotationMap().remove(udId); if (ScreenMap.getMap().get(session) != null) { ScreenMap.getMap().get(session).interrupt(); } typeMap.remove(udId); picMap.remove(udId); try { session.close(); } catch (IOException e) { e.printStackTrace(); } log.info("{} : quit.", session.getUserProperties().get("id").toString()); } } }
IDevice iDevice = udIdMap.get(session); if (iDevice != null) { Thread old = ScreenMap.getMap().get(session); if (old != null) { old.interrupt(); do { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (ScreenMap.getMap().get(session) != null); } typeMap.putIfAbsent(iDevice.getSerialNumber(), "scrcpy"); switch (typeMap.get(iDevice.getSerialNumber())) { case "scrcpy" -> { ScrcpyServerUtil scrcpyServerUtil = new ScrcpyServerUtil(); Thread scrcpyThread = scrcpyServerUtil.start(iDevice.getSerialNumber(), AndroidDeviceManagerMap.getRotationMap().get(iDevice.getSerialNumber()), session); ScreenMap.getMap().put(session, scrcpyThread); } case "minicap" -> { MiniCapUtil miniCapUtil = new MiniCapUtil(); AtomicReference<String[]> banner = new AtomicReference<>(new String[24]); Thread miniCapThread = miniCapUtil.start( iDevice.getSerialNumber(), banner, null, picMap.get(iDevice.getSerialNumber()) == null ? "high" : picMap.get(iDevice.getSerialNumber()), AndroidDeviceManagerMap.getRotationMap().get(iDevice.getSerialNumber()), session ); ScreenMap.getMap().put(session, miniCapThread); } } JSONObject picFinish = new JSONObject(); picFinish.put("msg", "picFinish"); BytesTool.sendText(session, picFinish.toJSONString()); }
1,257
467
1,724
String udId = session.getUserProperties().get("udId").toString(); IDevice iDevice = udIdMap.get(session); if (typeMap.get(udId) != null) { AndroidDeviceBridgeTool.screen(iDevice, typeMap.get(udId)); } if (picMap.get(udId) != null) { AndroidDeviceBridgeTool.screen(iDevice, picMap.get(udId)); }
<success>
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AudioWSServer.java
AudioWSServer
startAudio
class AudioWSServer implements IAndroidWSServer { @Value("${sonic.agent.key}") private String key; private Map<Session, Thread> audioMap = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId) throws Exception { if (secretKey.length() == 0 || (!secretKey.equals(key))) { log.info("Auth Failed!"); return; } IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId); session.getUserProperties().put("udId", udId); session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId)); WebSocketSessionMap.addSession(session); saveUdIdMapAndSet(session, iDevice); int wait = 0; boolean isInstall = true; while (AndroidAPKMap.getMap().get(udId) == null || (!AndroidAPKMap.getMap().get(udId))) { Thread.sleep(500); wait++; if (wait >= 40) { isInstall = false; break; } } if (!isInstall) { log.info("Waiting for apk install timeout!"); } else { startAudio(session); } } private void startAudio(Session session) {<FILL_FUNCTION_BODY>} private void stopAudio(Session session) { if (audioMap.get(session) != null) { audioMap.get(session).interrupt(); int wait = 0; while (!audioMap.get(session).isInterrupted()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } wait++; if (wait >= 3) { break; } } } audioMap.remove(session); } // @OnMessage // public void onMessage(String message, Session session) { // JSONObject msg = JSON.parseObject(message); // log.info("{} send: {}",session.getUserProperties().get("id").toString(), msg); // switch (msg.getString("type")) { // case "start": // startAudio(session); // break; // case "stop": // stopAudio(session); // break; // } // } @OnClose public void onClose(Session session) { exit(session); } @OnError public void onError(Session session, Throwable error) { log.info("Audio socket error, cause: {}, ignore...", error.getMessage()); } private void exit(Session session) { stopAudio(session); WebSocketSessionMap.removeSession(session); removeUdIdMapAndSet(session); try { session.close(); } catch (IOException e) { e.printStackTrace(); } log.info("{} : quit.", session.getUserProperties().get("id").toString()); } }
stopAudio(session); IDevice iDevice = udIdMap.get(session); AndroidDeviceBridgeTool.executeCommand(iDevice, "appops set org.cloud.sonic.android PROJECT_MEDIA allow"); AndroidDeviceBridgeTool.executeCommand(iDevice, "appops set org.cloud.sonic.android RECORD_AUDIO allow"); AndroidDeviceBridgeTool.executeCommand(iDevice, "am start -n org.cloud.sonic.android/.plugin.audioPlugin.AudioActivity"); int wait = 0; String has = AndroidDeviceBridgeTool.executeCommand(iDevice, "cat /proc/net/unix"); while (!has.contains("sonicaudioservice")) { wait++; if (wait > 8) { return; } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } has = AndroidDeviceBridgeTool.executeCommand(iDevice, "cat /proc/net/unix"); } int appAudioPort = PortTool.getPort(); Thread audio = new Thread(() -> { try { AndroidDeviceBridgeTool.forward(iDevice, appAudioPort, "sonicaudioservice"); Socket audioSocket = null; InputStream inputStream = null; try { audioSocket = new Socket("localhost", appAudioPort); inputStream = audioSocket.getInputStream(); while (audioSocket.isConnected() && !Thread.interrupted()) { byte[] lengthBytes = inputStream.readNBytes(32); if (Thread.interrupted() || lengthBytes.length == 0) { break; } StringBuilder binStr = new StringBuilder(); for (byte lengthByte : lengthBytes) { binStr.append(lengthByte); } Integer readLen = Integer.valueOf(binStr.toString(), 2); byte[] dataBytes = inputStream.readNBytes(readLen); ByteBuffer byteBuffer = ByteBuffer.allocate(dataBytes.length); byteBuffer.put(dataBytes); byteBuffer.flip(); BytesTool.sendByte(session, byteBuffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (audioSocket != null && audioSocket.isConnected()) { try { audioSocket.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch (Exception ignored) { } AndroidDeviceBridgeTool.removeForward(iDevice, appAudioPort, "sonicaudioservice"); }); audio.start(); audioMap.put(session, audio);
826
733
1,559
Thread thread = new Thread(() -> { try { String udId = session.getUserProperties().get("udId").toString(); IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId); AudioRecord audioRecord = new AudioRecord(iDevice); audioRecord.start(); audioMap.put(session, thread); while (!thread.isInterrupted()) { try { session.getBasicRemote().sendText(audioRecord.getAudio()); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }); thread.start();
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AudioWSServer.java<line>87<col>47<err>cannot find symbol <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AudioWSServer.java<line>87<col>17<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSScreenWSServer.java
IOSScreenWSServer
onOpen
class IOSScreenWSServer implements IIOSWSServer { @Value("${sonic.agent.key}") private String key; @Value("${sonic.agent.port}") private int port; @OnOpen public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId, @PathParam("token") String token) throws InterruptedException {<FILL_FUNCTION_BODY>} @OnClose public void onClose(Session session) { exit(session); } @OnError public void onError(Session session, Throwable error) { log.error(error.getMessage()); } private void exit(Session session) { synchronized (session) { ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule"); future.cancel(true); WebSocketSessionMap.removeSession(session); removeUdIdMapAndSet(session); try { session.close(); } catch (IOException e) { e.printStackTrace(); } log.info("{} : quit.", session.getUserProperties().get("id").toString()); } } }
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) { log.info("Auth Failed!"); return; } if (!SibTool.getDeviceList().contains(udId)) { log.info("Target device is not connecting, please check the connection."); return; } session.getUserProperties().put("udId", udId); session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId)); WebSocketSessionMap.addSession(session); saveUdIdMapAndSet(session, udId); int screenPort = 0; int wait = 0; while (wait < 120) { Integer p = IOSWSServer.screenMap.get(udId); if (p != null) { screenPort = p; break; } Thread.sleep(500); wait++; } if (screenPort == 0) { return; } int finalScreenPort = screenPort; new Thread(() -> { URL url; try { url = new URL("http://localhost:" + finalScreenPort); } catch (MalformedURLException e) { return; } MjpegInputStream mjpegInputStream = null; int waitMjpeg = 0; while (mjpegInputStream == null) { try { mjpegInputStream = new MjpegInputStream(url.openStream()); } catch (IOException e) { log.info(e.getMessage()); } try { Thread.sleep(1000); } catch (InterruptedException e) { log.info(e.getMessage()); return; } waitMjpeg++; if (waitMjpeg >= 20) { log.info("mjpeg server connect fail"); return; } } ByteBuffer bufferedImage; int i = 0; while (true) { try { if ((bufferedImage = mjpegInputStream.readFrameForByteBuffer()) == null) break; } catch (IOException e) { log.info(e.getMessage()); break; } i++; if (i % 3 != 0) { sendByte(session, bufferedImage); } else { i = 0; } } try { mjpegInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } log.info("screen done."); }).start(); session.getUserProperties().put("schedule", ScheduleTool.schedule(() -> { log.info("time up!"); if (session.isOpen()) { JSONObject errMsg = new JSONObject(); errMsg.put("msg", "error"); BytesTool.sendText(session, errMsg.toJSONString()); exit(session); } }, BytesTool.remoteTimeout));
325
780
1,105
if (key.equals(secretKey)) { session.getUserProperties().put("id", udId); session.getUserProperties().put("token", token); WebSocketSessionMap.putSession(udId, session); log.info("{} : connected.", udId); } else { session.close(); }
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSScreenWSServer.java<line>60<col>32<err>cannot find symbol
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSTerminalWSServer.java
IOSTerminalWSServer
onOpen
class IOSTerminalWSServer implements IIOSWSServer { @Value("${sonic.agent.key}") private String key; @OnOpen public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId, @PathParam("token") String token) throws Exception {<FILL_FUNCTION_BODY>} @OnMessage public void onMessage(String message, Session session) throws InterruptedException { JSONObject msg = JSON.parseObject(message); log.info("{} send: {}", session.getUserProperties().get("id").toString(), msg); String udId = udIdMap.get(session); switch (msg.getString("type")) { case "processList" -> SibTool.getProcessList(udId, session); case "appList" -> SibTool.getAppList(udId, session); case "syslog" -> SibTool.getSysLog(udId, msg.getString("filter"), session); case "stopSyslog" -> SibTool.stopSysLog(udId); } } @OnClose public void onClose(Session session) { exit(session); } @OnError public void onError(Session session, Throwable error) { log.error(error.getMessage()); JSONObject errMsg = new JSONObject(); errMsg.put("msg", "error"); sendText(session, errMsg.toJSONString()); } private void exit(Session session) { synchronized (session) { ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule"); future.cancel(true); if (udIdMap.get(session) != null) { SibTool.stopSysLog(udIdMap.get(session)); } WebSocketSessionMap.removeSession(session); removeUdIdMapAndSet(session); try { session.close(); } catch (IOException e) { e.printStackTrace(); } log.info("{} : quit.", session.getUserProperties().get("id").toString()); } } }
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) { log.info("Auth Failed!"); return; } if (!SibTool.getDeviceList().contains(udId)) { log.info("Target device is not connecting, please check the connection."); return; } session.getUserProperties().put("udId", udId); session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId)); WebSocketSessionMap.addSession(session); saveUdIdMapAndSet(session, udId); JSONObject ter = new JSONObject(); ter.put("msg", "terminal"); sendText(session, ter.toJSONString()); session.getUserProperties().put("schedule", ScheduleTool.schedule(() -> { log.info("time up!"); if (session.isOpen()) { JSONObject errMsg = new JSONObject(); errMsg.put("msg", "error"); BytesTool.sendText(session, errMsg.toJSONString()); exit(session); } }, BytesTool.remoteTimeout));
570
311
881
if (!key.equals(secretKey)) { session.close(); return; } if (!SibTool.checkToken(udId, token)) { session.close(); return; } if (WebSocketSessionMap.getSession(udId) != null) { exit(WebSocketSessionMap.getSession(udId)); } WebSocketSessionMap.addSession(udId, session); udIdMap.put(session, udId); log.info("{} : connected.", session.getUserProperties().get("id").toString()); JSONObject msg = new JSONObject(); msg.put("msg", "connected"); sendText(session, msg.toJSONString());
<file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSTerminalWSServer.java<line>53<col>21<err>cannot find symbol <file>SonicCloudOrg_sonic-agent/sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSTerminalWSServer.java<line>60<col>28<err>method addSession in class org.cloud.sonic.agent.common.maps.WebSocketSessionMap cannot be applied to given types;
SonicCloudOrg_sonic-agent
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/WebViewWSServer.java
WebViewWSServer
onMessage
class WebViewWSServer { private final Logger logger = LoggerFactory.getLogger(WebViewWSServer.class); @Value("${sonic.agent.key}") private String key; private Map<Session, WebSocketClient> sessionWebSocketClientMap = new HashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("port") int port, @PathParam("id") String id) throws Exception { if (secretKey.length() == 0 || (!secretKey.equals(key))) { logger.info("Auth Failed!"); return; } URI uri = new URI("ws://localhost:" + port + "/devtools/page/" + id); WebSocketClient webSocketClient = new WebSocketClient(uri) { @Override public void onOpen(ServerHandshake serverHandshake) { logger.info("Connected!"); } @Override public void onMessage(String s) { BytesTool.sendText(session, s); } @Override public void onClose(int i, String s, boolean b) { logger.info("Disconnected!"); } @Override public void onError(Exception e) { } }; webSocketClient.connect(); sessionWebSocketClientMap.put(session, webSocketClient); } @OnMessage public void onMessage(String message, Session session) throws InterruptedException {<FILL_FUNCTION_BODY>} @OnClose public void onClose(Session session) { sessionWebSocketClientMap.get(session).close(); sessionWebSocketClientMap.remove(session); } @OnError public void onError(Session session, Throwable error) { logger.error(error.getMessage()); } }
if (sessionWebSocketClientMap.get(session) != null) { try { sessionWebSocketClientMap.get(session).send(message); } catch (Exception e) { } }
470
58
528
sessionWebSocketClientMap.get(session).send(message);
<success>