Example usage for java.lang Process getClass

List of usage examples for java.lang Process getClass

Introduction

In this page you can find the example usage for java.lang Process getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:uk.ac.susx.tag.method51.core.organise.subprocess.JVMInstance.java

public void run(ProcessBuilder pb) throws IOException {
    Process process = pb.start();

    //new StreamGobbler(process.getErrorStream()).start();

    try {//  w  w w  .  ja v a 2 s.  c  o m
        Field f = process.getClass().getDeclaredField("pid");
        f.setAccessible(true);
        int pid = f.getInt(process);

        writePid(pid);

    } catch (NoSuchFieldException | IllegalAccessException e) {
        LOG.error("Exception caught", e);
    }
}

From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java

private void extractLocal() throws Exception {

    URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar");
    String homeDir = System.getProperty("user.home");
    String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar";
    File dest = new File(remoteJarFile);
    try {//from  w  w w  .ja v  a 2  s .  c  om
        FileUtils.copyURLToFile(localJarUrl, dest);
    } catch (Exception e) {
        logger.error(e.toString());
    }

    String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY);
    String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY);
    String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY);
    String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY);
    String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1));
    String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY);
    // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY);
    String hdfsExtractLogFile = outputSchemaFile + ".log";

    String[] hadoopCmd = { "hadoop", "jar", remoteJarFile,
            "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile,
            "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile,
            "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster,
            "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList,
            "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread,
            "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" };
    // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab,
    ProcessBuilder pb = new ProcessBuilder(hadoopCmd);
    File logFile = new File(hdfsExtractLogFile);
    pb.redirectErrorStream(true);
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile));
    Process process = pb.start();
    int pid = -1;
    if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
        /* get the PID on unix/linux systems */
        try {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            pid = f.getInt(process);
        } catch (Throwable e) {
        }
    }
    logger.info("executue command [PID=" + pid + "]: " + hadoopCmd);

    // wait until this process finished.
    int execResult = process.waitFor();

    // if the process failed, log the error and throw exception
    if (execResult > 0) {
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String errString = "HDFS Metadata Extract Error:\n";
        String line = "";
        while ((line = br.readLine()) != null)
            errString = errString.concat(line).concat("\n");
        logger.error("*** Process  failed, status: " + execResult);
        logger.error(errString);
        throw new Exception("Process + " + pid + " failed");
    }

}

From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java

/**
 * Attempt to get the process id for this process
 * /*from  www .  j  a  va2 s .  c  om*/
 * @param process The process to get the id from
 * @return The id of the process
 */
private int processId(final java.lang.Process process) {
    int processId = 0;
    try {
        Field f = process.getClass().getDeclaredField("pid");
        f.setAccessible(true);

        processId = f.getInt(process);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return processId;
}

From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

/**
 * Helper method  to get process id for the given process.
 *
 * @param proc java process object representing the job launcher
 * @return pid for this process/*  w ww .  ja v a 2s . co m*/
 * @throws GenieException if there is an error getting the process id
 */
private int getProcessId(final Process proc) throws GenieException {
    log.debug("called");

    try {
        final Field f = proc.getClass().getDeclaredField(JobConstants.PID);
        f.setAccessible(true);
        return f.getInt(proc);
    } catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException
            | SecurityException e) {
        final String msg = "Can't get process id for job";
        log.error(msg, e);
        throw new GenieServerException(msg, e);
    }
}

From source file:net.pms.service.ProcessManager.java

/**
 * Retrieves the process ID (PID) for the specified {@link Process}.
 *
 * @param process the {@link Process} for whose PID to retrieve.
 * @return The PID or zero if the PID couldn't be retrieved.
 *//* w w w . j a  va2s . com*/
public static int getProcessId(@Nullable Process process) {
    if (process == null) {
        return 0;
    }
    try {
        Field field;
        if (Platform.isWindows()) {
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            int pid = Kernel32.INSTANCE.GetProcessId(new HANDLE(new Pointer(field.getLong(process))));
            if (pid == 0 && LOGGER.isDebugEnabled()) {
                int lastError = Kernel32.INSTANCE.GetLastError();
                LOGGER.debug("KERNEL32.getProcessId() failed with error {}", lastError);
            }
            return pid;
        }
        field = process.getClass().getDeclaredField("pid");
        field.setAccessible(true);
        return field.getInt(process);
    } catch (Exception e) {
        LOGGER.warn("Failed to get process id for process \"{}\": {}", process, e.getMessage());
        LOGGER.trace("", e);
        return 0;
    }
}

