Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

In this page you can find the example usage for java.io File getCanonicalPath.

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:net.sf.jsignpdf.verify.Verifier.java

/**
 * @param args/*from w w w.  jav a 2 s .  c om*/
 */
public static void main(String[] args) {

    // create the Options
    Option optHelp = new Option("h", "help", false, "print this message");
    // Option optVersion = new Option("v", "version", false,
    // "print version info");
    Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files");
    optCerts.setArgName("certificates");
    Option optPasswd = new Option("p", "password", true, "set password for opening PDF");
    optPasswd.setArgName("password");
    Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder");
    optExtract.setArgName("folder");
    Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java");
    Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore");
    Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name");
    optKsType.setArgName("keystore_type");
    Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file");
    optKsFile.setArgName("file");
    Option optKsPass = new Option("kp", "keystore-password", true,
            "password for keystore file (look on -kf option)");
    optKsPass.setArgName("password");
    Option optFailFast = new Option("ff", "fail-fast", false,
            "flag which sets the Verifier to exit with error code on the first validation failure");

    final Options options = new Options();
    options.addOption(optHelp);
    // options.addOption(optVersion);
    options.addOption(optCerts);
    options.addOption(optPasswd);
    options.addOption(optExtract);
    options.addOption(optListKs);
    options.addOption(optListCert);
    options.addOption(optKsType);
    options.addOption(optKsFile);
    options.addOption(optKsPass);
    options.addOption(optFailFast);

    CommandLine line = null;
    try {
        // create the command line parser
        CommandLineParser parser = new PosixParser();
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Illegal command used: " + exp.getMessage());
        System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM);
    }

    final boolean failFast = line.hasOption("ff");
    final String[] tmpArgs = line.getArgs();
    if (line.hasOption("h") || args == null || args.length == 0) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]",
                "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null,
                true);
    } else if (line.hasOption("lk")) {
        // list keystores
        for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
            System.out.println(tmpKsType);
        }
    } else if (line.hasOption("lc")) {
        // list certificate aliases in the keystore
        for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"))) {
            System.out.println(tmpCert);
        }
    } else {
        final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"));
        tmpLogic.setFailFast(failFast);

        if (line.hasOption("c")) {
            String tmpCertFiles = line.getOptionValue("c");
            for (String tmpCFile : tmpCertFiles.split(";")) {
                tmpLogic.addX509CertFile(tmpCFile);
            }
        }
        byte[] tmpPasswd = null;
        if (line.hasOption("p")) {
            tmpPasswd = line.getOptionValue("p").getBytes();
        }
        String tmpExtractDir = null;
        if (line.hasOption("e")) {
            tmpExtractDir = new File(line.getOptionValue("e")).getPath();
        }

        int exitCode = 0;

        for (String tmpFilePath : tmpArgs) {
            int exitCodeForFile = 0;
            System.out.println("Verifying " + tmpFilePath);
            final File tmpFile = new File(tmpFilePath);
            if (!tmpFile.canRead()) {
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE;
                System.err.println("Couln't read the file. Check the path and permissions.");
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            }
            final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd);
            if (tmpResult.getException() != null) {
                tmpResult.getException().printStackTrace();
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM;
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            } else {
                System.out.println("Total revisions: " + tmpResult.getTotalRevisions());
                for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) {
                    System.out.println(tmpSigVer.toString());
                    if (tmpExtractDir != null) {
                        try {
                            File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_"
                                    + tmpSigVer.getRevision() + ".pdf");
                            System.out.println("Extracting to " + tmpExFile.getCanonicalPath());
                            FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath());

                            InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd,
                                    tmpSigVer.getName());
                            IOUtils.copy(tmpIS, tmpFOS);
                            tmpIS.close();
                            tmpFOS.close();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        }
                    }
                }
                exitCodeForFile = tmpResult.getVerificationResultCode();
                if (failFast && SignatureVerification.isError(exitCodeForFile)) {
                    System.exit(exitCodeForFile);
                }
            }
            exitCode = Math.max(exitCode, exitCodeForFile);
        }
        if (exitCode != 0 && tmpArgs.length > 1) {
            System.exit(SignatureVerification.isError(exitCode)
                    ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR
                    : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING);
        } else {
            System.exit(exitCode);
        }
    }
}

