通过java代码启动和停止postgreSQL服务

时间:2016-09-23 06:34:04

标签: java windows postgresql

我有一个要求,我需要通过java代码启动和停止postgreSQL服务。我写了下面的代码,但我收到了以下错误:

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();
        }
}

以下是我的代码:

public class BroadcastService extends Service {

    private static final String TAG = "BroadcastService";
    public static final String BROADCAST_ACTION = "com.example.activity.displayevent";
    private final Handler handler = new Handler();
    Intent intentBS;
    int counter = 0;
@Override
    public void onCreate() {
        super.onCreate();

        intentBS = new Intent(BROADCAST_ACTION);    
}
 @Override
    public void onStart(Intent intentBS, int startId) {
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            getShiftCode();         
            handler.postDelayed(this, 10000); // 10 seconds
        }
    };    
private void getShiftCode() {
     List<Header> headers = new ArrayList<Header>();
     headers.add(new BasicHeader("Accept", "application/json"));

     EmployeeRestClient.get(BroadcastService.this, "RestExample/shiftcode", 
    headers.toArray(new Header[headers.size()]),null, 
        new JsonHttpResponseHandler() {
     @Override
     public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
     ArrayList<String> scArray = new ArrayList<String>();

       for (int i = 0; i < response.length(); i++) {
        try {
             String Sc_array = c.getString("shift_Code");
             scArray.add(Sc_array);
             } catch (JSONException e) {
             e.printStackTrace();
               }
           }
                shift_Code1= scArray.get(0);
                intentBS.putExtra("shift_Code1", shift_Code1);

           getEmployees();
           sendBroadcast(intentBS);

         }
    });
 }

private void getEmployees() {
     List<Header> headers = new ArrayList<Header>();
     headers.add(new BasicHeader("Accept", "application/json"));

     EmployeeRestClient.get(BroadcastService.this, "RestExample/employee", 
    headers.toArray(new Header[headers.size()]),null, 
        new JsonHttpResponseHandler() {
     @Override
     public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
     ArrayList<String> employeeArray1 = new ArrayList<String>();
     ArrayList<String> employeeArray2 = new ArrayList<String>();

       for (int i = 0; i < response.length(); i++) {
        try {
              String  First_NameArray = c.getString("first_Name");
          String  Second_NameArray = c.getString("second_name");
          employeeArray1.add(First_NameArray );
          employeeArray2.add(Second_NameArray );

             } catch (JSONException e) {
             e.printStackTrace();
               }
           }
             intentBS.putExtra("employee_Array1", employeeArray1);
         intentBS.putExtra("employee_Array2", employeeArray2);
      }
    });
 }

如果我以管理员身份开始我的日食,那么这很好用。此外,如果我在命令提示符下运行启动和停止命令(以管理员身份打开,即右键单击命令提示符图标并单击“以管理员身份运行”),则它们会成功执行。但是如果我在正常命令提示符下运行命令(不是以管理员身份打开),那么我也会遇到相同的错误。

请告知是否有任何解决方案或任何方法来解决此问题。

1 个答案:

答案 0 :(得分:0)

在java中,有一个以管理员身份运行Windows cmd的选项

使用以下代码替换您的代码“commands.add("cmd.exe");”并尝试

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