List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:org.fusesource.ide.buildtools.Downloader.java
public void downloadArchetypes() throws IOException { if (delete) { FileUtils.deleteDirectory(archetypeDir); archetypeDir.mkdirs();// w w w . j av a 2s . c o m } PrintWriter out = new PrintWriter(new FileWriter(new File(archetypeDir, "archetypes.xml"))); out.println("<archetypes>"); try { downloadArchetypesForGroup(out, "org.apache.camel.archetypes", System.getProperty("camel.version")); downloadArchetypesForGroup(out, "org.apache.cxf.archetype", System.getProperty("cxf.version")); // removed fabric8 archetypes // downloadArchetypesForGroup(out, "io.fabric8.archetypes", System.getProperty("fabric.version")); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); } finally { out.println("</archetypes>"); out.close(); } LOG.info("Running git add..."); ProcessBuilder pb = new ProcessBuilder("git", "add", "*"); pb.directory(archetypeDir); pb.start(); }
From source file:net.rim.ejde.internal.packaging.PackagingManager.java
private void runRapcCommand() throws CoreException { try {/*from ww w .j a va 2s. c om*/ File workDir = _bbProject.getProject().getLocation().toFile(); if (writeToFile) { File outputFile = null; String outputFileName = _bbProject.getProject().getName() + ".files"; outputFile = new File(workDir, outputFileName); _rapcCommandsHead.add("@" + outputFileName); flushToFile(outputFile); } else { _rapcCommandsHead.addAll(_rapcCommands); } String command = getStringCommand(_rapcCommandsHead); _log.trace("Execute rapc command: " + command + "; Working Directory: " + workDir.getPath()); ProcessBuilder rapcBuilder = new ProcessBuilder(_rapcCommandsHead); String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { Map<String, String> env = rapcBuilder.environment(); String pathName = "Path"; for (String s : env.keySet()) { if (s.equalsIgnoreCase("Path")) pathName = s; } String path = env.get(pathName); path = path == null ? javaHome : (path + File.pathSeparator + javaHome); path = path + File.pathSeparator + javaHome + File.separator + "bin"; env.put(pathName, path); _log.trace("PATH=" + path); } rapcBuilder.directory(workDir); rapcBuilder.redirectErrorStream(true); long startTime = System.currentTimeMillis(); _consoleOutputStream.println( NLS.bind(Messages.PackagingManager_PACKAGING_PROJECT_MSG, _bbProject.getProject().getName())); _consoleOutputStream.println(command); Process process = rapcBuilder.start(); InputStream inStream = process.getInputStream(); InputStreamHandler inputHandler = new InputStreamHandler(_bbProject.getProject(), _consoleOutputStream, inStream); inputHandler.start(); int result = process.waitFor(); inputHandler.join(); float spendTime = ((float) (System.currentTimeMillis() - startTime)) / 1000; if (result == 0) { _consoleOutputStream.println(NLS.bind(Messages.PackagingManager_PACKAGING_SUCCEED_MSG, new String[] { _bbProject.getProject().getName(), String.valueOf(spendTime) })); } else { _consoleOutputStream.println(NLS.bind(Messages.PackagingManager_PACKAGING_FAILED_MSG, new String[] { _bbProject.getProject().getName(), String.valueOf(spendTime) })); } } catch (IOException e) { throw new CoreException(StatusFactory.createErrorStatus(e.getMessage())); } catch (InterruptedException e) { throw new CoreException(StatusFactory.createErrorStatus(e.getMessage())); } }
From source file:org.squidy.nodes.MultiTouch.java
@Override public final void onStart() { super.onStart(); startOSCServer();/*from w w w.jav a 2 s. c o m*/ fireStatusChange("pixelclock", getPixelclock(), pixelclock); int camID = getCameraID(); int portOut = 4000 + camID; int portIn = 4100 + camID; setOscPortConfigIn(portIn); setOscPortConfigOut(portOut); fireStatusChange("osc-port-in", getOscPortConfigIn(), portIn); fireStatusChange("osc-port-out", getOscPortConfigOut(), portOut); if (cameraConfigComm != null) cameraConfigComm.closeConnections(); cameraConfigComm = new CameraConfigComm(remoteAddress, getOscPortConfigOut(), getOscPortConfigIn(), getImageServerPort(), Endian.LITTLE_ENDIAN, this); // laserServer = new LaserServer(this, laserPositionPort); // configManager = new ConfigManager(this, laserConfigurationPort); // proxy = new ProxyServer(this, proxyConfigurationPort, true); // imageServer = new ProxyServer(this, proxyCameraPort, false); frame = new JFrame("Image Display"); frame.setLayout(new BorderLayout()); // frame.setSize(new Dimension(800, 800)); // frame.setPreferredSize(new Dimension(800, 800)); // //frame.setResizable(false); imageDisplay = new ImageDisplay(); imageDisplay.setBackground(Color.BLACK); imageDisplay.setSize(200, 200); imageDisplay.setPreferredSize(new Dimension(200, 200)); imageDisplay.setRequiredCornerPoints(patternW * patternH); frame.setBackground(Color.BLACK); frame.add(imageDisplay, BorderLayout.CENTER); JButton clearCorners = new JButton("Delete All Corner Points"); clearCorners.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int option = JOptionPane.showConfirmDialog(frame, "Would you like to remove all corner points?", "Remove corner points", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.YES_OPTION) { imageDisplay.deleteAllCornerPoints(); } } }); frame.add(clearCorners, BorderLayout.SOUTH); // frame.add(imageDisplay); // Insets insets = frame.getInsets(); frame.pack(); frame.validate(); if (getMode() != MODE_OFF) frame.setVisible(true); new Thread() { public void run() { super.run(); while (isProcessing()) { try { trackerSocket = new Socket(remoteAddress, remotePort); System.out.println("Connected to Touch Tracker"); connectedToTracker = true; cameraConfigComm.setStopped(false); if (isTrackFingers() == true) setTrackFingers(isTrackFingers()); else sendAllTrackingParams(); //close SquidyVision windows if (!displayBlobDetector) cameraConfigComm.sendParameter("display-blob-detector", "bool", "false"); BufferedReader in = new BufferedReader( new InputStreamReader(trackerSocket.getInputStream())); in.readLine(); } catch (UnknownHostException e1) { System.out.println("Connection to Touch Tracker closed. Retrying..."); imageDisplay.repaint(); connectedToTracker = false; cameraConfigComm.setStopped(true); } catch (IOException e1) { System.out.println("Connection to Touch Tracker closed. Retrying..."); imageDisplay.repaint(); connectedToTracker = false; cameraConfigComm.setStopped(true); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); if (isStartTrackingAutomatically() && !connectedToTracker) { new Thread() { /** * */ @Override public void run() { super.run(); String curDir = System.getProperty("user.dir"); System.out.println("Java Working Directory: " + curDir); // if the tracker isn't running if (!connectedToTracker && !trackerRunning()) { ProcessBuilder pb = new ProcessBuilder( new String[] { "ext/" + trackerProgramName, Integer.toString(getCameraID()) }); pb.directory(new File(".", "ext")); Process process = null; try { process = pb.start(); // camerasReady++; // if (camerasReady == cameras && !isTracking) { // new Thread() { // public void run() { // try { // sleep(6000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // if (laserConfigClient == null) { // laserConfigClient = new LaserConfigClient(); // } // // laserConfigClient.startAllTracking(); // }; // }.start(); // } processInputStreamReading(process); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getMessage(), e); } publishFailure(e); } if (process != null) { cameraProcesses.add(process); } } } }.start(); } // check number of set corner points final int difference = imageDisplay.getRequiredCornerPoints() - imageDisplay.getNumberOfCornerPoints(); if (difference != 0) { if (difference > 0) ReacTIVision.showErrorPopUp("Too few corner points set."); else ReacTIVision.showErrorPopUp("Too many corner points set."); } }
From source file:com.microsoft.webapp.debug.WebAppLaunchConfigurationDelegate.java
@Override public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { final ILaunchConfiguration configToUse = config; String port = "8000"; Map<String, String> conMap = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP, new HashMap<String, String>()); for (java.util.Map.Entry<String, String> entry : conMap.entrySet()) { if (entry.getKey().equalsIgnoreCase("port")) { port = entry.getValue();/* w w w . j a v a 2 s . c o m*/ } } final String portToDisplayError = port; try { // check port availability if (Utils.isPortAvailable(Integer.parseInt(port))) { // get web app name to which user want to debug his application String website = config.getAttribute(AzureLaunchConfigurationAttributes.WEBSITE_DISPLAY, ""); if (!website.isEmpty()) { website = website.substring(0, website.indexOf('(')).trim(); Map<WebSite, WebSiteConfiguration> webSiteConfigMap = PreferenceWebAppUtil.load(); // retrieve web apps configurations for (Entry<WebSite, WebSiteConfiguration> entry : webSiteConfigMap.entrySet()) { final WebSite websiteTemp = entry.getKey(); if (websiteTemp.getName().equals(website)) { // check is there a need for preparation AzureManager manager = AzureManagerImpl.getManager(); final WebSiteConfiguration webSiteConfiguration = entry.getValue(); final WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings( webSiteConfiguration.getSubscriptionId(), webSiteConfiguration.getWebSpaceName(), website); // case - if user uses shortcut without going to Azure Tab Map<String, Boolean> mp = Activator.getDefault().getWebsiteDebugPrep(); if (!mp.containsKey(website)) { mp.put(website, false); } Activator.getDefault().setWebsiteDebugPrep(mp); if (Activator.getDefault().getWebsiteDebugPrep().get(website).booleanValue()) { // already prepared. Just start debugSession.bat // retrieve MSDeploy publish profile WebSitePublishSettings.MSDeployPublishProfile msDeployProfile = null; for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof MSDeployPublishProfile) { msDeployProfile = (MSDeployPublishProfile) pp; break; } } if (msDeployProfile != null) { ProcessBuilder pb = null; String os = System.getProperty("os.name").toLowerCase(); String webAppDirPath = String.format("%s%s%s", PluginUtil.pluginFolder, File.separator, com.microsoft.webapp.util.Messages.webAppPluginID); if (Activator.IS_WINDOWS) { String command = String.format(Messages.command, port, website, msDeployProfile.getUserName(), msDeployProfile.getPassword()); pb = new ProcessBuilder("cmd", "/c", "start", "cmd", "/k", command); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // escape $ for linux String userName = "\\" + msDeployProfile.getUserName(); String command = String.format(Messages.commandSh, port, website, userName, msDeployProfile.getPassword()); pb = new ProcessBuilder("/bin/bash", "-c", command); } else { // escape $ for mac String userName = "'" + msDeployProfile.getUserName() + "'"; // On mac, you need to specify exact path of JAR String command = String.format(Messages.commandMac, webAppDirPath + "/", port, website, userName, msDeployProfile.getPassword()); String commandNext = "tell application \"Terminal\" to do script \"" + command + "\""; pb = new ProcessBuilder("osascript", "-e", commandNext); } pb.directory(new File(webAppDirPath)); try { pb.start(); Thread.sleep(10000); } catch (Exception e) { Activator.getDefault().log(Messages.errTtl, e); } super.launch(config, mode, launch, monitor); } } else { // start the process of preparing the web app, in a blocking way Display.getDefault().syncExec(new Runnable() { @Override public void run() { boolean choice = MessageDialog.openConfirm(PluginUtil.getParentShell(), Messages.title, Messages.remoteDebug); if (choice) { IRunnableWithProgress op = new PrepareForDebug(websiteTemp, webSiteConfiguration, webSitePublishSettings); try { new ProgressMonitorDialog(PluginUtil.getParentShell()).run(true, true, op); MessageDialog.openInformation(PluginUtil.getParentShell(), Messages.title, Messages.debugReady); } catch (Exception e) { Activator.getDefault().log(e.getMessage(), e); } } WebAppUtils.openDebugLaunchDialog(configToUse); } }); } break; } } } } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { PluginUtil.displayErrorDialog(PluginUtil.getParentShell(), Messages.errTtl, String.format(Messages.portMsg, portToDisplayError)); WebAppUtils.openDebugLaunchDialog(configToUse); } }); } } catch (Exception ex) { Activator.getDefault().log(ex.getMessage(), ex); } }
From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java
@Override public String startServiceForSimultion(String serviceId, String runtimeOptions, Map<String, Object> simulationContext) { String instanceId = serviceId + "-" + new Date().getTime(); // get execution path ServiceInfo serviceInfo = services.get(serviceId); if (serviceInfo == null) { //TODO: publish error on status topic throw new RuntimeException("Service not found: " + serviceId); }/* w ww.j a v a2s. c o m*/ // are multiple allowed? if not check to see if it is already running, if it is then fail if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) { throw new RuntimeException( "Service is already running and multiple instances are not allowed: " + serviceId); } File serviceDirectory = new File( getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId); ProcessBuilder processServiceBuilder = new ProcessBuilder(); Process process = null; List<String> commands = new ArrayList<String>(); Map<String, String> envVars = processServiceBuilder.environment(); //set environment variables List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables(); for (EnvironmentVariable envVar : envVarList) { String value = envVar.getEnvValue(); //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (value.contains("(")) { String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")"); for (String args : replaceValue) { value = value.replace("(" + args + ")", simulationContext.get(args).toString()); } } } envVars.put(envVar.getEnvName(), value); } //add executation command commands.add(serviceInfo.getExecution_path()); //Check if static args contain any replacement values List<String> staticArgsList = serviceInfo.getStatic_args(); for (String staticArg : staticArgsList) { if (staticArg != null) { //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (staticArg.contains("(")) { String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")"); for (String args : replaceArgs) { staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString()); } } } commands.add(staticArg); } } if (runtimeOptions != null) { commands.add(runtimeOptions); } try { if (serviceInfo.getType().equals(ServiceType.PYTHON)) { commands.add(0, "python"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.EXE)) { processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.JAVA)) { commands.add(0, "java -jar"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.WEB)) { } else { throw new RuntimeException("Type not recognized " + serviceInfo.getType()); } } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace); StringBuilder commandString = new StringBuilder(); for (String s : commands) { commandString.append(s); commandString.append(" "); } logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); } //create serviceinstance object ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId, process); serviceInstance.setService_info(serviceInfo); //add to service instances map serviceInstances.put(instanceId, serviceInstance); return instanceId; }
From source file:net.rptools.maptool.launcher.MapToolLauncher.java
/** * Launch MT in a separate process with its own JVM. * /*from w w w . j a va2 s.c o m*/ * Note that each string passed in must have just a single "argument". Which * is to say that you can't just lump them all into one string and pass * that. So the max mem gets one, the min mem gets one and so on. * * @throws IOException */ private void launchMapTool() throws IOException { ProcessBuilder pb = null; List<String> cmdArgs; File log = new File(mapToolDataDir, "log.txt"); // Lee: console options if (startConsole) { if (IS_WINDOWS) { cmdArgs = getLaunchCommand(invocationCommands[1], mapToolJarDir); // log = null; // Windows doesn't like having multiple tasks opening the same file for writing all at once } else if (IS_MAC) { cmdArgs = getLaunchCommand(invocationCommands[0], mapToolJarDir); pb = new ProcessBuilder(new String[] { "open", "-a", "Console", log.toString() }); pb.start(); } else { // Lee: Linux launch cmdArgs = getLaunchCommand(invocationCommands[2], mapToolJarDir); } } else { // Lee: launch normally cmdArgs = getLaunchCommand(invocationCommands[0], mapToolJarDir); } pb = new ProcessBuilder(cmdArgs); logMsg(Level.INFO, "Setting current directory to: {0}. Command line is {1}.", null, new Object[] { mapToolJarDir, cmdArgs.toString() }); try { pb.directory(mapToolJarDir); // This is a great idea, but .redirectOutput() requires Java 1.7+ so it won't build for // J6 and hence users with the Java provided by Apple can't use the launcher. :( // if (log != null) // pb.redirectOutput(log).redirectErrorStream(true); pb.start(); } catch (final IOException ex) { logMsg(Level.SEVERE, "Error starting MapTool instance; dir={0}, cmd={1}\n{2}", "msg.error.startingMapTool", mapToolJarDir, cmdArgs, ex); return; } }
From source file:jeplus.JEPlusFrameMain.java
private void jMenuItemJEPlusEAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemJEPlusEAActionPerformed // Check if JEPlus+EA folder is available if (JEPlusConfig.getDefaultInstance().getJEPlusEADir() == null) { // Select a file to open fc.resetChoosableFileFilters();//from w w w. j ava2 s .co m fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setCurrentDirectory(new File("./")); fc.setMultiSelectionEnabled(false); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { String path = fc.getSelectedFile().getPath() + File.separator; JEPlusConfig.getDefaultInstance().setJEPlusEADir(path); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); } else { fc.setFileSelectionMode(JFileChooser.FILES_ONLY); return; } } // Launch JESS Client new Thread(new Runnable() { @Override public void run() { List<String> command = new ArrayList<>(); command.add("java"); command.add("-jar"); command.add("jEPlus+EA.jar"); command.add(getCurrentProjectFile()); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(JEPlusConfig.getDefaultInstance().getJEPlusEADir())); builder.redirectErrorStream(true); try { Process proc = builder.start(); // int ExitValue = proc.waitFor(); try (BufferedReader ins = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { int res = ins.read(); while (res != -1) { res = ins.read(); } } } catch (IOException ex) { logger.error("Cannot run jEPlus+EA.", ex); } } }, "jEPlus+EA").start(); }
From source file:jeplus.JEPlusFrameMain.java
private void jMenuItemJESSClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemJESSClientActionPerformed // Check if JESS Client folder is available if (JEPlusConfig.getDefaultInstance().getJESSClientDir() == null) { String ori = fc.getDialogTitle(); // Select a file to open fc.setDialogTitle("Choose where JESS Client is located"); fc.resetChoosableFileFilters();//from w w w . j a v a 2 s . c o m fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setCurrentDirectory(new File("./")); fc.setMultiSelectionEnabled(false); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { String path = fc.getSelectedFile().getPath() + File.separator; JEPlusConfig.getDefaultInstance().setJESSClientDir(path); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setDialogTitle(ori); } else { fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setDialogTitle(ori); return; } } // Launch JESS Client new Thread(new Runnable() { @Override public void run() { List<String> command = new ArrayList<>(); command.add("java"); command.add("-jar"); command.add("jess_client_v3.jar"); command.add(getProject().getBaseDir()); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(JEPlusConfig.getDefaultInstance().getJESSClientDir())); builder.redirectErrorStream(true); try { Process proc = builder.start(); // int ExitValue = proc.waitFor(); try (BufferedReader ins = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { int res = ins.read(); while (res != -1) { res = ins.read(); } } } catch (IOException ex) { logger.error("Cannot run JESS_Client.", ex); } } }, "JESS_Client").start(); }
From source file:com.kdmanalytics.toif.framework.toolAdaptor.ToolAdaptor.java
/** * Run the tool. A command needs to be constructed, the same as you would if * you were running it from the command line. * /*w ww .ja v a2 s . c o m*/ * @return return the process which was created by running the tool. * @throws ToifException */ public java.io.File runTool() throws ToifException { ProcessBuilder process = null; java.io.File file = null; final String[] command = getCommands(); synchronized (this) { StringBuilder sb = new StringBuilder(); for (String cmd : command) { sb.append(cmd).append(" "); } } process = new ProcessBuilder(command); // DISABLED Nicing Windows. It seems that the cmd is dodgy and // occasionally loses the path that we set in the environment, // and it certainly does not like having absolute paths to // executables (at least ones with spaces). // Put the executable directory in path // if(SystemUtils.IS_OS_WINDOWS && execDir != null) // { // Map<String,String> env = process.environment(); // String envPath = env.get("PATH"); // if(envPath != null) // { // envPath = execDir.toString() + ";" + envPath; // } // else // { // envPath = execDir.toString(); // } // System.err.println("SETTING PATH: " + envPath); // env.put("PATH", envPath); // } // This doesn't work without spawning a bat or shell wrapper // // Extra path information // java.io.File paths = options.getPaths(); // if(paths != null) // { // Map<String,String> env = process.environment(); // String envPath = env.get("PATH"); // if(envPath != null) // { // envPath = paths + ";" + envPath; // } // else // { // envPath = paths.toString(); // } // System.err.println("SETTING PATH: " + envPath); // env.put("PATH", envPath); // } if (workingDirectory != null) { process.directory(workingDirectory); } java.io.File outputDirectory = options.getOutputDirectory(); outputDirectory.mkdirs(); file = null; if (adaptorImpl.getAdaptorName().equals("Splint")) { file = new java.io.File(outputDirectory, options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName()); java.io.File file2 = new java.io.File(outputDirectory, options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName()); java.io.File tmp = null; try { tmp = java.io.File.createTempFile("splint", ".tmp"); } catch (IOException e) { LOG.error("", e); throw new ToifException(); } if (tmp != null) { tmp.deleteOnExit(); process.redirectOutput(tmp); } process.redirectError(file2); } // if (adaptorImpl.getAdaptorName().equals("Cppcheck")) // { // file = new java.io.File(options.getOutputDirectory(), // options.getInputFile().getName() + "." + // adaptorImpl.getRuntoolName()); // java.io.File file2 = new java.io.File(options.getOutputDirectory(), // options.getInputFile().getName() + "-err." // + adaptorImpl.getRuntoolName()); // // process.redirectOutput(file2); // process.redirectError(file); // } else { file = new java.io.File(outputDirectory, options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName()); java.io.File file2 = new java.io.File(outputDirectory, options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName()); process.redirectOutput(file); process.redirectError(file2); } try { Process p = process.start(); p.waitFor(); // Check the exit value to ensure that process did not fail // except splint, splint is stupid and is always non-zero String name = adaptorImpl.getAdaptorName(); if ((p.exitValue() != 0) && (!"Splint".equals(name))) { int status = p.exitValue(); final String msg = "Adaptor process failure detected for '" + name + "': status=" + status + " " + options.getAdaptor().toString(); LOG.error(msg); throw new ToifException(msg); } return file; } catch (final IOException | InterruptedException e) { final String msg = options.getAdaptor().toString() + ": Could not write to output. " + e; LOG.error(msg); throw new ToifException(e); } }
From source file:org.apache.asterix.aql.translator.AqlTranslator.java
private void handlePregelixStatement(AqlMetadataProvider metadataProvider, Statement stmt, IHyracksClientConnection hcc) throws AsterixException, Exception { RunStatement pregelixStmt = (RunStatement) stmt; boolean bActiveTxn = true; String dataverseNameFrom = getActiveDataverse(pregelixStmt.getDataverseNameFrom()); String dataverseNameTo = getActiveDataverse(pregelixStmt.getDataverseNameTo()); String datasetNameFrom = pregelixStmt.getDatasetNameFrom().getValue(); String datasetNameTo = pregelixStmt.getDatasetNameTo().getValue(); if (dataverseNameFrom != dataverseNameTo) { throw new AlgebricksException("Pregelix statements across different dataverses are not supported."); }//w w w . ja v a 2s . com MetadataTransactionContext mdTxnCtx = MetadataManager.INSTANCE.beginTransaction(); metadataProvider.setMetadataTxnContext(mdTxnCtx); MetadataLockManager.INSTANCE.pregelixBegin(dataverseNameFrom, datasetNameFrom, datasetNameTo); try { // construct input paths Index fromIndex = null; List<Index> indexes = MetadataManager.INSTANCE.getDatasetIndexes(mdTxnCtx, dataverseNameFrom, pregelixStmt.getDatasetNameFrom().getValue()); for (Index ind : indexes) { if (ind.isPrimaryIndex()) fromIndex = ind; } if (fromIndex == null) { throw new AlgebricksException("Tried to access non-existing dataset: " + datasetNameFrom); } Dataset datasetFrom = MetadataManager.INSTANCE.getDataset(mdTxnCtx, dataverseNameFrom, datasetNameFrom); IFileSplitProvider fromSplits = metadataProvider.splitProviderAndPartitionConstraintsForDataset( dataverseNameFrom, datasetNameFrom, fromIndex.getIndexName(), datasetFrom.getDatasetDetails().isTemp()).first; StringBuilder fromSplitsPaths = new StringBuilder(); for (FileSplit f : fromSplits.getFileSplits()) { fromSplitsPaths .append("asterix://" + f.getNodeName() + f.getLocalFile().getFile().getAbsolutePath()); fromSplitsPaths.append(","); } fromSplitsPaths.setLength(fromSplitsPaths.length() - 1); // Construct output paths Index toIndex = null; indexes = MetadataManager.INSTANCE.getDatasetIndexes(mdTxnCtx, dataverseNameTo, pregelixStmt.getDatasetNameTo().getValue()); for (Index ind : indexes) { if (ind.isPrimaryIndex()) toIndex = ind; } if (toIndex == null) { throw new AlgebricksException("Tried to access non-existing dataset: " + datasetNameTo); } Dataset datasetTo = MetadataManager.INSTANCE.getDataset(mdTxnCtx, dataverseNameTo, datasetNameTo); IFileSplitProvider toSplits = metadataProvider.splitProviderAndPartitionConstraintsForDataset( dataverseNameTo, datasetNameTo, toIndex.getIndexName(), datasetTo.getDatasetDetails().isTemp()).first; StringBuilder toSplitsPaths = new StringBuilder(); for (FileSplit f : toSplits.getFileSplits()) { toSplitsPaths.append("asterix://" + f.getNodeName() + f.getLocalFile().getFile().getAbsolutePath()); toSplitsPaths.append(","); } toSplitsPaths.setLength(toSplitsPaths.length() - 1); try { Dataset toDataset = MetadataManager.INSTANCE.getDataset(mdTxnCtx, dataverseNameTo, datasetNameTo); DropStatement dropStmt = new DropStatement(new Identifier(dataverseNameTo), pregelixStmt.getDatasetNameTo(), true); this.handleDatasetDropStatement(metadataProvider, dropStmt, hcc); IDatasetDetailsDecl idd = new InternalDetailsDecl(toIndex.getKeyFieldNames(), false, null, toDataset.getDatasetDetails().isTemp()); DatasetDecl createToDataset = new DatasetDecl(new Identifier(dataverseNameTo), pregelixStmt.getDatasetNameTo(), new Identifier(toDataset.getItemTypeName()), new Identifier(toDataset.getNodeGroupName()), toDataset.getCompactionPolicy(), toDataset.getCompactionPolicyProperties(), toDataset.getHints(), toDataset.getDatasetType(), idd, false); this.handleCreateDatasetStatement(metadataProvider, createToDataset, hcc); } catch (Exception e) { e.printStackTrace(); throw new AlgebricksException("Error cleaning the result dataset. This should not happen."); } // Flush source dataset flushDataset(hcc, metadataProvider, mdTxnCtx, dataverseNameFrom, datasetNameFrom, fromIndex.getIndexName()); // call Pregelix String pregelix_home = System.getenv("PREGELIX_HOME"); if (pregelix_home == null) { throw new AlgebricksException("PREGELIX_HOME is not defined!"); } // construct command ArrayList<String> cmd = new ArrayList<String>(); cmd.add("bin/pregelix"); cmd.add(pregelixStmt.getParameters().get(0)); // jar cmd.add(pregelixStmt.getParameters().get(1)); // class for (String s : pregelixStmt.getParameters().get(2).split(" ")) { cmd.add(s); } cmd.add("-inputpaths"); cmd.add(fromSplitsPaths.toString()); cmd.add("-outputpath"); cmd.add(toSplitsPaths.toString()); StringBuilder command = new StringBuilder(); for (String s : cmd) { command.append(s); command.append(" "); } LOGGER.info("Running Pregelix Command: " + command.toString()); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(new File(pregelix_home)); pb.redirectErrorStream(true); MetadataManager.INSTANCE.commitTransaction(mdTxnCtx); bActiveTxn = false; Process pr = pb.start(); int resultState = 0; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); if (line.contains("job finished")) { resultState = 1; } if (line.contains("Exception") || line.contains("Error")) { if (line.contains("Connection refused")) { throw new AlgebricksException( "The connection to your Pregelix cluster was refused. Is it running? Is the port in the query correct?"); } if (line.contains("Could not find or load main class")) { throw new AlgebricksException( "The main class of your Pregelix query was not found. Is the path to your .jar file correct?"); } if (line.contains("ClassNotFoundException")) { throw new AlgebricksException( "The vertex class of your Pregelix query was not found. Does it exist? Is the spelling correct?"); } if (line.contains("HyracksException")) { throw new AlgebricksException( "Something went wrong executing your Pregelix Job (HyracksException). Check the configuration of STORAGE_BUFFERCACHE_PAGESIZE and STORAGE_MEMORYCOMPONENT_PAGESIZE." + "It must match the one of Asterix. You can use managix describe -admin to find out the right configuration. " + "Check also if your datatypes in Pregelix and Asterix are matching."); } throw new AlgebricksException( "Something went wrong executing your Pregelix Job. Perhaps the Pregelix cluster needs to be restartet. " + "Check the following things: Are the datatypes of Asterix and Pregelix matching? " + "Is the server configuration correct (node names, buffer sizes, framesize)? Check the logfiles for more details."); } } pr.waitFor(); in.close(); if (resultState != 1) { throw new AlgebricksException( "Something went wrong executing your Pregelix Job. Perhaps the Pregelix cluster needs to be restartet. " + "Check the following things: Are the datatypes of Asterix and Pregelix matching? " + "Is the server configuration correct (node names, buffer sizes, framesize)? Check the logfiles for more details."); } } catch (Exception e) { if (bActiveTxn) { abort(e, e, mdTxnCtx); } throw e; } finally { MetadataLockManager.INSTANCE.pregelixEnd(dataverseNameFrom, datasetNameFrom, datasetNameTo); } }