From source file:de.prozesskraft.ptest.Compare.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*  w  ww  . j  a va2 s .co m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oref = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against")
            //            .isRequired()
            .create("ref");

    Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription(
            "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref")
            //            .isRequired()
            .create("exam");

    Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file")
            //            .isRequired()
            .create("result");

    Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription(
            "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements")
            //            .isRequired()
            .create("summary");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no")
            //            .isRequired()
            .create("md5");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oref);
    options.addOption(oexam);
    options.addOption(oresult);
    options.addOption(osummary);
    options.addOption(omd5);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("compare", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.err.println("web:     " + web);
        System.err.println("author: " + author);
        System.err.println("version:" + version);
        System.err.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String result = "";
    boolean md5 = false;
    String ref = null;
    String exam = null;

    if (!(commandline.hasOption("ref"))) {
        System.err.println("option -ref is mandatory");
        error = true;
    } else {
        ref = commandline.getOptionValue("ref");
    }

    if (!(commandline.hasOption("exam"))) {
        java.io.File refFile = new java.io.File(ref).getCanonicalFile();
        java.io.File examFile = refFile.getParentFile();
        exam = examFile.getCanonicalPath();

        System.err.println("setting default: -exam=" + exam);
    } else {
        exam = commandline.getOptionValue("exam");
    }

    if (error) {
        exiter();
    }

    if (!(commandline.hasOption("result"))) {
        System.err.println("setting default: -result=result.txt");
        result = "result.txt";
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default: -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // einlesen der referenzdaten
    java.io.File refPath = new java.io.File(ref);

    Dir refDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (refPath.exists() && refPath.isDirectory()) {
        refDir.setBasepath(refPath.getCanonicalPath());
        refDir.genFingerprint(0f, true, new ArrayList<String>());
        refDir.setRespectMd5Recursive(md5);
        System.err.println("-ref is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (refPath.exists()) {
        refDir.setInfilexml(refPath.getCanonicalPath());
        System.err.println("-ref is a fingerprint");
        try {
            refDir.readXml();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refDir.setRespectMd5Recursive(md5);
    } else if (!refPath.exists()) {
        System.err.println("-ref does not exist! " + refPath.getAbsolutePath());
        exiter();
    }

    // einlesen der prueflingsdaten
    java.io.File examPath = new java.io.File(exam);

    Dir examDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (examPath.exists() && examPath.isDirectory()) {
        examDir.setBasepath(examPath.getCanonicalPath());
        examDir.genFingerprint(0f, true, new ArrayList<String>());
        examDir.setRespectMd5Recursive(md5);
        System.err.println("-exam is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (examPath.exists()) {
        examDir.setInfilexml(examPath.getCanonicalPath());
        System.err.println("-exam is a fingerprint");
        try {
            examDir.readXml();
        } catch (JAXBException e) {
            System.err.println("error while reading xml");
            e.printStackTrace();
        }
        examDir.setRespectMd5Recursive(md5);
    } else if (!examPath.exists()) {
        System.err.println("-exam does not exist! " + examPath.getAbsolutePath());
        exiter();
    }

    // durchfuehren des vergleichs
    refDir.runCheck(examDir);

    //      if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive())
    if (refDir.isMatchSuccessfullRecursive()) {
        System.out.println("SUCCESS");
    } else {
        System.out.println("FAILED");
    }

    // printen der csv-ergebnis-tabelle
    if (commandline.hasOption("summary")) {
        if (commandline.getOptionValue("summary").equals("error")) {
            System.err.println("the results of the reference are crucial for result FAILED|SUCCESS");
            System.err.println(refDir.sprintSummaryAsCsv("error"));
            System.err.println(examDir.sprintSummaryAsCsv("error"));
        } else if (commandline.getOptionValue("summary").equals("all")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
        } else if (commandline.getOptionValue("summary").equals("debug")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
            // printen des loggings
            System.err.println("------ logging of reference --------");
            System.err.println(refDir.getLogAsStringRecursive());
            System.err.println("------ logging of examinee --------");
            System.err.println(examDir.getLogAsStringRecursive());
        } else {
            System.err.println("for option -summary you only may use all|error");
            exiter();
        }
    }

}

From source file:ar.com.qbe.siniestros.model.utils.MimeMagic.Magic.java

/**
 * DOCUMENT ME!//  w  w  w. j a  v  a2  s  .c  o m
 *
 * @param args DOCUMENT ME!
 */
public static void main(String[] args) {
    try {
        if (args.length == 0) {
            System.err.println("usage: test <file>");
            System.exit(1);
            ;
        }
        File f = new File(args[0]);

        if (f.exists()) {
            MagicMatch match = Magic.getMagicMatch(f, true, false);

            System.out.println("filename: " + args[0]);
            printMagicMatch(System.out, match, "");
        } else {
            System.err.println("file '" + f.getCanonicalPath() + "' not found");
        }
    } catch (MagicMatchNotFoundException e) {
        System.out.println("no match found");
    } catch (Exception e) {
        System.err.println("error: " + e);
        e.printStackTrace(System.err);
    }
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {//from  w w w  . j  a  va 2  s.  c om
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

From source file:com.cloudera.recordbreaker.schemadict.SchemaDictionary.java

public static void main(String argv[]) throws IOException {
    boolean shouldDump = false;
    boolean shouldAdd = false;
    File avroDataFile = null;//  w  w  w. ja  v  a  2  s. c o m
    String dictMessage = null;

    CommandLine cmd = null;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("d", false, "Dump contents of schema dictionary");
    options.addOption("a", true, "Add datafile to new schema dictionary element");
    options.addOption("m", true, "Add comment message as part of new schema dictionary element");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException e) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        shouldDump = true;
    }

    if (cmd.hasOption("a")) {
        avroDataFile = new File(cmd.getOptionValue("a")).getCanonicalFile();
    }
    if (cmd.hasOption("m")) {
        dictMessage = cmd.getOptionValue("m");
        if (cmd.hasOption("a")) {
            shouldAdd = true;
        }
    }
    if ((!shouldAdd) && (cmd.hasOption("a") || cmd.hasOption("m"))) {
        System.err.println("Must indicate -a AND -m to add new schema dictionary item");
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length == 0) {
        System.err.println("No schema dictionary path provided.");
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    File dictionaryDir = new File(argArray[0]).getCanonicalFile();
    SchemaDictionary dict = new SchemaDictionary(dictionaryDir);

    if (shouldAdd) {
        dict.addDictionaryElt(avroDataFile, dictMessage);
    }

    if (shouldDump) {
        int counter = 1;
        for (SchemaDictionaryEntry entry : dict.contents()) {
            System.err.println("" + counter + ".  " + entry.getInfo());
            System.err.println(entry.getSchema());
            System.err.println();
            counter++;
        }
        int numItems = counter - 1;
        System.err.println(
                "Dictionary at " + dictionaryDir.getCanonicalPath() + " has " + numItems + " item(s).");
    }
}

From source file:de.prozesskraft.ptest.Launch.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from  ww w .  j ava2s. c  o m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ospl = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory with sample input data")
            //            .isRequired()
            .create("spl");

    Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory, default: .] directory where the test will be performed")
            //            .isRequired()
            .create("instancedir");

    Option ocall = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory, default: random call in spl-directory] file with call-string")
            //            .isRequired()
            .create("call");

    Option oaltapp = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription(
                    "[optional] alternative app. this String replaces the first line of the .call-file.")
            //            .isRequired()
            .create("altapp");

    Option oaddopt = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] add an option to the call.")
            //            .isRequired()
            .create("addopt");

    Option onolaunch = new Option("nolaunch",
            "only create instance directory, copy all spl files, but do NOT launch the process");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ospl);
    options.addOption(oinstancedir);
    options.addOption(ocall);
    options.addOption(oaltapp);
    options.addOption(oaddopt);
    options.addOption(onolaunch);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("launch", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String spl = null;
    String instancedir = null;
    String call = null;
    String altapp = null;
    ArrayList<String> addopt = new ArrayList<String>();

    // spl initialisieren
    if (commandline.hasOption("spl")) {
        spl = commandline.getOptionValue("spl");
    } else {
        System.err.println("option -spl is mandatory");
        error = true;
    }

    // instancedir initialisieren
    if (commandline.hasOption("instancedir")) {
        instancedir = commandline.getOptionValue("instancedir");
    } else {
        instancedir = System.getProperty("user.dir");
    }

    // call initialisieren
    if (commandline.hasOption("call")) {
        call = commandline.getOptionValue("call");
    }

    // altapp initialisieren
    if (commandline.hasOption("altapp")) {
        altapp = commandline.getOptionValue("altapp");
    }

    // addopt initialisieren
    if (commandline.hasOption("addopt")) {
        for (String actString : commandline.getOptionValues("addopt")) {
            addopt.add(actString);
        }
    }

    // wenn fehler, dann exit
    if (error) {
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // das erste spl-objekt geben lassen
    Spl actSpl = new Splset(spl).getSpl().get(0);

    // den call, result und altapp ueberschreiben
    actSpl.setName("default");

    if (call != null) {
        actSpl.setCall(new java.io.File(call));
    }
    if (actSpl.getCall() == null) {
        System.err.println("error: no call information found");
        System.exit(1);
    }

    if (altapp != null) {
        actSpl.setAltapp(altapp);
    }

    if (addopt.size() > 0) {
        actSpl.setAddopt(addopt);
    }

    actSpl.setResult(null);

    // das instancedir erstellen
    java.io.File actSplInstanceDir = new java.io.File(instancedir);
    System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath());
    actSplInstanceDir.mkdirs();

    // Inputdaten in das InstanceDir exportieren
    actSpl.exportInput(actSplInstanceDir);

    // exit, wenn --nolaunch
    if (commandline.hasOption("nolaunch")) {
        System.err.println("info: exiting, because of -nolaunch");
        System.exit(0);
    }

    // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht)
    String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log";
    String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt";
    String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt";
    String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid";

    // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl
    // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden
    // syscall ersetzt die zeichensequenz wieder zurueck in ein " "
    ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList();
    ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>();
    for (String actString : callFuerSyscall) {
        callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%"));
    }

    try {
        // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten
        // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory'
        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(ini.get("apps", "pkraft-syscall").split(" ")));

        // die sonstigen argumente hinzufuegen
        processSyscallWithArgs.add("-call");
        processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen));
        //         processSyscallWithArgs.add("\""+call+"\"");
        processSyscallWithArgs.add("-stdout");
        processSyscallWithArgs.add(AbsStdout);
        processSyscallWithArgs.add("-stderr");
        processSyscallWithArgs.add(AbsStderr);
        processSyscallWithArgs.add("-pid");
        processSyscallWithArgs.add(AbsPid);
        processSyscallWithArgs.add("-mylog");
        processSyscallWithArgs.add(AbsLogSyscallWrapper);
        processSyscallWithArgs.add("-maxrun");
        processSyscallWithArgs.add("" + 3000);

        // erstellen prozessbuilder
        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        // erweitern des PATHs um den prozesseigenen path
        //         Map<String,String> env = pb.environment();
        //         String path = env.get("PATH");
        //         log("debug", "$PATH="+path);
        //         path = this.parent.getAbsPath()+":"+path;
        //         env.put("PATH", path);
        //         log("info", "path: "+path);

        // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll)
        java.io.File directory = new java.io.File(instancedir);
        System.err.println("info: setting execution directory to: " + directory.getCanonicalPath());
        pb.directory(directory);

        // zum debuggen ein paar ausgaben
        //         java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt");
        //         p1.waitFor();
        //         java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt");
        //         p2.waitFor();
        //         java.lang.Process pro = Runtime.getRuntime().exec("nautilus");
        //         java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()]));
        //         p3.waitFor();

        System.err.println("info: calling: " + pb.command());

        // starten des prozesses
        java.lang.Process sysproc = pb.start();

        // einfangen der stdout- und stderr des subprozesses
        InputStream is_stdout = sysproc.getInputStream();
        InputStream is_stderr = sysproc.getErrorStream();

        // Send your InputStream to an InputStreamReader:
        InputStreamReader isr_stdout = new InputStreamReader(is_stdout);
        InputStreamReader isr_stderr = new InputStreamReader(is_stderr);

        // That needs to go to a BufferedReader:
        BufferedReader br_stdout = new BufferedReader(isr_stdout);
        BufferedReader br_stderr = new BufferedReader(isr_stderr);

        //         // oeffnen der OutputStreams zu den Ausgabedateien
        //         FileWriter fw_stdout = new FileWriter(sStdout);
        //         FileWriter fw_stderr = new FileWriter(sStderr);

        // zeilenweise in die files schreiben
        String line_out = new String();
        String line_err = new String();

        while (br_stdout.readLine() != null) {
        }

        //         while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null))
        //         {
        //            if (!(line_out == null))
        //            {
        //               System.out.println(line_out);
        //               System.out.flush();
        //            }
        //            if (!(line_err == null))
        //            {
        //               System.err.println(line_err);
        //               System.err.flush();
        //            }
        //         }

        int exitValue = sysproc.waitFor();

        //         fw_stdout.close();
        //         fw_stderr.close();

        System.err.println("exitvalue: " + exitValue);

        sysproc.destroy();

        System.exit(exitValue);

        //         alternativer aufruf
        //         java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " "));

        //         log("info", "call executed. pid="+sysproc.hashCode());

        // wait 2 seconds for becoming the pid-file visible
        //         Thread.sleep(2000);

        //         int exitValue = sysproc.waitFor();

        //         // der prozess soll bis laengstens
        //         if(exitValue != 0)
        //         {
        //            System.err.println("error: call returned a value indicating an error: "+exitValue);
        //         }
        //         else
        //         {
        //            System.err.println("info: call returned value: "+exitValue);
        //         }

        //         System.err.println("info: "+new Date().toString());
        //         System.err.println("info: bye");
        //
        //         sysproc.destroy();
        //
        //         System.exit(sysproc.exitValue());
    } catch (Exception e2) {
        System.err.println("error: " + e2.getMessage());
        System.exit(1);
    }

}

From source file:fi.iki.elonen.SimpleWebServer.java

/**
 * Starts as a standalone file server and waits for Enter.
 *//*w w  w  .j av  a2s  . c  o m*/
public static void main(String[] args) {
    // Defaults
    int port = 8080;

    String host = null; // bind to all interfaces by default
    List<File> rootDirs = new ArrayList<File>();
    boolean quiet = false;
    String cors = null;
    Map<String, String> options = new HashMap<String, String>();

    // Parse command-line, with short and long versions of the options.
    for (int i = 0; i < args.length; ++i) {
        if ("-h".equalsIgnoreCase(args[i]) || "--host".equalsIgnoreCase(args[i])) {
            host = args[i + 1];
        } else if ("-p".equalsIgnoreCase(args[i]) || "--port".equalsIgnoreCase(args[i])) {
            if (args[i + 1].equals("public")) {
                port = PUBLIC;
            } else if (args[i + 1].equals("private")) {
                port = PRIVATE;
            } else {
                port = Integer.parseInt(args[i + 1]);
            }
        } else if ("-q".equalsIgnoreCase(args[i]) || "--quiet".equalsIgnoreCase(args[i])) {
            quiet = true;
        } else if ("-d".equalsIgnoreCase(args[i]) || "--dir".equalsIgnoreCase(args[i])) {
            rootDirs.add(new File(args[i + 1]).getAbsoluteFile());
        } else if (args[i].startsWith("--cors")) {
            cors = "*";
            int equalIdx = args[i].indexOf('=');
            if (equalIdx > 0) {
                cors = args[i].substring(equalIdx + 1);
            }
        } else if ("--licence".equalsIgnoreCase(args[i])) {
            System.out.println(SimpleWebServer.LICENCE + "\n");
        } else if (args[i].startsWith("-X:")) {
            int dot = args[i].indexOf('=');
            if (dot > 0) {
                String name = args[i].substring(0, dot);
                String value = args[i].substring(dot + 1, args[i].length());
                options.put(name, value);
            }
        }
    }

    if (rootDirs.isEmpty()) {
        rootDirs.add(new File(".").getAbsoluteFile());
    }
    options.put("host", host);
    options.put("port", "" + port);
    options.put("quiet", String.valueOf(quiet));
    StringBuilder sb = new StringBuilder();
    for (File dir : rootDirs) {
        if (sb.length() > 0) {
            sb.append(":");
        }
        try {
            sb.append(dir.getCanonicalPath());
        } catch (IOException ignored) {
        }
    }
    options.put("home", sb.toString());
    ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class);
    for (WebServerPluginInfo info : serviceLoader) {
        String[] mimeTypes = info.getMimeTypes();
        for (String mime : mimeTypes) {
            String[] indexFiles = info.getIndexFilesForMimeType(mime);
            if (!quiet) {
                System.out.print("# Found plugin for Mime type: \"" + mime + "\"");
                if (indexFiles != null) {
                    System.out.print(" (serving index files: ");
                    for (String indexFile : indexFiles) {
                        System.out.print(indexFile + " ");
                    }
                }
                System.out.println(").");
            }
            registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options);
        }
    }
    ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet, cors));
}

