How to use LinuxVirtualMachine method of sun.tools.attach.LinuxVirtualMachine class

Best Powermock code snippet using sun.tools.attach.LinuxVirtualMachine.LinuxVirtualMachine

Source:LinuxVirtualMachine.java Github

copy

Full Screen

...32import java.io.File;33/*34 * Linux implementation of HotSpotVirtualMachine35 */36public class LinuxVirtualMachine extends HotSpotVirtualMachine {37 // "/tmp" is used as a global well-known location for the files38 // .java_pid<pid>. and .attach_pid<pid>. It is important that this39 // location is the same for all processes, otherwise the tools40 // will not be able to find all Hotspot processes.41 // Any changes to this needs to be synchronized with HotSpot.42 private static final String tmpdir = "/tmp";43 // Indicates if this machine uses the old LinuxThreads44 static boolean isLinuxThreads;45 // The patch to the socket file created by the target VM46 String path;47 /**48 * Attaches to the target VM49 */50 LinuxVirtualMachine(AttachProvider provider, String vmid)51 throws AttachNotSupportedException, IOException52 {53 super(provider, vmid);54 // This provider only understands pids55 int pid;56 try {57 pid = Integer.parseInt(vmid);58 } catch (NumberFormatException x) {59 throw new AttachNotSupportedException("Invalid process identifier");60 }61 // Find the socket file. If not found then we attempt to start the62 // attach mechanism in the target VM by sending it a QUIT signal.63 // Then we attempt to find the socket file again.64 path = findSocketFile(pid);65 if (path == null) {66 File f = createAttachFile(pid);67 try {68 // On LinuxThreads each thread is a process and we don't have the69 // pid of the VMThread which has SIGQUIT unblocked. To workaround70 // this we get the pid of the "manager thread" that is created71 // by the first call to pthread_create. This is parent of all72 // threads (except the initial thread).73 if (isLinuxThreads) {74 int mpid;75 try {76 mpid = getLinuxThreadsManager(pid);77 } catch (IOException x) {78 throw new AttachNotSupportedException(x.getMessage());79 }80 assert(mpid >= 1);81 sendQuitToChildrenOf(mpid);82 } else {83 sendQuitTo(pid);84 }85 // give the target VM time to start the attach mechanism86 int i = 0;87 long delay = 200;88 int retries = (int)(attachTimeout() / delay);89 do {90 try {91 Thread.sleep(delay);92 } catch (InterruptedException x) { }93 path = findSocketFile(pid);94 i++;95 } while (i <= retries && path == null);96 if (path == null) {97 throw new AttachNotSupportedException(98 "Unable to open socket file: target process not responding " +99 "or HotSpot VM not loaded");100 }101 } finally {102 f.delete();103 }104 }105 // Check that the file owner/permission to avoid attaching to106 // bogus process107 checkPermissions(path);108 // Check that we can connect to the process109 // - this ensures we throw the permission denied error now rather than110 // later when we attempt to enqueue a command.111 int s = socket();112 try {113 connect(s, path);114 } finally {115 close(s);116 }117 }118 /**119 * Detach from the target VM120 */121 public void detach() throws IOException {122 synchronized (this) {123 if (this.path != null) {124 this.path = null;125 }126 }127 }128 // protocol version129 private final static String PROTOCOL_VERSION = "1";130 // known errors131 private final static int ATTACH_ERROR_BADVERSION = 101;132 /**133 * Execute the given command in the target VM.134 */135 InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {136 assert args.length <= 3; // includes null137 // did we detach?138 String p;139 synchronized (this) {140 if (this.path == null) {141 throw new IOException("Detached from target VM");142 }143 p = this.path;144 }145 // create UNIX socket146 int s = socket();147 // connect to target VM148 try {149 connect(s, p);150 } catch (IOException x) {151 close(s);152 throw x;153 }154 IOException ioe = null;155 // connected - write request156 // <ver> <cmd> <args...>157 try {158 writeString(s, PROTOCOL_VERSION);159 writeString(s, cmd);160 for (int i=0; i<3; i++) {161 if (i < args.length && args[i] != null) {162 writeString(s, (String)args[i]);163 } else {164 writeString(s, "");165 }166 }167 } catch (IOException x) {168 ioe = x;169 }170 // Create an input stream to read reply171 SocketInputStream sis = new SocketInputStream(s);172 // Read the command completion status173 int completionStatus;174 try {175 completionStatus = readInt(sis);176 } catch (IOException x) {177 sis.close();178 if (ioe != null) {179 throw ioe;180 } else {181 throw x;182 }183 }184 if (completionStatus != 0) {185 // read from the stream and use that as the error message186 String message = readErrorMessage(sis);187 sis.close();188 // In the event of a protocol mismatch then the target VM189 // returns a known error so that we can throw a reasonable190 // error.191 if (completionStatus == ATTACH_ERROR_BADVERSION) {192 throw new IOException("Protocol mismatch with target VM");193 }194 // Special-case the "load" command so that the right exception is195 // thrown.196 if (cmd.equals("load")) {197 throw new AgentLoadException("Failed to load agent library");198 } else {199 if (message == null) {200 throw new AttachOperationFailedException("Command failed in target VM");201 } else {202 throw new AttachOperationFailedException(message);203 }204 }205 }206 // Return the input stream so that the command output can be read207 return sis;208 }209 /*210 * InputStream for the socket connection to get target VM211 */212 private class SocketInputStream extends InputStream {213 int s;214 public SocketInputStream(int s) {215 this.s = s;216 }217 public synchronized int read() throws IOException {218 byte b[] = new byte[1];219 int n = this.read(b, 0, 1);220 if (n == 1) {221 return b[0] & 0xff;222 } else {223 return -1;224 }225 }226 public synchronized int read(byte[] bs, int off, int len) throws IOException {227 if ((off < 0) || (off > bs.length) || (len < 0) ||228 ((off + len) > bs.length) || ((off + len) < 0)) {229 throw new IndexOutOfBoundsException();230 } else if (len == 0)231 return 0;232 return LinuxVirtualMachine.read(s, bs, off, len);233 }234 public void close() throws IOException {235 LinuxVirtualMachine.close(s);236 }237 }238 // Return the socket file for the given process.239 private String findSocketFile(int pid) {240 File f = new File(tmpdir, ".java_pid" + pid);241 if (!f.exists()) {242 return null;243 }244 return f.getPath();245 }246 // On Solaris/Linux a simple handshake is used to start the attach mechanism247 // if not already started. The client creates a .attach_pid<pid> file in the248 // target VM's working directory (or temp directory), and the SIGQUIT handler249 // checks for the file.250 private File createAttachFile(int pid) throws IOException {251 String fn = ".attach_pid" + pid;252 String path = "/proc/" + pid + "/cwd/" + fn;253 File f = new File(path);254 try {255 f.createNewFile();256 } catch (IOException x) {257 f = new File(tmpdir, fn);258 f.createNewFile();259 }260 return f;261 }262 /*263 * Write/sends the given to the target VM. String is transmitted in264 * UTF-8 encoding.265 */266 private void writeString(int fd, String s) throws IOException {267 if (s.length() > 0) {268 byte b[];269 try {270 b = s.getBytes("UTF-8");271 } catch (java.io.UnsupportedEncodingException x) {272 throw new InternalError(x);273 }274 LinuxVirtualMachine.write(fd, b, 0, b.length);275 }276 byte b[] = new byte[1];277 b[0] = 0;278 write(fd, b, 0, 1);279 }280 //-- native methods281 static native boolean isLinuxThreads();282 static native int getLinuxThreadsManager(int pid) throws IOException;283 static native void sendQuitToChildrenOf(int pid) throws IOException;284 static native void sendQuitTo(int pid) throws IOException;285 static native void checkPermissions(String path) throws IOException;286 static native int socket() throws IOException;287 static native void connect(int fd, String path) throws IOException;288 static native void close(int fd) throws IOException;...

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.IOException;3import java.lang.management.ManagementFactory;4import java.lang.management.MemoryMXBean;5import java.lang.management.MemoryUsage;6import java.lang.reflect.Constructor;7import java.lang.reflect.InvocationTargetException;8import java.lang.reflect.Method;9import java.util.List;10import java.util.Map;11import com.sun.tools.attach.VirtualMachine;12import com.sun.tools.attach.VirtualMachineDescriptor;13public class AttachDemo {14 public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {15 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);16 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[1]);17 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[2]);18 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[3]);19 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[4]);20 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[5]);21 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[6]);22 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[7]);23 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[8]);24 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[9]);25 System.out.println("This is the process id of the process running this java program: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[10]);26 System.out.println("This is the process id of the process running this java program: "

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import sun.tools.attach.LinuxVirtualMachine;2public class GetProcessName {3 public static void main(String[] args) {4 if (args.length != 1) {5 System.out.println("Usage: GetProcessName <PID>");6 System.exit(1);7 }8 try {9 int pid = Integer.parseInt(args[0]);10 String processName = LinuxVirtualMachine.getProcessName(pid);11 System.out.println("Process name: " + processName);12 } catch (Exception e) {13 System.out.println("Exception: " + e);14 }15 }16}

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import java.io.File;2import java.io.IOException;3import java.lang.management.ManagementFactory;4import java.lang.reflect.InvocationTargetException;5import java.lang.reflect.Method;6import java.util.ArrayList;7import java.util.List;8import com.sun.tools.attach.VirtualMachine;9import com.sun.tools.attach.VirtualMachineDescriptor;10public class LinuxVirtualMachine {11 public static void main(String[] args) throws IOException, SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {12 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];13 System.out.println("pid: " + pid);14 Method method = VirtualMachine.class.getDeclaredMethod("getProcessId");15 method.setAccessible(true);16 List<VirtualMachineDescriptor> vms = VirtualMachine.list();17 for (VirtualMachineDescriptor vmd : vms) {18 VirtualMachine vm = VirtualMachine.attach(vmd);19 Integer processId = (Integer) method.invoke(vm);20 System.out.println("Virtual Machine: " + vmd.displayName() + ", pid: " + processId + ", id: " + vm.id());21 vm.detach();22 }

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import sun.tools.attach.LinuxVirtualMachine;2import java.util.List;3import java.util.ArrayList;4import java.io.IOException;5import java.io.File;6import java.io.BufferedReader;7import java.io.FileReader;8import java.io.InputStreamReader;9import java.io.InputStream;10import java.io.FileInputStream;11import java.io.FileNotFoundException;12import java.io.UnsupportedEncodingException;13import java.util.Scanner;14import java.util.Iterator;15import java.util.Map;16import java.util.HashMap;17import java.util.Collections;18import java.util.Comparator;19import java.util.regex.Pattern;20import java.util.regex.Matcher;21import java.util.Arrays;22{23 public static void main(String[] args) throws Exception24 {25 List<LinuxVirtualMachine> procList = LinuxVirtualMachine.getProcessList();26 String targetPID = LinuxVirtualMachine.getProcessId("targetProcessName");27 System.out.println("targetPID: " + targetPID);28 for (LinuxVirtualMachine lvm: procList)29 {30 System.out.println("PID: " + lvm.getProcessId());31 System.out.println("ProcessName: " + lvm.getProcessName());32 }33 }34}

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import java.io.BufferedReader;2import java.io.InputStreamReader;3import java.lang.reflect.Method;4import java.util.ArrayList;5import java.util.List;6public static long getPID(String processName) {7 String line;8 long pid = -1;9 try {10 Process p = Runtime.getRuntime().exec("jps -l");11 BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));12 while ((line = input.readLine()) != null) {13 if (line.contains(processName)) {14 String[] parts = line.split(" ");15 pid = Long.parseLong(parts[0]);16 break;17 }18 }19 input.close();20 } catch (Exception ex) {21 ex.printStackTrace();22 }23 return pid;24}

Full Screen

Full Screen

LinuxVirtualMachine

Using AI Code Generation

copy

Full Screen

1import java.io.*;2import java.lang.reflect.*;3import java.util.*;4import sun.tools.attach.*;5{6 public static void main(String[] args) throws Exception7 {8 String pid = getPid(args[0]);9 System.out.println("pid = " + pid);10 List<String> classes = getLoadedClasses(pid);11 for (String className : classes)12 {13 System.out.println(className);14 }15 }16 public static String getPid(String processName) throws Exception17 {18 String pid = null;19 List<String> processes = getRunningProcesses();20 for (String process : processes)21 {22 String[] processInfo = process.split(" ");23 String name = processInfo[processInfo.length - 1];24 if (name.equals(processName))25 {26 pid = processInfo[0];27 break;28 }29 }30 return pid;31 }32 public static List<String> getRunningProcesses() throws Exception33 {34 List<String> processes = new ArrayList<String>();35 Process process = Runtime.getRuntime().exec("ps -e");36 InputStream is = process.getInputStream();37 BufferedReader reader = new BufferedReader(new InputStreamReader(is));38 String line = null;39 while ((line = reader.readLine()) != null)40 {41 processes.add(line);42 }43 return processes;44 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Powermock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful