public String executeCommand(String srvrmgrCommand) throws IOException, SrvrMgrException { String result = ""; if (!this.getLocked()) this.setLocked(); else throw new IOException("Instance locked while trying to execute command " + srvrmgrCommand); byte[] inputData = new byte[1024]; try { processInput.write(srvrmgrCommand); processInput.newLine(); processInput.flush(); /*TODO: debug*/ processLog(srvrmgrCommand, "Input command"); } catch (IOException ex) { if (!srvrmgrCommand.equals("exit")) { getProcessInput().close(); getProcessOutputStream().close(); getProcess().destroy(); startProcess(); result = executeCommand(srvrmgrCommand); Loggers.SERVER.error( Util.PLUGIN_NAME + ": Process has been killed. Restarting process", ex); // throw new SrvrMgrException("Process has been killed. Restarting process"); return result; } else Loggers.SERVER.error(Util.PLUGIN_NAME + ": Process has been killed already", ex); // throw new SrvrMgrException("Process has been killed already"); } while ((readInputStreamWithTimeout(processOutputStream, inputData, 1000)) > 0 || !result.contains("srvrmgr>")) { result += new String(inputData, StandardCharsets.UTF_8); inputData = new byte[1024]; if (result.contains("Disconnecting from server")) break; } this.setLastCommandDate(System.currentTimeMillis()); this.setUnLocked(); /*TODO: debug*/ processLog(result, getLastCommandDate(), "Command output"); return result; }
private static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis) throws IOException { try { int bufferOffset = 0; long maxTimeMillis = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) { int readLength = java.lang.Math.min(is.available(), b.length - bufferOffset); int readResult = is.read(b, bufferOffset, readLength); if (readResult == -1) break; bufferOffset += readResult; } return bufferOffset; } catch (IOException ex) { Loggers.SERVER.error("Error reading stream. Stream closed: " + ex); return -1; } }
private static int getProcessId(Process process) { int PID = 0; if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handl = f.getLong(process); Kernel kernel = Kernel.INSTANCE; W32API.HANDLE handle = new W32API.HANDLE(); handle.setPointer(Pointer.createConstant(handl)); PID = kernel.GetProcessId(handle); } catch (Throwable e) { Loggers.SERVER.error("PID PROBLEM " + e); } } return PID; }