List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:ch.entwine.weblounge.common.impl.util.process.ProcessExecutor.java
/** * Executes the process. During execution, {@link #onLineRead(String)} will be * called for process output. When finished, {@link #onProcessFinished(int)} * is called.//from www. ja va2 s . c o m * * @throws ProcessExcecutorException * if an error occurs during execution */ public final void execute() throws ProcessExcecutorException { BufferedReader in = null; Process process = null; StreamHelper errorStreamHelper = null; try { // create process. // no special working directory is set which means the working directory // of the current java process is used. ProcessBuilder pbuilder = new ProcessBuilder(commandLine); pbuilder.redirectErrorStream(redirectErrorStream); process = pbuilder.start(); // Consume error stream if necessary if (!redirectErrorStream) { errorStreamHelper = new StreamHelper(process.getErrorStream()); } // Read input and in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = in.readLine()) != null) { if (!onLineRead(line)) break; } // wait until the task is finished process.waitFor(); int exitCode = process.exitValue(); onProcessFinished(exitCode); } catch (Throwable t) { String msg = null; if (errorStreamHelper != null) { msg = errorStreamHelper.contentBuffer.toString(); } else { msg = t.getMessage(); } // TODO: What if the error stream has been redirected? Can we still get // the error message? throw new ProcessExcecutorException(msg, t); } finally { if (process != null) process.destroy(); IOUtils.closeQuietly(in); } }
From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java
@Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor = new NullProgressMonitor(); }/*from ww w. j a va 2 s. c o m*/ monitor.beginTask(configuration.getName() + "...", 6); if (monitor.isCanceled()) { return; } try { monitor.subTask("Verifying launch attributes"); String mainTypeName = getMainTypeName(configuration); File workingDir = getWorkingDirectory(configuration); String[] envp = getEnvironment(configuration); List<String> pgmArgs = splitArgs(getProgramArguments(configuration)); List<String> vmArgs = splitArgs(getVMArguments(configuration)); String[] classpath = getClasspath(configuration); String[] bootclasspath = getBootpath(configuration); IJavaProject javaProject = getJavaProject(configuration); int debuggerPort = findFreePort(); boolean hasDebugPlugin = false; if (monitor.isCanceled()) { return; } // Verification done monitor.worked(1); RoboVMPlugin.consoleInfo("Building executable"); monitor.subTask("Creating source locator"); setDefaultSourceLocator(launch, configuration); monitor.worked(1); monitor.subTask("Creating build configuration"); Config.Builder configBuilder; try { configBuilder = new Config.Builder(); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID, "Launch failed. Check the RoboVM console for more information.", e)); } configBuilder.logger(RoboVMPlugin.getConsoleLogger()); File projectRoot = getJavaProject(configuration).getProject().getLocation().toFile(); RoboVMPlugin.loadConfig(configBuilder, projectRoot, isTestConfiguration()); Arch arch = getArch(configuration, mode); OS os = getOS(configuration, mode); configBuilder.os(os); configBuilder.arch(arch); File tmpDir = RoboVMPlugin.getBuildDir(getJavaProjectName(configuration)); tmpDir = new File(tmpDir, configuration.getName()); tmpDir = new File(new File(tmpDir, os.toString()), arch.toString()); if (mainTypeName != null) { tmpDir = new File(tmpDir, mainTypeName); } if (ILaunchManager.DEBUG_MODE.equals(mode)) { configBuilder.debug(true); String sourcepaths = RoboVMPlugin.getSourcePaths(javaProject); configBuilder.addPluginArgument("debug:sourcepath=" + sourcepaths); configBuilder.addPluginArgument("debug:jdwpport=" + debuggerPort); configBuilder.addPluginArgument( "debug:logdir=" + new File(projectRoot, "robovm-logs").getAbsolutePath()); // check if we have the debug plugin for (Plugin plugin : configBuilder.getPlugins()) { if ("DebugLaunchPlugin".equals(plugin.getClass().getSimpleName())) { hasDebugPlugin = true; } } } if (bootclasspath != null) { configBuilder.skipRuntimeLib(true); for (String p : bootclasspath) { configBuilder.addBootClasspathEntry(new File(p)); } } for (String p : classpath) { configBuilder.addClasspathEntry(new File(p)); } if (mainTypeName != null) { configBuilder.mainClass(mainTypeName); } // we need to filter those vm args that belong to plugins // in case of iOS run configs, we can only pass program args filterPluginArguments(vmArgs, configBuilder); filterPluginArguments(pgmArgs, configBuilder); configBuilder.tmpDir(tmpDir); configBuilder.skipInstall(true); Config config = null; AppCompiler compiler = null; try { RoboVMPlugin.consoleInfo("Cleaning output dir " + tmpDir.getAbsolutePath()); FileUtils.deleteDirectory(tmpDir); tmpDir.mkdirs(); Home home = RoboVMPlugin.getRoboVMHome(); if (home.isDev()) { configBuilder.useDebugLibs(Boolean.getBoolean("robovm.useDebugLibs")); configBuilder.dumpIntermediates(true); } configBuilder.home(home); config = configure(configBuilder, configuration, mode).build(); compiler = new AppCompiler(config); if (monitor.isCanceled()) { return; } monitor.worked(1); monitor.subTask("Building executable"); AppCompilerThread thread = new AppCompilerThread(compiler, monitor); thread.compile(); if (monitor.isCanceled()) { RoboVMPlugin.consoleInfo("Build canceled"); return; } monitor.worked(1); RoboVMPlugin.consoleInfo("Build done"); } catch (InterruptedException e) { RoboVMPlugin.consoleInfo("Build canceled"); return; } catch (IOException e) { RoboVMPlugin.consoleError("Build failed"); throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID, "Build failed. Check the RoboVM console for more information.", e)); } try { RoboVMPlugin.consoleInfo("Launching executable"); monitor.subTask("Launching executable"); mainTypeName = config.getMainClass(); List<String> runArgs = new ArrayList<String>(); runArgs.addAll(vmArgs); runArgs.addAll(pgmArgs); LaunchParameters launchParameters = config.getTarget().createLaunchParameters(); launchParameters.setArguments(runArgs); launchParameters.setWorkingDirectory(workingDir); launchParameters.setEnvironment(envToMap(envp)); customizeLaunchParameters(config, launchParameters, configuration, mode); String label = String.format("%s (%s)", mainTypeName, DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date())); // launch plugin may proxy stdout/stderr fifo, which // it then writes to. Need to save the original fifos File stdOutFifo = launchParameters.getStdoutFifo(); File stdErrFifo = launchParameters.getStderrFifo(); PipedInputStream pipedIn = new PipedInputStream(); PipedOutputStream pipedOut = new PipedOutputStream(pipedIn); Process process = compiler.launchAsync(launchParameters, pipedIn); if (stdOutFifo != null || stdErrFifo != null) { InputStream stdoutStream = null; InputStream stderrStream = null; if (launchParameters.getStdoutFifo() != null) { stdoutStream = new OpenOnReadFileInputStream(stdOutFifo); } if (launchParameters.getStderrFifo() != null) { stderrStream = new OpenOnReadFileInputStream(stdErrFifo); } process = new ProcessProxy(process, pipedOut, stdoutStream, stderrStream, compiler); } IProcess iProcess = DebugPlugin.newProcess(launch, process, label); // setup the debugger if (ILaunchManager.DEBUG_MODE.equals(mode) && hasDebugPlugin) { VirtualMachine vm = attachToVm(monitor, debuggerPort); // we were canceled if (vm == null) { process.destroy(); return; } if (vm instanceof VirtualMachineImpl) { ((VirtualMachineImpl) vm).setRequestTimeout(DEBUGGER_REQUEST_TIMEOUT); } JDIDebugModel.newDebugTarget(launch, vm, mainTypeName + " at localhost:" + debuggerPort, iProcess, true, false, true); } RoboVMPlugin.consoleInfo("Launch done"); if (monitor.isCanceled()) { process.destroy(); return; } monitor.worked(1); } catch (Throwable t) { RoboVMPlugin.consoleError("Launch failed"); throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID, "Launch failed. Check the RoboVM console for more information.", t)); } } finally { monitor.done(); } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void _buildModule(String tablename) throws Exception { BufferedReader br = null;/*from w w w . j av a 2 s . c o m*/ try { try { String anthome = System.getenv("ANT_HOME"); String antpath = "ant "; if (anthome != null) { antpath = anthome + "bin\\ant.bat "; } String command = antpath + " buildmyjar -Dmodulename=" + tablename; File buildXMLFile = new File(PropsValues.PROJECT_HOME); // Process process = Runtime.getRuntime().exec(command); Process process = Runtime.getRuntime().exec(command, null, buildXMLFile); // Get the input stream and read from it br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null, output = ""; while ((line = br.readLine()) != null) { output += line + "\n"; } System.out.print(output); process.destroy(); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } com.krawler.runtime.utils.URLClassLoaderUtil urlObj = new com.krawler.runtime.utils.URLClassLoaderUtil( new URL[] {}); File jarFile = new File(PropsValues.PROJECT_HOME + "lib\\module-" + tablename + ".jar"); urlObj.addFile(jarFile); } catch (Exception e) { logger.warn(e.getMessage(), e); } finally { if (br != null) { br.close(); } } }
From source file:com.google.dart.tools.debug.core.configs.DartServerLaunchConfigurationDelegate.java
protected void launchVM(ILaunch launch, DartLaunchConfigWrapper launchConfig, boolean enableDebugging, IProgressMonitor monitor) throws CoreException { // Usage: dart [options] script.dart [arguments] File currentWorkingDirectory = getCurrentWorkingDirectory(launchConfig); String scriptPath = launchConfig.getApplicationName(); scriptPath = translateToFilePath(currentWorkingDirectory, scriptPath); String vmExecPath = ""; if (DartSdkManager.getManager().hasSdk()) { File vmExec = DartSdkManager.getManager().getSdk().getVmExecutable(); if (vmExec != null) { vmExecPath = vmExec.getAbsolutePath().toString(); }/*from w w w . j a va 2s.c o m*/ } else { vmExecPath = DartDebugCorePlugin.getPlugin().getDartVmExecutablePath(); } if (vmExecPath.length() == 0) { throw new CoreException( DartDebugCorePlugin.createErrorStatus("The executable path for the Dart VM has not been set.")); } List<String> commandsList = new ArrayList<String>(); int connectionPort = NetUtils.findUnusedPort(DEFAULT_PORT_NUMBER); commandsList.add(vmExecPath); commandsList.addAll(Arrays.asList(launchConfig.getVmArgumentsAsArray())); if (enableDebugging) { commandsList.add("--debug:" + connectionPort); } observatoryPort = NetUtils.findUnusedPort(0); launchConfig.setObservatoryPort(observatoryPort); launchConfig.save(); commandsList.add("--enable-vm-service:" + observatoryPort); commandsList.add("--trace_service_pause_events"); if (launchConfig.getPauseIsolateOnExit()) { commandsList.add("--pause-isolates-on-exit"); } if (launchConfig.getPauseIsolateOnStart()) { commandsList.add("--pause-isolates-on-start"); } // This lets us debug isolates. if (enableDebugging) { commandsList.add("--break-at-isolate-spawn"); } String coverageTempDir = null; if (DartCoreDebug.ENABLE_COVERAGE) { coverageTempDir = CoverageManager.createTempDir(); commandsList.add("--coverage_dir=" + coverageTempDir); } String packageRoot = DartCore.getPlugin().getVmPackageRoot(launchConfig.getProject()); if (packageRoot != null) { String fileSeparator = System.getProperty("file.separator"); if (!packageRoot.endsWith(fileSeparator)) { packageRoot += fileSeparator; } commandsList.add("--package-root=" + packageRoot); } commandsList.add(scriptPath); commandsList.addAll(Arrays.asList(launchConfig.getArgumentsAsArray())); String[] commands = commandsList.toArray(new String[commandsList.size()]); ProcessBuilder processBuilder = new ProcessBuilder(commands); if (currentWorkingDirectory != null) { processBuilder.directory(currentWorkingDirectory); } Process runtimeProcess = null; try { runtimeProcess = processBuilder.start(); if (coverageTempDir != null) { UriToFileResolver uriToFileResolver = new UriToFileResolver(launch); CoverageManager.registerProcess(uriToFileResolver, coverageTempDir, launchConfig.getApplicationName(), runtimeProcess); } } catch (IOException ioe) { throw new CoreException( new Status(IStatus.ERROR, DartDebugCorePlugin.PLUGIN_ID, ioe.getMessage(), ioe)); } IProcess eclipseProcess = null; Map<String, String> processAttributes = new HashMap<String, String>(); String programName = "dart"; processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName); processAttributes.put(IProcess.ATTR_CMDLINE, describe(processBuilder)); if (runtimeProcess != null) { monitor.beginTask("Dart", IProgressMonitor.UNKNOWN); eclipseProcess = DebugPlugin.newProcess(launch, runtimeProcess, launchConfig.getApplicationName() + " (" + new Date() + ")", processAttributes); } if (runtimeProcess == null || eclipseProcess == null) { if (runtimeProcess != null) { runtimeProcess.destroy(); } throw new CoreException(DartDebugCorePlugin.createErrorStatus("Error starting Dart VM process")); } eclipseProcess.setAttribute(IProcess.ATTR_CMDLINE, describe(processBuilder)); if (enableDebugging) { ServerDebugTarget debugTarget = new ServerDebugTarget(launch, eclipseProcess, connectionPort); try { debugTarget.connect(); launch.addDebugTarget(debugTarget); } catch (DebugException ex) { // We don't throw an exception if the process died before we could connect. if (!isProcessDead(runtimeProcess)) { throw ex; } } } monitor.done(); }
From source file:org.wso2.carbon.integration.tests.carbontools.Wsdl2JavaCommandTestCase.java
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE }) @Test(groups = "carbon.core", description = "Generate java codes from wsdl using wsdl2java script") public void testWsdl2JavaCodeGeneration() throws CarbonToolsIntegrationTestException, XPathExpressionException { boolean fileCreated = false; Process process = null; String commandDirectory;/*w w w . ja v a 2s. c om*/ try { String wsdlURL = automationContext.getContextUrls().getServiceUrl() + "/Version?wsdl"; log.info("Service URL -" + wsdlURL); String[] cmdArrayToWsdl2Java; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem() .contains(OperatingSystems.WINDOWS.name().toLowerCase()))) { throw new SkipException("Bug when running wsdl2java.bat on windows"); //TODO - uncomment the following code when carbon 15151 is fixed //https://wso2.org/jira/browse/CARBON-15151 //cmdArrayToWsdl2Java = //new String[]{"cmd.exe", "/c", "wsdl2java.bat", "-uri", serviceUrl}; //commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + //File.separator + "bin"; } else { cmdArrayToWsdl2Java = new String[] { "sh", "wsdl2java.sh", "-uri", wsdlURL }; commandDirectory = System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin"; } process = CarbonCommandToolsUtil.runScript(commandDirectory, cmdArrayToWsdl2Java); fileCreated = CarbonCommandToolsUtil.waitForFileCreation(System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "bin" + File.separator + "src" + File.separator + "org" + File.separator + "wso2" + File.separator + "carbon" + File.separator + "core" + File.separator + "services" + File.separator + "version" + File.separator + "VersionStub.java"); } finally { if (process != null) { process.destroy(); } } assertTrue(fileCreated, "Java file not created successfully"); }
From source file:org.alfresco.util.exec.RuntimeExec.java
/** * Executes the statement that this instance was constructed with an optional * timeout after which the command is asked to * /*from ww w. j a v a2 s .c om*/ * @param properties the properties that the command might be executed with. * <code>null</code> properties will be treated as an empty string for substitution * purposes. * @param timeoutMs a timeout after which {@link Process#destroy()} is called. * ignored if less than or equal to zero. Note this method does not guarantee * to terminate the process (it is not a kill -9). * * @return Returns the full execution results */ public ExecutionResult execute(Map<String, String> properties, final long timeoutMs) { int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1; // check that the command has been set if (command == null) { throw new AlfrescoRuntimeException("Runtime command has not been set: \n" + this); } // create the properties Runtime runtime = Runtime.getRuntime(); Process process = null; String[] commandToExecute = null; try { // execute the command with full property replacement commandToExecute = getCommand(properties); final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory); process = thisProcess; if (timeoutMs > 0) { final String[] command = commandToExecute; timer.schedule(new TimerTask() { @Override public void run() { // Only try to kill the process if it is still running try { thisProcess.exitValue(); } catch (IllegalThreadStateException stillRunning) { if (transformerDebugLogger.isDebugEnabled()) { transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000) + " seconds). Killing process " + Arrays.deepToString(command)); } thisProcess.destroy(); } } }, timeoutMs); } } catch (IOException e) { // The process could not be executed here, so just drop out with an appropriate error state String execOut = ""; String execErr = e.getMessage(); int exitValue = defaultFailureExitValue; ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut, execErr); logFullEnvironmentDump(result); return result; } // create the stream gobblers InputStreamReaderThread stdOutGobbler = new InputStreamReaderThread(process.getInputStream(), charset); InputStreamReaderThread stdErrGobbler = new InputStreamReaderThread(process.getErrorStream(), charset); // start gobbling stdOutGobbler.start(); stdErrGobbler.start(); // wait for the process to finish int exitValue = 0; try { if (waitForCompletion) { exitValue = process.waitFor(); } } catch (InterruptedException e) { // process was interrupted - generate an error message stdErrGobbler.addToBuffer(e.toString()); exitValue = defaultFailureExitValue; } if (waitForCompletion) { // ensure that the stream gobblers get to finish stdOutGobbler.waitForCompletion(); stdErrGobbler.waitForCompletion(); } // get the stream values String execOut = stdOutGobbler.getBuffer(); String execErr = stdErrGobbler.getBuffer(); // construct the return value ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut, execErr); // done logFullEnvironmentDump(result); return result; }
From source file:edu.umd.cs.buildServer.BuildServer.java
public boolean alreadyRunning() throws Exception { int oldPid = getPidFileContents(false); if (oldPid < 0) return false; ProcessBuilder b = new ProcessBuilder( new String[] { "/bin/ps", "xww", "-o", "pid,lstart,user,state,pcpu,cputime,args" }); String user = System.getProperty("user.name"); Process p = b.start(); try {/* w w w .j a v a 2s . co m*/ Scanner s = new Scanner(p.getInputStream()); String header = s.nextLine(); // log.trace("ps header: " + header); while (s.hasNext()) { String txt = s.nextLine(); if (!txt.contains(user)) continue; int pid = Integer.parseInt(txt.substring(0, 5).trim()); if (pid == oldPid) { if (!isQuiet()) { System.out.println("BuildServer is already running"); System.out.println(txt); } return true; } } s.close(); } finally { p.destroy(); } long pidLastModified = getPidFile().lastModified(); String msg = "Previous buildserver pid " + oldPid + " died; had started at " + new Date(pidLastModified); System.out.println(msg); File currentFile = getCurrentFile(); long currentFileLastModified = currentFile.lastModified(); if (currentFile.exists() && currentFileLastModified >= pidLastModified) { Scanner scanner = new Scanner(currentFile); int submissionPK = scanner.nextInt(); int testSetupPK = scanner.nextInt(); scanner.nextLine(); // skip EOL String kind = scanner.nextLine().trim(); String load = scanner.nextLine().trim(); scanner.close(); reportBuildServerDeath(submissionPK, testSetupPK, currentFileLastModified, kind, load); } currentFile.delete(); getPidFile().delete(); System.out.println("Deleting old pid file"); return false; }
From source file:org.spoutcraft.launcher.skin.ConsoleFrame.java
/** * Construct the frame.//w w w . jav a 2 s. co m * * @param numLines number of lines to show at a time * @param colorEnabled true to enable a colored console * @param trackProc process to track * @param killProcess true to kill the process on console close */ public ConsoleFrame(int numLines, boolean colorEnabled, final Process trackProc, final boolean killProcess) { super("Console"); this.numLines = numLines; this.colorEnabled = colorEnabled; this.trackProc = trackProc; this.highlightedAttributes = new SimpleAttributeSet(); StyleConstants.setForeground(highlightedAttributes, Color.BLACK); StyleConstants.setBackground(highlightedAttributes, Color.YELLOW); this.errorAttributes = new SimpleAttributeSet(); StyleConstants.setForeground(errorAttributes, new Color(200, 0, 0)); this.infoAttributes = new SimpleAttributeSet(); StyleConstants.setForeground(infoAttributes, new Color(200, 0, 0)); this.debugAttributes = new SimpleAttributeSet(); StyleConstants.setForeground(debugAttributes, Color.DARK_GRAY); setSize(new Dimension(650, 400)); buildUI(); Compatibility.setIconImage(this, Toolkit.getDefaultToolkit().getImage(LoginFrame.spoutcraftIcon)); if (trackProc != null) { track(trackProc); } addMouseListener(this); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { if (trackProc != null && killProcess) { trackProc.destroy(); if (loggerHandler != null) { rootLogger.removeHandler(loggerHandler); } event.getWindow().dispose(); } } }); }
From source file:org.pepstock.jem.junit.init.submitters.AbstractSubmitter.java
/** * //from w w w .ja va2s.co m * @param command * @param args * @return * @throws NodeMessageException * @throws IOException * @throws InterruptedException */ int launch(String command, String[] args) throws NodeMessageException, IOException, InterruptedException { String osCommand = null; if (SystemUtils.IS_OS_WINDOWS) { osCommand = command + ".cmd"; } else { osCommand = command + ".sh"; } Process process = null; try { File logFile = File.createTempFile("junit", "log"); String redirect = "> " + FilenameUtils.normalize(logFile.getAbsolutePath(), true) + " 2>&1"; StringBuilder sb = new StringBuilder(osCommand); for (String arg : args) { sb.append(" ").append(arg); } System.err.println(sb.toString()); sb.append(" ").append(redirect); // create a process builder ProcessBuilder builder = new ProcessBuilder(); Shell shell = CurrentPlatform.getInstance().getShell(); builder.command(shell.getName(), shell.getParameters(), sb.toString()); // set directory where execute process builder.directory(new File(System.getenv("JEM_HOME") + "/bin")); // load variable environment from a temporary maps that you can use // inside of configure method. Map<String, String> env = System.getenv(); Map<String, String> map = builder.environment(); for (Map.Entry<String, String> e : env.entrySet()) { map.put(e.getKey(), e.getValue()); } // start process and save instance process = builder.start(); // wait for end of job execution int rc = process.waitFor(); FileInputStream fis = new FileInputStream(logFile); IOUtils.copy(fis, System.out); IOUtils.closeQuietly(fis); logFile.delete(); return rc; } finally { if (process != null) { process.destroy(); } } }
From source file:org.intermine.install.swing.CreateDatabaseWorker.java
/** * Create a database using the Postgres <code>createdb</code> program. * //from ww w. jav a2s .co m * @param server The database server. * @param databaseName The database name. * @param userName The database user name. * @param password The user password. * @param encoding The encoding for the database. * * @throws IOException if there is a problem running <code>createdb</code>. * * @throws InterruptedException if the thread is interrupted while running * the <code>createdb</code>. * * @throws DatabaseCreationException if the process completes but failed * to create the database. */ protected void createDatabaseWithCreatedb(String server, String databaseName, String userName, String password, String encoding) throws IOException, InterruptedException, DatabaseCreationException { String[] commands = { "/usr/bin/createdb", "-h", server, "-E", encoding, "-O", userName, "-W", "-T", "template0", databaseName }; if (logger.isDebugEnabled()) { StringBuilder command = new StringBuilder(); for (int i = 0; i < commands.length; i++) { if (i > 0) { command.append(' '); } command.append(commands[i]); } logger.debug(command); } StringBuilder output = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); Integer exitCode = null; Process p = Runtime.getRuntime().exec(commands); try { BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream())); boolean passwordSet = false; while (true) { try { while (stdin.ready()) { char c = (char) stdin.read(); output.append(c); } while (stderr.ready()) { char c = (char) stderr.read(); errorOutput.append(c); } if (!passwordSet && errorOutput.indexOf("Password:") >= 0) { PrintStream out = new PrintStream(p.getOutputStream(), true); out.println(password); passwordSet = true; } exitCode = p.exitValue(); // If this succeeds, we're done. break; } catch (IllegalThreadStateException e) { // Process not done, so wait and continue. Thread.sleep(250); } } } finally { try { p.exitValue(); } catch (IllegalThreadStateException e) { // Not finished, but something has failed. p.destroy(); } } if (errorOutput.length() > 0) { throw new DatabaseCreationException(exitCode, output.toString(), errorOutput.toString()); } if (exitCode != 0) { throw new DatabaseCreationException("Return code from createdb = " + exitCode, exitCode, output.toString(), errorOutput.toString()); } }