List of usage examples for java.io File canExecute
public boolean canExecute()
From source file:net.sf.sze.service.impl.converter.ZeugnisCreatorServiceImpl.java
@Override public void afterPropertiesSet() { LOG.info("PDF-Erstellung aktiv = {}", Boolean.valueOf(createPdf)); if (createPdf) { if ("SERVICE".equals(converter)) { final File ooExecutable = new File(ooExecutableString); if (!ooExecutable.canExecute()) { throw new IllegalStateException( ooExecutable.getAbsolutePath() + "kann nicht ausgefhrt werden."); }/*ww w. ja va 2 s . com*/ File userEnv = null; if (ooEnv) { userEnv = new File("./ooenv"); if (!userEnv.exists() && !userEnv.mkdirs()) { throw new IllegalStateException(userEnv.getAbsolutePath() + " kann nicht angelegt werden."); } } oo2pdfConverter = new OO2PdfConverterJodImpl(ooExecutable, userEnv, ooPort); } else if ("UNO".equals(converter)) { oo2pdfConverter = new OO2PdfConverterUnoImpl(); } else { throw new IllegalArgumentException("Unknown converter " + converter + "."); } oo2pdfConverter.init(); LOG.info("Init PDF-Creation mit {}", converter); } odtOutputBaseDir = new File(odtOutputBaseDirAsString); pdfPrintOutputBaseDir = new File(pdfPrintOutputBaseDirAsString); pdfScreenOutputBaseDir = new File(pdfScreenOutputBaseDirAsString); }
From source file:io.fabric8.maven.plugin.mojo.infra.AbstractInstallMojo.java
private File installAndConfigureBinary(File binDirectory, String binName, String binVersionUrl, String binDownloadUrlFormat) throws MojoExecutionException { File binaryFile = null; validateDir(binDirectory);/*from w ww .j a va 2s. co m*/ String fileName = binName; if (Platform.windows.equals(getPlatform())) { fileName += ".exe"; } binaryFile = new File(binDirectory, fileName); if (!binaryFile.exists() || !binaryFile.isFile() || !binaryFile.canExecute()) { downloadExecutable(binVersionUrl, binDownloadUrlFormat, binDirectory, binaryFile, binName); } // lets check if the binary directory is on the path if (!ProcessUtil.folderIsOnPath(log, binDirectory)) { updateStartupScriptInstructions(binDirectory, binName); } return binaryFile; }
From source file:jenkins.plugins.tanaguru.TanaguruRunnerBuilder.java
@Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { // This is where you 'build' the project. File contextDir = new File(getDescriptor().getTanaguruCliPath()); if (!contextDir.exists()) { listener.getLogger().println("Le chemin vers le contexte d'excution est incorrect"); return false; }//from w ww .j av a 2s .com File scriptFile = new File(getDescriptor().getTanaguruCliPath() + "/" + TG_SCRIPT_NAME); if (!scriptFile.canExecute()) { listener.getLogger().println("Le script n'est pas excutable"); return false; } String spaceEscapedScenarioName = scenarioName.replace(' ', '_'); TanaguruRunner tanaguruRunner = new TanaguruRunner(TG_SCRIPT_NAME, spaceEscapedScenarioName, scenario, build.getNumber(), refAndLevel.split(";")[0], refAndLevel.split(";")[1], contextDir, getDescriptor().getFirefoxPath(), getDescriptor().getDisplayPort(), StringUtils.isBlank(xmxValue) ? DEFAULT_XMX_VALUE : xmxValue, listener, getDescriptor().getIsDebug()); tanaguruRunner.callTanaguruService(); writeResultToWorkspace(tanaguruRunner, build.getWorkspace()); linkToTanaguruWebapp(tanaguruRunner, spaceEscapedScenarioName, scenario, contextDir, build.getProject().getDisplayName()); setBuildStatus(build, tanaguruRunner); return true; }
From source file:org.waarp.commandexec.server.LocalExecServerHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { answered = false;/* ww w . ja va 2s .c o m*/ String request = msg; // Generate and write a response. String response; response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result; ExecuteWatchdog watchdog = null; try { if (request.length() == 0) { // No command response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result; } else { String[] args = request.split(" "); int cpt = 0; long tempDelay; try { tempDelay = Long.parseLong(args[0]); cpt++; } catch (NumberFormatException e) { tempDelay = delay; } if (tempDelay < 0) { // Shutdown Order isShutdown = true; logger.warn("Shutdown order received"); response = LocalExecDefaultResult.ShutdownOnGoing.status + " " + LocalExecDefaultResult.ShutdownOnGoing.result; Thread thread = new GGLEThreadShutdown(factory); thread.start(); return; } String binary = args[cpt++]; File exec = new File(binary); if (exec.isAbsolute()) { // If true file, is it executable if (!exec.canExecute()) { logger.error("Exec command is not executable: " + request); response = LocalExecDefaultResult.NotExecutable.status + " " + LocalExecDefaultResult.NotExecutable.result; return; } } // Create command with parameters CommandLine commandLine = new CommandLine(binary); for (; cpt < args.length; cpt++) { commandLine.addArgument(args[cpt]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); ByteArrayOutputStream outputStream; outputStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); if (tempDelay > 0) { // If delay (max time), then setup Watchdog watchdog = new ExecuteWatchdog(tempDelay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { // Execute the command status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(LocalExecDefaultResult.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } catch (IOException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } else { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error( "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } try { pumpStreamHandler.stop(); } catch (IOException e3) { } if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); response = LocalExecDefaultResult.TimeOutExecution.status + " " + LocalExecDefaultResult.TimeOutExecution.result; try { outputStream.close(); } catch (IOException e2) { } } else { try { response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name()); } catch (UnsupportedEncodingException e) { response = status + " " + outputStream.toString(); } try { outputStream.close(); } catch (IOException e2) { } } } } finally { // We do not need to write a ByteBuf here. // We know the encoder inserted at LocalExecInitializer will do the // conversion. ctx.channel().writeAndFlush(response + "\n"); answered = true; if (watchdog != null) { watchdog.stop(); } logger.info("End of Command: " + request + " : " + response); ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n"); } }
From source file:com.thoughtworks.cruise.util.command.CommandLine.java
private void addExecutable(List<String> args, String executable) { File file = new File(workingDir, executable); if (file.exists() && file.canExecute()) { args.add(file.getAbsolutePath()); } else {/*from www. jav a2 s. co m*/ args.add(executable); } }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
public GrassProcesses() { super(Text.text("Geographic Resources Analysis Support System"), "grass", GrassProcesses.class); String grass = GeoServerExtensions.getProperty("GRASS"); String grass_mod = GeoServerExtensions.getProperty("GRASS_MODULES"); if (grass != null) { LOGGER.info("defined GRASS=" + grass); EXEC = grass;//w ww .j a v a 2s .co m } else if (SYSTEM == Env.LINUX) { EXEC = "/usr/local/bin/grass70"; LOGGER.info("default GRASS=" + EXEC); } else if (SYSTEM == Env.MAC) { EXEC = "/Applications/GRASS-7.0.app/Contents/MacOS/grass70"; LOGGER.info("default GRASS=" + EXEC); } else if (SYSTEM == Env.WINDOWS) { if (new File("C:\\Program Files (x86)").exists()) { EXEC = "C:\\Program Files (x86)\\GRASS GIS 7.0.0\\grass70.bat"; } else { EXEC = "C:\\Program Files\\GRASS GIS 7.0.0\\grass70.bat"; } LOGGER.info("default GRASS=" + EXEC); } else { LOGGER.warning("GRASS default executable unavailable for '" + System.getProperty("os.name") + "'. Please use GRASS environmental variable, context parameter or system property"); EXEC = null; } if (grass_mod != null) { LOGGER.info("defined GRASS_MODULES=" + grass_mod); BIN = grass_mod; } else if (SYSTEM == Env.LINUX) { BIN = "/usr/lib/grass70/bin"; LOGGER.info("default GRASS_MODULES=" + BIN); } else if (SYSTEM == Env.MAC) { BIN = "/Applications/GRASS-7.0.app/Contents/MacOS/bin"; LOGGER.info("default GRASS_MODULES=" + BIN); } else if (SYSTEM == Env.WINDOWS) { if (new File("C:\\Program Files (x86)").exists()) { BIN = "C:\\Program Files (x86)\\GRASS GIS 7.0.0\\bin"; } else { BIN = "C:\\Program Files\\GRASS GIS 7.0.0\\bin"; } LOGGER.info("default GRASS_MODULES=" + BIN); } else { LOGGER.warning("GRASS modules unavailable for '" + System.getProperty("os.name") + "'. Please use GRASS_MODULES environmental variable, context parameter or system property"); BIN = null; } if (EXEC != null) { File exec = new File(EXEC); if (!exec.exists()) { LOGGER.warning(EXEC + " does not exist"); EXEC = null; } if (!exec.canExecute()) { LOGGER.warning(EXEC + " not executable"); EXEC = null; } } if (BIN != null) { File exec = new File(BIN); if (!exec.exists()) { LOGGER.warning(BIN + " does not exist"); BIN = null; } } }
From source file:org.eclipse.acute.OmnisharpStreamConnectionProvider.java
/** * * @param commandLine/*from w w w. j a v a 2 s . co m*/ * @return the command-line to run the server, or null is expected resources are not found * @throws IOException */ protected @Nullable String getDefaultCommandLine(File serverPath) throws IOException { File serverFileUrl = null; if (Platform.OS_WIN32.equals(Platform.getOS())) { serverFileUrl = new File(serverPath, "server/Omnisharp.exe"); //$NON-NLS-1$ } else { serverFileUrl = new File(serverPath, "run"); //$NON-NLS-1$ } if (serverFileUrl == null || !serverFileUrl.exists()) { AcutePlugin.logError(NLS.bind(Messages.omnisharpStreamConnection_serverNotFoundError, serverPath)); return null; } else if (!serverFileUrl.canExecute()) { AcutePlugin .logError(NLS.bind(Messages.omnisharpStreamConnection_serverNotExecutableError, serverFileUrl)); // return value anyway } return serverFileUrl.getAbsolutePath() + " -stdio -lsp"; //$NON-NLS-1$ }
From source file:com.ikanow.infinit.e.application.handlers.polls.LogstashTestRequestPollHandler.java
@Override public void performPoll() { if (null == LOGSTASH_DIRECTORY) { // (static memory not yet initialized) try {/*from www .ja v a 2 s . c o m*/ Thread.sleep(1000); // (extend the sleep time a bit) } catch (Exception e) { } return; } // 1] Check - does logstash exist on this server: File logstashBinary = new File(LOGSTASH_BINARY); if (!logstashBinary.canExecute()) { try { Thread.sleep(10000); // (extend the sleep time a bit) } catch (Exception e) { } return; } // 2] (Unlike harvester, _don't_ grab an application token, you can run this on as many servers as you want) // 3] Setup if (null == _logHarvesterQ) { _logHarvesterQ = new MongoQueue(DbManager.getIngest().getLogHarvesterQ().getDB().getName(), DbManager.getIngest().getLogHarvesterQ().getName()); } if (null == _testOutputTemplate) { try { File testOutputTemplate = new File(LOGSTASH_TEST_OUTPUT_TEMPLATE); InputStream inStream = null; try { inStream = new FileInputStream(testOutputTemplate); _testOutputTemplate = IOUtils.toString(inStream); } catch (Exception e) {// abandon ship! return; } finally { inStream.close(); } } catch (Exception e) {// abandon ship! //DEBUG //e.printStackTrace(); return; } } //TESTED // 4] Check if any new requests have been made: BasicDBObject queueQuery = new BasicDBObject("logstash", new BasicDBObject(DbManager.exists_, true)); DBObject nextElement = _logHarvesterQ.pop(queueQuery); while (nextElement != null) { //DEBUG //System.out.println("FOUND: " + nextElement.toString()); TestLogstashExtractorPojo testInfo = TestLogstashExtractorPojo.fromDb(nextElement, TestLogstashExtractorPojo.class); if ((null == testInfo.maxDocs) || (null == testInfo.logstash.config) || (null == testInfo.isAdmin) || (null == testInfo.sourceKey)) { TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Internal Logic Error. Missing one of: maxDocs, isAdmin, sourceKey, logstash.config"; _logHarvesterQ.push(testErr.toDb()); return; } //TESTED // Validate/tranform the configuration: StringBuffer errMessage = new StringBuffer(); String logstashConfig = LogstashConfigUtils.validateLogstashInput(testInfo.sourceKey, testInfo.logstash.config, errMessage, testInfo.isAdmin); if (null == logstashConfig) { // Validation error... TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Validation error: " + errMessage.toString(); _logHarvesterQ.push(testErr.toDb()); return; } //TESTED // Replacement for #LOGSTASH{host} - currently only replacement supported (+ #IKANOW{} in main code) try { logstashConfig = logstashConfig.replace("#LOGSTASH{host}", java.net.InetAddress.getLocalHost().getHostName()); } catch (Exception e) { logstashConfig = logstashConfig.replace("#LOGSTASH{host}", "localhost.localdomain"); } //TESTED String outputConf = _testOutputTemplate.replace("_XXX_COLLECTION_XXX_", testInfo._id.toString()); //TESTED String sinceDbPath = LOGSTASH_WD + ".sincedb_" + testInfo._id.toString(); String conf = logstashConfig.replace("_XXX_DOTSINCEDB_XXX_", sinceDbPath) + outputConf.replace("_XXX_SOURCEKEY_XXX_", testInfo.sourceKey); boolean allWorked = false; Process logstashProcess = null; try { // 1] Create the process ArrayList<String> args = new ArrayList<String>(4); args.addAll(Arrays.asList(LOGSTASH_BINARY, "-e", conf)); if (0 == testInfo.maxDocs) { args.add("-t"); // test mode, must faster } //TESTED if ((null != testInfo.logstash.testDebugOutput) && testInfo.logstash.testDebugOutput) { args.add("--debug"); } else { args.add("--verbose"); } ProcessBuilder logstashProcessBuilder = new ProcessBuilder(args); logstashProcessBuilder = logstashProcessBuilder.directory(new File(LOGSTASH_WD)) .redirectErrorStream(true); logstashProcessBuilder.environment().put("JAVA_OPTS", ""); //DEBUG //System.out.println("STARTING: " + ArrayUtils.toString(logstashProcessBuilder.command().toArray())); // 2] Kick off the process logstashProcess = logstashProcessBuilder.start(); StringWriter outputAndError = new StringWriter(); OutputCollector outAndErrorStream = new OutputCollector(logstashProcess.getInputStream(), new PrintWriter(outputAndError)); outAndErrorStream.start(); final int toWait_s = 240; boolean exited = false; // 3] Check the output collection for records int errorVal = 0; long priorCount = 0L; int priorLogCount = 0; int timeOfLastLoggingChange = 0; int timeOfLastDocCountChange = 0; String reasonForExit = ""; int inactivityTimeout_s = 10; // (default) if (null != testInfo.logstash.testInactivityTimeout_secs) { inactivityTimeout_s = testInfo.logstash.testInactivityTimeout_secs; } for (int i = 0; i < toWait_s; i += 5) { try { Thread.sleep(5000); } catch (Exception e) { } long count = DbManager.getCollection("ingest", testInfo._id.toString()).count(); // 3.1] Do we have all the records (or is the number staying static) //DEBUG //System.out.println("FOUND: " + count + " VS " + priorCount + " , " + priorPriorCount); // 3.1a] All done? if ((count >= testInfo.maxDocs) && (count > 0)) { allWorked = true; break; } //TESTED // 3.1b] If not, has anything changes? if (priorCount != count) { timeOfLastDocCountChange = i; } if (priorLogCount != outAndErrorStream.getLines()) { timeOfLastLoggingChange = i; } // 3.1c] Check for inactivity if ((timeOfLastDocCountChange > 0) && (i - timeOfLastDocCountChange) >= inactivityTimeout_s) { // Delay between events: treat as success allWorked = true; break; } //TESTED if ((0 == count) && outAndErrorStream.getPipelineStarted() && ((timeOfLastLoggingChange > 0) && (i - timeOfLastLoggingChange) >= inactivityTimeout_s)) { // Delay between log messages after pipeline started, no documents, treat as failure //DEBUG //System.out.println("LOG LINES! " + i + " NUM = " + outAndErrorStream.getLines()); errorVal = 1; reasonForExit = "No records received and logging inactive.\n"; break; } //TESTED // 3.2] Has the process exited unexpectedly? try { errorVal = logstashProcess.exitValue(); reasonForExit = "Logstash process exited with error: " + errorVal + ".\n"; exited = true; //DEBUG //System.out.println("GOT EXIT VALUE: " + errorVal); break; } //TESTED catch (Exception e) { } // that's OK we're just still going is all... priorCount = count; priorLogCount = outAndErrorStream.getLines(); } //(end loop while waiting for job to complete) // 4] If the process is still running then kill it if (!exited) { //DEBUG //System.out.println("EXITED WITHOUT FINISHING"); logstashProcess.destroy(); } //TESTED // 5] Things to do when the job is done: (worked or not) // Send a message to the harvester outAndErrorStream.join(); // (if we're here then must have closed the process, wait for it to die) TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; if ((testInfo.maxDocs > 0) || (0 != errorVal)) { testErr.error = reasonForExit + outputAndError.toString(); // (note this is capped at well below the BSON limit in the thread below) } else { // maxDocs==0 (ie pre-publish test) AND no error returned testErr.error = null; } _logHarvesterQ.push(testErr.toDb()); //TESTED } catch (Exception e) { //DEBUG //e.printStackTrace(); TestLogstashExtractorPojo testErr = new TestLogstashExtractorPojo(); testErr._id = testInfo._id; testErr.error = "Internal Logic Error: " + e.getMessage(); _logHarvesterQ.push(testErr.toDb()); } //TOTEST finally { // If we created a sincedb path then remove it: try { new File(sinceDbPath).delete(); } catch (Exception e) { } // (don't care if it fails) if (!allWorked) { // (otherwise up to the harvester to remove these) try { DbManager.getCollection("ingest", testInfo._id.toString()).drop(); } catch (Exception e) { } // doesn't matter if this errors } try { // Really really want to make sure the process isn't running if (null != logstashProcess) { logstashProcess.destroy(); } } catch (Exception e) { } catch (Error ee) { } } //TESTED // (If we actually processed an element, then try again immediate) nextElement = _logHarvesterQ.pop(queueQuery); } }
From source file:jenkins.plugins.asqatasun.AsqatasunRunnerBuilder.java
@Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { // This is where you 'build' the project. File contextDir = new File(getDescriptor().getAsqatasunRunnerPath()); if (!contextDir.exists()) { listener.getLogger().println("Le chemin vers le contexte d'excution est incorrect " + getDescriptor().getAsqatasunRunnerPath()); return false; }/* w w w . ja v a 2s. c o m*/ File scriptFile = new File(getDescriptor().getAsqatasunRunnerPath() + "/" + TG_SCRIPT_NAME); if (!scriptFile.canExecute()) { listener.getLogger().println("Le script n'est pas excutable"); return false; } String spaceEscapedScenarioName = scenarioName.replace(' ', '_'); AsqatasunRunner asqatasunRunner = new AsqatasunRunner(TG_SCRIPT_NAME, spaceEscapedScenarioName, scenario, build.getNumber(), refAndLevel.split(";")[0], refAndLevel.split(";")[1], contextDir, getDescriptor().getFirefoxPath(), getDescriptor().getDisplayPort(), StringUtils.isBlank(xmxValue) ? DEFAULT_XMX_VALUE : xmxValue, listener, getDescriptor().getIsDebug()); listener.getLogger().print("call runner service"); asqatasunRunner.callService(); listener.getLogger().print("Analysis terminated. Now Linking To Workspace"); writeResultToWorkspace(asqatasunRunner, build.getWorkspace()); linkToWebapp(asqatasunRunner, spaceEscapedScenarioName, scenario, contextDir, listener.getLogger(), getDescriptor().getIsDebug(), build.getProject().getDisplayName()); setBuildStatus(build, asqatasunRunner); return true; }
From source file:org.italiangrid.storm.webdav.authz.vomap.VOMapDetailServiceBuilder.java
private void directorySanityChecks(File directory) { if (!directory.exists()) throw new IllegalArgumentException( "VOMS map files configuration directory does not exists: " + directory.getAbsolutePath()); if (!directory.isDirectory()) throw new IllegalArgumentException( "VOMS map files configuration directory is not a directory: " + directory.getAbsolutePath()); if (!directory.canRead()) throw new IllegalArgumentException( "VOMS map files configuration directory is not readable: " + directory.getAbsolutePath()); if (!directory.canExecute()) throw new IllegalArgumentException( "VOMS map files configuration directory is not traversable: " + directory.getAbsolutePath()); }