From source file:de.prozesskraft.pkraft.Perlcode.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from ww w .j a  v  a2 s.  c o m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("perlcode", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:de.prozesskraft.pkraft.Startinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from   www .  j  a va2 s.  co m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/"
            + "../etc/pkraft-startinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option obasedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[optional, default .] base directory where instance shourd run.")
            //            .isRequired()
            .create("basedir");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[optional] definition file of the process you want to start an instance from.")
            //            .isRequired()
            .create("definition");

    Option onostart = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] oppresses the start of the instance. (only create the process-instance)")
            //            .isRequired()
            .create("nostart");

    Option opdomain = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] domain of the process (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pdomain");

    Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pname");

    Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription(
            "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)")
            //            .isRequired()
            .create("pversion");

    Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg()
            .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.")
            //            .isRequired()
            .create("commitfile");

    Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg()
            .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE")
            //            .isRequired()
            .create("commitvariable");

    Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription(
            "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitfiledummy");

    Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription(
            "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.")
            //            .isRequired()
            .create("commitvariabledummy");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(obasedir);
    options.addOption(odefinition);
    options.addOption(onostart);
    options.addOption(opname);
    options.addOption(opversion);
    options.addOption(ocommitfile);
    options.addOption(ocommitvariable);
    options.addOption(ocommitfiledummy);
    options.addOption(ocommitvariabledummy);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("startinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition")) && (!(commandline.hasOption("pname"))
            || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion"))
            || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) {
        System.err.println("you must not use option -definition with -pversion or -pname or -pdomain");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    Process p1 = new Process();
    String pathToDefinition = "";

    if (commandline.hasOption("definition")) {
        pathToDefinition = commandline.getOptionValue("definition");
    } else if (commandline.hasOption("pname") && commandline.hasOption("pversion")
            && commandline.hasOption("pdomain")) {
        pathToDefinition.replaceAll("/+$", "");
        pathToDefinition = ini.get("process", "domain-installation-directory") + "/"
                + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/"
                + commandline.getOptionValue("pversion") + "/process.xml";
    } else {
        System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory");
        exiter();
    }

    // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert
    java.io.File xmlDefinition = new java.io.File(pathToDefinition);
    if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) {
        System.err.println("process definition does not exist: " + pathToDefinition);
        exiter();
    }

    p1.setInfilexml(xmlDefinition.getCanonicalPath());
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e1) {
        System.err.println(e1.getMessage());
    }

    // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will
    // root-verzeichnis erstellen
    if (commandline.hasOption("basedir")) {
        p2.setBaseDir(commandline.getOptionValue("basedir"));
    }

    p2.makeRootdir();

    // den pfad fuers binary setzen
    p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    // step, an den die commits gehen, soll 'root' sein.
    Step stepRoot = p2.getRootStep();

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfile")) {
        for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) {
            String[] parts = actOptionCommitfile.split("=");
            File userFile = new File();

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfile " + actOptionCommitfile);
                exiter();
            }

            // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
            // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
            for (Commit actCommit : stepRoot.getCommit()) {
                // alle files des aktuellen commits
                for (File actFile : actCommit.getFile()) {
                    if (actFile.getKey().equals(userFile.getKey())) {
                        // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                        if (actFile.getGlob() != null) {
                            // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                            if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) {
                                File newFile = actFile.clone();
                                newFile.setGlob(userFile.getGlob());
                                System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                        + newFile.getKey() + "=" + newFile.getGlob() + ")");
                                actCommit.addFile(newFile);
                                break;
                            } else {
                                System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " "
                                        + actFile.getKey() + "-files into commit " + actCommit.getName());
                                exiter();
                            }
                        }
                        // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                        else {
                            actFile.setGlob(userFile.getGlob());
                            actFile.setGlobdir(p2.getBaseDir());
                            System.err.println("entering file into commit '" + actCommit.getName() + "' ("
                                    + actFile.getKey() + "=" + actFile.getGlob() + ")");
                            break;
                        }
                    }
                }
            }
        }
    }

    // committen von files (ueber einen glob)
    if (commandline.hasOption("commitfiledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitFiledummy = new Commit();
        commitFiledummy.setName("fileDummy");
        stepRoot.addCommit(commitFiledummy);

        for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) {
            String[] parts = actOptionCommitfiledummy.split("=");
            File userFile = new File();
            commitFiledummy.addFile(userFile);

            if (parts.length == 1) {
                userFile.setKey(new java.io.File(parts[0]).getName());
                userFile.setGlob(parts[0]);
            } else if (parts.length == 2) {
                userFile.setKey(parts[0]);
                userFile.setGlob(parts[1]);
            } else {
                System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy);
                exiter();
            }
            userFile.setGlobdir(p2.getBaseDir());
            System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' ("
                    + userFile.getKey() + "=" + userFile.getGlob() + ")");
        }
    }

    if (commandline.hasOption("commitvariable")) {
        for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) {
            if (actOptionCommitvariable.matches(".+=.+")) {
                String[] parts = actOptionCommitvariable.split("=");
                Variable userVariable = new Variable();

                if (parts.length == 1) {
                    userVariable.setKey("default");
                    userVariable.setValue(parts[0]);
                } else if (parts.length == 2) {
                    userVariable.setKey(parts[0]);
                    userVariable.setValue(parts[1]);
                } else {
                    System.err.println("error in option -commitvariable");
                    exiter();
                }
                //                  commit.addVariable(variable);

                // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden
                // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen
                for (Commit actCommit : stepRoot.getCommit()) {
                    // alle files des aktuellen commits
                    for (Variable actVariable : actCommit.getVariable()) {
                        if (actVariable.getKey().equals(userVariable.getKey())) {
                            // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden
                            if (actVariable.getGlob() != null) {
                                // wenn die maximale erlaubte anzahl noch nicht erreicht ist
                                if (actCommit.getVariable(actVariable.getKey()).size() < actVariable
                                        .getMaxoccur()) {
                                    Variable newVariable = actVariable.clone();
                                    newVariable.setValue(userVariable.getValue());
                                    System.err.println("entering variable into commit '" + actCommit.getName()
                                            + "' (" + newVariable.getKey() + "=" + newVariable.getValue()
                                            + ")");
                                    actCommit.addVariable(newVariable);
                                    break;
                                } else {
                                    System.err.println("fatal: you only may commit " + actVariable.getMaxoccur()
                                            + " " + actVariable.getKey() + "-variable(s) into commit "
                                            + actCommit.getName());
                                    exiter();
                                }
                            }
                            // ansonsten das bereits vorhandene file im commit mit den daten befuellen
                            else {
                                actVariable.setValue(userVariable.getValue());
                                System.err.println("entering variable into commit '" + actCommit.getName()
                                        + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")");
                                break;
                            }
                        }
                    }
                }
            } else {
                System.err.println("-commitvariable " + actOptionCommitvariable
                        + " does not match pattern \"NAME=VALUE\".");
                exiter();
            }

        }
    }

    if (commandline.hasOption("commitvariabledummy")) {
        // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit
        Commit commitVariabledummy = new Commit();
        commitVariabledummy.setName("variableDummy");
        stepRoot.addCommit(commitVariabledummy);

        for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) {
            String[] parts = actOptionCommitvariabledummy.split("=");
            Variable userVariable = new Variable();
            commitVariabledummy.addVariable(userVariable);

            if (parts.length == 1) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[0]);
            } else if (parts.length == 2) {
                userVariable.setKey(parts[0]);
                userVariable.setValue(parts[1]);
            } else {
                System.err.println("error in option -commitvariabledummy");
                exiter();
            }

            System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' ("
                    + userVariable.getKey() + "=" + userVariable.getValue() + ")");
        }
    }

    //      if (commandline.hasOption("basedir"))
    //      {
    //         p2.setBaseDir(commandline.getOptionValue("basedir"));
    //      }

    //         commit.doIt();
    stepRoot.commit();

    // root-verzeichnis erstellen
    p2.makeRootdir();

    // den pfad fuers binary setzen
    //      p2.setOutfilebinary(p2.getRootdir() + "/process.pmb");

    System.err.println("info: writing process instance " + p2.getOutfilebinary());

    // binary schreiben
    p2.writeBinary();

    try {
        Thread.sleep(1500, 0);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //         Runtime.getRuntime().exec("process-manager -help");

    // starten nur, falls es nicht abgewaehlt wurde
    if (!commandline.hasOption("nostart")) {
        System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary());
        String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary();
        System.err.println("calling: " + aufrufString);

        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(aufrufString.split(" ")));

        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        //      ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary());
        //      Map<String,String> env = pb.environment();
        //      String path = env.get("PATH");
        //      System.out.println("PATH: "+path);
        //      
        java.lang.Process p = pb.start();
        System.err.println("pid: " + p.hashCode());
    } else {
        System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary());
    }

}

