简体   繁体   中英

Start and stop postgreSQL service through java code

I have one requirement where I need to start and stop postgreSQL service through java code. I have written below code but I am getting below error:

    System error 5 has occurred.

    Access is denied.

    System error 5 has occurred.

    Access is denied.

Below is my code:

package frontend.guifx.pginstallation;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import common.core.Logger;

import frontend.guifx.util.ConstPG;

public class StartAndStopPostgres {
    public static String version = "9.5";
    public static void main(String[] args){
        try {
            System.out.println("Execution starts");
            copyPostgreSqlConfFileAndRestartPg();
            System.out.println("Execution finished");

        } catch (IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

        private static void copyPostgreSqlConfFileAndRestartPg() throws IOException, InterruptedException {
            // TODO Auto-generated method stub
            Path path = Paths.get("data/PGLogs");
            //if directory exists?
            if (!Files.exists(path)) {
                try {
                    Files.createDirectories(path);
                } catch (IOException e) {
                    //fail to create directory
                    e.printStackTrace();
                }
            }
            Logger.print(StartAndStopPostgres.class, new String[] { "Copying postgresql.conf file ........" });
            Path source = Paths.get("data/postgresql.windows.conf");
            String copyConfFileTo = getInstallationPath(version);
            copyConfFileTo = copyConfFileTo.substring(0, copyConfFileTo.lastIndexOf("\\"));
            Path outputDirectoryPath = Paths.get(copyConfFileTo+File.separator+"data");
            Files.copy(source, outputDirectoryPath.resolve(outputDirectoryPath.getFileSystem().getPath("postgresql.conf")), StandardCopyOption.REPLACE_EXISTING);
            Logger.print(StartAndStopPostgres.class, new String[] { "Tunning datbase starts........" });

            Runtime rt = Runtime.getRuntime();
            final File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ConstPG.CREATE_RESTART_PG_BAT_FILE);
            PrintWriter writer = new PrintWriter(file, "UTF-8");
            writer.println("net stop postgresql-x64-"+version);
            writer.println("net start postgresql-x64-"+version);
            writer.close();
            String executeSqlCommand = file.getAbsolutePath();
            Process process = rt.exec(executeSqlCommand);

            /*final List<String> commands = new ArrayList<String>();
            commands.add("cmd.exe");
            commands.add("/C");
            commands.add("net stop postgresql-x64-9.5");
            commands.add("net start postgresql-x64-9.5");
            ProcessBuilder b = new ProcessBuilder(commands);
            Process process = b.start();*/
            //public static final String PG_RESTART_PG_LOG_FILE = PG_LOGS+"/pgRestartProcess.log";
            File createPgRestartProcessFile = new File(ConstPG.PG_RESTART_PG_LOG_FILE);
            redirectProcessExecutionOutput(process, createPgRestartProcessFile);
            int exitVal = process.waitFor();
            Logger.print(StartAndStopPostgres.class, new String[] { "EXIT VALUE after tunning the PostgreSql database :::::::::::::::::::::" + exitVal + " Logs written to file at: " + createPgRestartProcessFile.getAbsolutePath() });

        }

        public static String getInstallationPath( String version) {
            //public static final String PROGRAMME_FILES = "C:\\Program Files\\";
//          public static final String PROGRAMME_FILES_X86 = "C:\\Program Files (x86)\\";
//          public static final String POSTGRESQL = "PostgreSQL";
//          public static final String PSQL_PATH = "\\bin\\psql.exe";

            //Const values used below are as above

            String psql = findFile(ConstPG.PROGRAMME_FILES, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
            if (psql == null) {
                psql = findFile(ConstPG.PROGRAMME_FILES_X86, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
            }
            if(psql != null){
                psql = psql.substring(0, psql.lastIndexOf("\\"));
            }
            return psql;
        }

        public static String findFile(String directoryName, String fileName) {
            File directory = new File(directoryName);

            // get all the files from a directory
            File[] fList = directory.listFiles();

            String absolutePath;

            if (fList != null) {
                for (File file : fList) {
                    if (file.isFile()) {
                        absolutePath = file.getAbsolutePath();
                        if (absolutePath.contains(fileName))
                            return (absolutePath);
                    } else if (file.isDirectory()) {
                        absolutePath = findFile(file.getAbsolutePath(), fileName);
                        if (absolutePath != null)
                            return (absolutePath);
                    }
                }
            }
            return (null);
        }


        private static void redirectProcessExecutionOutput(Process process, File processFile) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = null;
            FileWriter fw = new FileWriter(processFile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            while ((line = reader.readLine()) != null) {
                Logger.print(StartAndStopPostgres.class, new String[] { line });
                bw.write(line);
                bw.newLine();
            }
            bw.close();
        }
}

If I start my eclipse as an Administrator then this works fine. Also if I run start and stop commands on command prompt (which is opened as an Administrator ie right click on command prompt icon and click 'run as Administrator') then they execute successfully. But if I run the commands on normal command prompt (which is not opened as a administrator) then I get the same error there as well.

Please advise if there is any solution or any approach to solve this problem.

In java there is a option to run windows cmd as administrator

replace your code " commands.add("cmd.exe"); " with below code and try

commands.add("runas /profile /user:ADMINUSERNAME \"cmd.exe");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM