Best Powermock code snippet using sun.tools.attach.LinuxVirtualMachine.read
Source:LinuxVirtualMachine.java
...39 // 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;289 static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;290 static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;291 static {292 System.loadLibrary("attach");293 isLinuxThreads = isLinuxThreads();294 }295}...
read
Using AI Code Generation
1package com.journaldev;2import java.io.BufferedReader;3import java.io.IOException;4import java.io.InputStreamReader;5import java.util.Arrays;6import java.util.List;7import java.util.stream.Collectors;8import sun.tools.attach.LinuxVirtualMachine;9public class AttachToProcess {10 public static void main(String[] args) throws Exception {11 List<String> pids = getProcessIds();12 System.out.println("Process IDs: "+pids);13 for (String pid : pids) {14 try {15 LinuxVirtualMachine vm = LinuxVirtualMachine.attach(pid);16 System.out.println("Process Name: "+vm.getSystemProperties().getProperty("sun.java.command"));17 vm.detach();18 } catch (Exception e) {19 e.printStackTrace();20 }21 }22 }23 private static List<String> getProcessIds() throws IOException {24 Process p = Runtime.getRuntime().exec("jps -l");25 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {26 return input.lines().map(line -> line.split(" ")[0]).collect(Collectors.toList());27 }28 }29}
read
Using AI Code Generation
1import sun.tools.attach.LinuxVirtualMachine;2import sun.tools.attach.LinuxVirtualMachineDescriptor;3import java.util.List;4import java.util.Scanner;5import java.util.Vector;6import java.util.stream.Collectors;7import java.util.stream.Stream;8public class Main {9 public static void main(String[] args) throws Exception {10 String pid = args[0];11 String cmd = args[1];12 LinuxVirtualMachine vm = null;13 try {14 vm = LinuxVirtualMachine.attach(pid);15 String output = vm.execute(cmd);16 System.out.println(output);17 } finally {18 if (vm != null) {19 vm.detach();20 }21 }22 }23}24import sun.tools.attach.LinuxVirtualMachineDescriptor;25import java.util.List;26import java.util.Scanner;27import java.util.Vector;28import java.util.stream.Collectors;29import java.util.stream.Stream;30public class Main {31 public static void main(String[] args) throws Exception {32 List<LinuxVirtualMachineDescriptor> vmds = LinuxVirtualMachineDescriptor.list();33 Vector<String> pids = new Vector<String>();34 for(LinuxVirtualMachineDescriptor vmd: vmds){35 pids.add(vmd.id());36 }37 System.out.println(pids);38 }39}40import sun.tools.attach.LinuxVirtualMachineDescriptor;41import java.util.List;42import java.util.Scanner;43import java.util.Vector;44import java.util.stream.Collectors;45import java.util.stream.Stream;46public class Main {47 public static void main(String[] args) throws Exception {48 List<LinuxVirtualMachineDescriptor> vmds = LinuxVirtualMachineDescriptor.list();49 Vector<String> pids = new Vector<String>();50 for(LinuxVirtualMachineDescriptor vmd: vmds){51 pids.add(vmd.id());52 }53 System.out.println(pids);54 }55}56import sun.tools.attach.LinuxVirtualMachine;57import sun.tools.attach.LinuxVirtualMachineDescriptor;58import java.util.List;59import java.util.Scanner;60import java.util.Vector;61import java.util.stream.Collectors;62import java.util.stream.Stream;63public class Main {64 public static void main(String[] args) throws Exception {65 String pid = args[0];66 LinuxVirtualMachine vm = null;67 try {
read
Using AI Code Generation
1import sun.tools.attach.LinuxVirtualMachine;2import java.io.IOException;3import java.lang.reflect.InvocationTargetException;4import java.lang.reflect.Method;5import java.util.List;6import java.util.stream.Collectors;7import java.util.stream.Stream;8public class PidFinder {9 public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {10 List<String> pids = Stream.of(LinuxVirtualMachine.list()).filter(pid -> {11 try {12 LinuxVirtualMachine vm = LinuxVirtualMachine.attach(pid);13 String name = vm.getSystemProperties().getProperty("sun.java.command");14 vm.detach();15 return name != null && name.contains("com.mycompany.app.MyApp");16 } catch (Exception e) {17 return false;18 }19 }).collect(Collectors.toList());20 System.out.println(pids);21 }22}
read
Using AI Code Generation
1import sun.tools.attach.LinuxVirtualMachine;2import sun.tools.attach.LinuxVirtualMachineDescriptor;3import java.util.List;4import java.util.ArrayList;5import java.util.Arrays;6import java.util.concurrent.TimeUnit;7import java.util.concurrent.ExecutorService;8import java.util.concurrent.Executors;9public class GetPid {10 public static void main(String[] args) throws Exception {11 List<LinuxVirtualMachineDescriptor> lvmList = LinuxVirtualMachine.list();12 int pid = -1;13 for (LinuxVirtualMachineDescriptor lvm : lvmList) {14 if (lvm.displayName().contains("MyJavaApp")) {15 pid = lvm.id();16 }17 }18 System.out.println("pid = " + pid);19 if (pid > 0) {20 LinuxVirtualMachine vm = LinuxVirtualMachine.attach(pid);21 System.out.println("vm = " + vm);22 String cmd = "jstack " + pid;23 System.out.println("cmd = " + cmd);24 String output = vm.execute(cmd, new ArrayList<String>());25 System.out.println("output = " + output);26 vm.detach();27 }28 }29}30 at java.lang.Thread.sleep(Native Method)31 at java.lang.Thread.sleep(Thread.java:340)32 at java.lang.Thread.sleep(Thread.java:280)33 at com.roytuts.java.get.pid.GetPid.main(GetPid
read
Using AI Code Generation
1import java.lang.management.ManagementFactory;2import sun.tools.attach.LinuxVirtualMachine;3import sun.tools.attach.LinuxVirtualMachineDescriptor;4public class GetProcessID {5 public static void main(String[] args) throws Exception {6 String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];7 System.out.println(pid);8 LinuxVirtualMachine vm = LinuxVirtualMachine.getVirtualMachine(Integer.parseInt(pid));9 System.out.println(vm.getProcessId());10 System.out.println(vm.getSystemProperties());11 for (LinuxVirtualMachineDescriptor desc : LinuxVirtualMachine.listVirtualMachines()) {12 System.out.println(desc.displayName());13 System.out.println(desc.id());14 }15 }16}
read
Using AI Code Generation
1import java.io.*;2import java.lang.management.*;3import java.util.*;4import sun.tools.attach.*;5public class HeapDumpReader {6 public static void main(String[] args) throws Exception {7 if (args.length != 2) {8 System.err.println("Usage: java HeapDumpReader <PID> <class>");9 System.exit(1);10 }11 int pid = Integer.parseInt(args[0]);12 String className = args[1];13 String heapDumpFile = "/tmp/heapdump";14 LinuxVirtualMachine vm = LinuxVirtualMachine.attach(pid);15 try {16 vm.dumpHeap(heapDumpFile);17 System.out.println("Heap dump written to " + heapDumpFile);18 try (FileInputStream in = new FileInputStream(heapDumpFile);19 BufferedInputStream buf = new BufferedInputStream(in);20 DataInputStream dis = new DataInputStream(buf)) {21 long startTime = System.currentTimeMillis();22 long size = 0;23 long count = 0;24 long instances = 0;25 long total = 0;26 long skipped = 0;27 long skippedSize = 0;28 long skippedInstances = 0;29 long skippedTotal = 0;30 long skippedSizeTotal = 0;31 long skippedInstancesTotal = 0;32 long skippedSizeInstances = 0;33 long skippedSizeInstancesTotal = 0;34 long skippedSizeInstancesSize = 0;35 long skippedSizeInstancesSizeTotal = 0;36 long skippedSizeInstancesSizeInstances = 0;37 long skippedSizeInstancesSizeInstancesTotal = 0;38 long skippedSizeInstancesSizeInstancesSize = 0;39 long skippedSizeInstancesSizeInstancesSizeTotal = 0;40 long skippedSizeInstancesSizeInstancesSizeInstances = 0;41 long skippedSizeInstancesSizeInstancesSizeInstancesTotal = 0;42 long skippedSizeInstancesSizeInstancesSizeInstancesSize = 0;43 long skippedSizeInstancesSizeInstancesSizeInstancesSizeTotal = 0;44 long skippedSizeInstancesSizeInstancesSizeInstancesSizeInstances = 0;45 long skippedSizeInstancesSizeInstancesSizeInstancesSizeInstancesTotal = 0;46 long skippedSizeInstancesSizeInstancesSizeInstancesSizeInstancesSize = 0;
read
Using AI Code Generation
1import java.io.*;2import java.util.*;3import java.lang.management.*;4import java.lang.reflect.*;5import java.util.concurrent.*;6import java.util.concurrent.locks.*;7import java.util.concurrent.atomic.*;8import java.lang.management.*;9import java.util.concurrent.locks.*;10import java.util.concurrent.atomic.*;11import java.lang.reflect.*;12import java.lang.management.*;13import java.util.concurrent.locks.*;14import java.util.concurrent.atomic.*;15import java.lang.reflect.*;16import java.lang.management.*;17import java.util.concurrent.locks.*;18import java.util.concurrent.atomic.*;19import java.lang.reflect.*;20import java.lang.management.*;21import java.util.concurrent.locks.*;22import java.util.concurrent.atomic.*;23import java.lang.reflect.*;24import java.lang.management.*;25import java.util.concurrent.locks.*;26import java.util.concurrent.atomic.*;27import java.lang.reflect.*;28import java.lang.management.*;29import java.util.concurrent.locks.*;30import java.util.concurrent.atomic.*;31import java.lang.reflect.*;32import java.lang.management.*;33import java.util.concurrent.locks.*;34import java.util.concurrent.atomic.*;35import java.lang.reflect.*;36import java.lang.management.*;37import java.util.concurrent.locks.*;38import java.util.concurrent.atomic.*;39import java.lang.reflect.*;40import java.lang.management.*;41import java.util.concurrent.locks.*;42import java.util.concurrent.atomic.*;43import java.lang.reflect.*;44import java.lang.management.*;45import java.util.concurrent.locks.*;46import java.util.concurrent.atomic.*;47import java.lang.reflect.*;48import java.lang.management.*;49import java.util.concurrent.locks.*;50import java.util.concurrent.atomic.*;51import java.lang.reflect.*;52import java.lang.management.*;53import java.util.concurrent.locks.*;54import java.util.concurrent.atomic.*;55import java.lang.reflect.*;56import java.lang.management.*;57import java.util.concurrent.locks.*;58import java.util.concurrent.atomic.*;59import java.lang.reflect.*;60import java.lang.management.*;61import java.util.concurrent.locks.*;62import java.util.concurrent.atomic.*;63import java.lang.reflect.*;64import java.lang.management.*;65import java.util.concurrent.locks.*;66import java.util.concurrent.atomic.*;67import java.lang.reflect.*;68import java.lang.management.*;69import java.util.concurrent.locks.*;70import java.util.concurrent.atomic.*;71import java.lang.reflect.*;72import java.lang.management.*;73import java.util.concurrent.locks.*;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!