From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java

/**
 * Main application to be run when this CygnusApplication is invoked. The only differences with the original one
 * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in
 * the command line./*from w w w.  ja  v a  2  s. c  o  m*/
 * @param args
 */
public static void main(String[] args) {
    try {
        Options options = new Options();

        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a conf file");
        option.setRequired(true);
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        option = new Option("p", "mgmt-if-port", true, "the management interface port");
        option.setRequired(false);
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);

        File configurationFile = new File(commandLine.getOptionValue('f'));
        String agentName = commandLine.getOptionValue('n');
        boolean reload = !commandLine.hasOption("no-reload-conf");

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("flume-ng agent", options, true);
            return;
        } // if

        int mgmtIfPort = 8081; // default value

        if (commandLine.hasOption('p')) {
            mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue();
        } // if

        // the following is to ensure that by default the agent will fail on startup if the file does not exist

        if (!configurationFile.exists()) {
            // if command line invocation, then need to fail fast
            if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) {
                String path = configurationFile.getPath();

                try {
                    path = configurationFile.getCanonicalPath();
                } catch (IOException ex) {
                    logger.error("Failed to read canonical path for file: " + path, ex);
                } // try catch

                throw new ParseException("The specified configuration file does not exist: " + path);
            } // if
        } // if

        List<LifecycleAware> components = Lists.newArrayList();
        CygnusApplication application;

        if (reload) {
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, 30);
            components.add(configurationProvider);
            application = new CygnusApplication(components, mgmtIfPort);
            eventBus.register(application);
        } else {
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication(mgmtIfPort);
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        application.start();

        final CygnusApplication appReference = application;
        Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") {
            @Override
            public void run() {
                appReference.stop();
            } // run
        });
    } catch (Exception e) {
        logger.error("A fatal error occurred while running. Exception follows.", e);
    } // try catch
}