From source file:net.pms.service.ProcessManager.java

/**
 * Checks if the process is still alive using reflection if possible.
 *
 * @param process the {@link Process} to check.
 * @return {@code true} if the process is still alive, {@code false}
 *         otherwise./* w ww  . j  ava 2 s. c o  m*/
 */
@SuppressFBWarnings("REC_CATCH_EXCEPTION")
public static boolean isProcessIsAlive(@Nullable Process process) {
    if (process == null) {
        return false;
    }
    // XXX replace with Process.isAlive() in Java 8
    try {
        Field field;
        field = process.getClass().getDeclaredField("handle");
        field.setAccessible(true);
        long handle = (long) field.get(process);
        field = process.getClass().getDeclaredField("STILL_ACTIVE");
        field.setAccessible(true);
        int stillActive = (int) field.get(process);
        Method method;
        method = process.getClass().getDeclaredMethod("getExitCodeProcess", long.class);
        method.setAccessible(true);
        int exitCode = (int) method.invoke(process, handle);
        return exitCode == stillActive;
    } catch (Exception e) {
        // Reflection failed, use the backup solution
    }
    try {
        process.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:com.baifendian.swordfish.execserver.job.ProcessJob.java

/**
 *  id//from  w  w w .j a v a 2  s  .  c o  m
 *
 * @param process ?
 * @return  id
 */
private int getProcessId(Process process) {
    int processId = 0;

    try {
        Field f = process.getClass().getDeclaredField("pid");
        f.setAccessible(true);

        processId = f.getInt(process);
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
    }

    return processId;
}

From source file:com.netflix.genie.server.jobmanager.impl.JobManagerImpl.java

/**
 * Get process id for the given process.
 *
 * @param proc java process object representing the job launcher
 * @return pid for this process//from   w  w w  . j a  va 2  s  .  c o m
 * @throws GenieException if there is an error getting the process id
 */
private int getProcessId(final Process proc) throws GenieException {
    LOG.debug("called");

    try {
        final Field f = proc.getClass().getDeclaredField(PID);
        f.setAccessible(true);
        return f.getInt(proc);
    } catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException
            | SecurityException e) {
        final String msg = "Can't get process id for job";
        LOG.error(msg, e);
        throw new GenieServerException(msg, e);
    }
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

public void destroyProcess(Process process) {
    final String classGetName = process.getClass().getName();
    if ("JAVA_LANG_WIN32_PROCESS".equals(classGetName)
            || "java.lang.ProcessImpl".equals(process.getClass().getName())) {
        // determine the pid on windowsplattforms
        process.destroy();//from w w  w. j av  a  2s. c  om
        try {
            Field field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            final int pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process));
            // killing the task.
            Runtime.getRuntime().exec("taskkill " + pid);

        } catch (SecurityException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (NoSuchFieldException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IOException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IllegalArgumentException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IllegalAccessException e) {
            System.out.println("Error in Killing the process:" + e);
        }

    }
}

From source file:org.wso2.carbon.integration.tests.carbontools.CarbonServerBasicOperationTestCase.java

@Test(groups = { "carbon.core" }, description = "Testing server startup argument --start")
public void testServerStartCommand() throws Exception {
    String[] cmdArrayToStart;/*  w w  w  .  j a v  a  2s.  c o  m*/
    Process process;

    if (CarbonCommandToolsUtil.getCurrentOperatingSystem()
            .contains(OperatingSystems.WINDOWS.name().toLowerCase())) {
        //Skipping the test execution on Windows
        throw new SkipException("--start option is not available for windows");
    } else {
        cmdArrayToStart = new String[] { "sh", "wso2server.sh", "--start", "-DportOffset=" + portOffset };

    }
    process = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArrayToStart);

    // Waiting until start the server
    boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(automationContext, portOffset);

    Field field = process.getClass().getDeclaredField("pid");
    field.setAccessible(true);
    processId = field.get(process).toString();
    log.info("process id for carbon server with offset " + portOffset + " : " + processId);

    assertTrue(startupStatus, "Unsuccessful login");
}