public int setupAndExecute()

in taverna-commandline-common/src/main/java/org/apache/taverna/commandline/CommandLineTool.java [169:329]


	public int setupAndExecute() throws InputMismatchException, InvalidOptionException,
			CMException, OpenDataflowException, ReaderException, IOException, ValidationException,
			ReadInputException, InvalidWorkflowException, RunProfileException,
			InvalidRunIdException, RunStateException, InvalidExecutionIdException, DatabaseConfigurationException {
				
		if (commandLineOptions.askedForHelp()) {
			commandLineOptions.displayHelp();
			return 0;
		}
			 setupDatabase(commandLineOptions);
			 setupJarCache();
			 
			 
			if (commandLineOptions.getWorkflow() != null) {
				
				/*
				 * Initialise Credential Manager and SSL stuff quite early as
				 * parsing and validating the workflow may require it
				 */
				String credentialManagerDirPath = commandLineOptions.getCredentialManagerDir();

				/*
				 * If credentialManagerDirPath is null, the Credential Manager
				 * will be initialized from the default location in
				 * <TAVERNA_HOME>/security somewhere inside user's home
				 * directory. This should not be used when running command line
				 * tool on a server and the Credential Manager dir path should
				 * always be passed in as we do not want to store the security
				 * files in user's home directory on the server (we do not even
				 * know which user the command line tool will be running as).
				 */
				if (credentialManagerDirPath != null) {
					credentialManager.setConfigurationDirectoryPath(Paths.get(
							credentialManagerDirPath));
				}

				// Initialise the SSL stuff - set the SSLSocketFactory
				// to use Taverna's Keystore and Truststore.
				credentialManager.initializeSSL();

				URL workflowURL = readWorkflowURL(commandLineOptions.getWorkflow());

				workflowBundle = workflowBundleIO.readBundle(workflowURL, null);

				logger.debug("Read the wf bundle");

				validateWorkflowBundle(workflowBundle);
				logger.debug("Validated the wf bundle");


				Set<ExecutionEnvironment> executionEnvironments = runService
						.getExecutionEnvironments();

				ExecutionEnvironment executionEnvironment = null;

				/*
				 * Find the right execution environment, e.g. local execution
				 * with the correct reference service based on command line
				 * options
				 */
				while (executionEnvironments.iterator().hasNext()) {
					// TODO Choose the right one
					// take the fist one for now
					executionEnvironment = executionEnvironments.iterator().next();
					break;
				}

				logger.debug("Got the execution environment");

				InputsHandler inputsHandler = new InputsHandler();
				Map<String, InputWorkflowPort> portMap = new HashMap<String, InputWorkflowPort>();

				Workflow workflow = workflowBundle.getMainWorkflow();

				for (InputWorkflowPort port : workflow.getInputPorts()) {
					portMap.put(port.getName(), port);
				}
				inputsHandler.checkProvidedInputs(portMap, commandLineOptions);
				logger.debug("Checked inputs");

				Bundle inputs = inputsHandler.registerInputs(portMap, commandLineOptions);
				logger.debug("Registered inputs");

				RunProfile runProfile = new RunProfile(executionEnvironment, workflowBundle, inputs);
			
				String runId = runService.createRun(runProfile);

				runService.start(runId);
				logger.debug("Started wf run");

				WorkflowReport report = runService.getWorkflowReport(runId);

				while (!workflowFinished(report)) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						System.err.println("Interrupted while waiting for workflow to finish");
						return 1;
					}
				}

				NamedSet<OutputWorkflowPort> workflowOutputPorts = workflow.getOutputPorts();
				if (!workflowOutputPorts.isEmpty()) {
					File outputDir = null;

					if (commandLineOptions.saveResultsToDirectory()) {
						outputDir = determineOutputDir(commandLineOptions, workflowBundle.getName());
						outputDir.mkdirs();
					}

					Path outputs = DataBundles.getOutputs(runService.getDataBundle(runId));

					if (outputDir != null) {
						SaveResultsHandler saveResultsHandler = new SaveResultsHandler(outputDir);

						for (OutputWorkflowPort outputWorkflowPort : workflowOutputPorts) {
							String workflowOutputPortName = outputWorkflowPort.getName();
							Path output = DataBundles.getPort(outputs, workflowOutputPortName);
							if (!DataBundles.isMissing(output)) {
								saveResultsHandler.saveResultsForPort(workflowOutputPortName, output);
							}
						}
					}
				}
				if (commandLineOptions.getSaveResultsToBundle() != null) {
					Path bundlePath = Paths.get(commandLineOptions.getSaveResultsToBundle());
					Bundle bundle = runService.getDataBundle(runId);
					if (! safeIsSameFile(bundlePath, bundle.getSource())) {
						// This can happen with 
						// -bundle same.zip -inputbundle same.zip
						// in which case we don't want to save to another file
						runService.save(runId, bundlePath);
					}
					System.out.println("Data Bundle saved to: " + bundlePath.toAbsolutePath());
				}
				runService.close(runId);

				if (report.getState().equals(State.FAILED)) {
					System.out.println("Workflow failed - see report below.");
					System.out.println(report);
				} else if (report.getState().equals(State.COMPLETED)) {
					System.out.println("Workflow completed.");
				}

			
		}

		// wait until user hits CTRL-C before exiting
		if (commandLineOptions.getStartDatabaseOnly()) {
			// FIXME: need to do this more gracefully.
			while (true) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					return 0;
				}
			}
		}

		return 0;
	}