Example usage for java.lang Process Process

List of usage examples for java.lang Process Process

Introduction

In this page you can find the example usage for java.lang Process Process.

Prototype

public Process() 

Source Link

Document

Default constructor for Process.

Usage

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

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

    /*----------------------------
      get options from ini-file// w w w  .j  a  v a2  s  . c o  m
    ----------------------------*/
    File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Checkconsistency.class) + "/"
            + "../etc/pkraft-checkconsistency.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 odefinition = OptionBuilder.withArgName("definition").hasArg()
            .withDescription("[mandatory] process model in xml format.")
            //            .isRequired()
            .create("definition");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);

    /*----------------------------
      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@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.out.println("option -definition 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();

    p1.setInfilexml(commandline.getOptionValue("definition"));
    Process p2;
    try {
        p2 = p1.readXml();

        if (p2.isProcessConsistent()) {
            System.out.println("process structure is consistent.");
        } else {
            System.out.println("process structure is NOT consistent.");
        }

        p2.printLog();

    } catch (JAXBException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

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

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

    //      try//  ww w . ja v  a2s  . 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(Createmap.class) + "/" + "../etc/pkraft-createmap.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");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: process.dot] file for generated map.")
            //            .isRequired()
            .create("output");

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

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

    options.addOption(ohelp);
    options.addOption(ooutput);
    options.addOption(odefinition);

    /*----------------------------
      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("createmap", options);
        System.out.println("");
        System.out.println("author: " + author + " | version: " + version + " | 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 output = new java.io.File(commandline.getOptionValue("output"));

    if (output.exists()) {
        System.err.println("warn: already exists: " + output.getCanonicalPath());
        exiter();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));

    // dummy process
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // den wrapper process generieren
    ArrayList<String> dot = p2.getProcessAsDotGraph();

    // dot file rausschreiben
    writeFile.writeFile(output, dot);
}

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

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

    //      try/*  w w w . j a va2  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(Wrap.class) + "/" + "../etc/pkraft-wrap.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 ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: .] file for generated wrapper process.")
            //            .isRequired()
            .create("output");

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

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

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

    /*----------------------------
      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("wrap", 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 output = new java.io.File(commandline.getOptionValue("output"));

    if (output.exists()) {
        System.err.println("warn: already exists: " + output.getCanonicalPath());
        exiter();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));

    // dummy process
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // den wrapper process generieren
    Process p3 = p2.getProcessAsWrapper();
    p3.setOutfilexml(output.getAbsolutePath());

    // den neuen wrap-process rausschreiben
    p3.writeXml();
}

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

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

    /*----------------------------
      get options from ini-file/*from w w  w .  j av  a2s. co  m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Clone.class) + "/" + "../etc/pkraft-clone.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 oinstance = OptionBuilder.withArgName("File").hasArg()
            .withDescription("[mandatory] process you want to clone.")
            //            .isRequired()
            .create("instance");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional, default: <basedirOfInstance>] base directory you want to place the root directory of the clone. this directory must exist at call time.")
            //            .isRequired()
            .create("basedir");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(obasedir);

    /*----------------------------
      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("clone", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@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("instance"))) {
        System.err.println("option -instance 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
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);
    java.io.File fileBaseDir = null;

    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist.");
        exiter();
    }

    // testen ob eventuell vorhandene angaben basedir
    if (commandline.hasOption("basedir")) {
        fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("error: -basedir: directory does not exist");
            exiter();
        }
        if (!fileBaseDir.isDirectory()) {
            System.err.println("error: -basedir: is not a directory");
            exiter();
        }
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    Process process = p1.readBinary();

    // directories setzen, falls angegeben
    if (fileBaseDir != null) {
        process.setBaseDir(fileBaseDir.getCanonicalPath());
    }

    // den main-prozess ueber die static function klonen
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                cloneProcess(processInSubprocess, clonedProcess);
            }
        }
    }
}

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

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

    /*----------------------------
      get options from ini-file/*from   ww w  .j a v  a2  s  . c  om*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.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 oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] instance you want to merge another instance into.")
            //            .isRequired()
            .create("instance");

    Option oguest = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] this instance will be merged into -instance.")
            //            .isRequired()
            .create("guest");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.")
            //            .isRequired()
            .create("basedir");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oguest);
    options.addOption(obasedir);

    /*----------------------------
      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("merge", 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("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }
    if (!(commandline.hasOption("guest"))) {
        System.err.println("at least one option -guest 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
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);

    String[] pathToGuest = commandline.getOptionValues("guest");

    String baseDir = null;
    if (commandline.hasOption("basedir")) {
        java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath());
            exiter();
        } else if (!fileBaseDir.isDirectory()) {
            System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath());
            exiter();
        }
        baseDir = commandline.getOptionValue("basedir");
    }

    // ueberpruefen ob die process.pmb files vorhanden sind
    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }
    for (String pathGuest : pathToGuest) {
        java.io.File fileGuest = new java.io.File(pathGuest);

        // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
        if (!fileGuest.exists()) {
            System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath());
            exiter();
        }
    }

    // base - instance einlesen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    p1.setOutfilebinary(pathToInstance);
    Process p2 = p1.readBinary();

    // alle guests einlesen
    ArrayList<Process> alleGuests = new ArrayList<Process>();
    for (String actPathGuest : pathToGuest) {
        Process p30 = new Process();
        p30.setInfilebinary(actPathGuest);
        Process pGuest = p30.readBinary();

        // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind
        if (!p2.getName().equals(pGuest.getName())) {
            System.err.println("error: instances are not from the same type (-instance=" + p2.getName()
                    + " != -guest=" + pGuest.getName());
            exiter();
        }

        // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind
        if (!p2.getVersion().equals(pGuest.getVersion())) {
            System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!="
                    + pGuest.getVersion());
            exiter();
        }

        alleGuests.add(pGuest);
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p3 = new Process();
    p3.setInfilebinary(pathToInstance);
    Process process = p3.readBinary();

    // den main-prozess ueber die static function klonen
    // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess);
                // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir()
                        + "/process.pmb";
                System.err.println("info: calling: " + call2);

                try {
                    java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
                } catch (IOException e) {
                    System.err.println("error: " + e.getMessage());
                }
            }
        }
    }

    // alle dependent steps der zielinstanz einsammeln
    // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden
    Map<Step, String> dependentSteps = new HashMap<Step, String>();

    // alle guest prozesse merge durchfuehren
    for (Process actGuestProcess : alleGuests) {
        System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary());

        // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren
        for (Step actStep : actGuestProcess.getStep()) {
            if (actStep.isAFannedMultistep()) {
                System.err.println("info: merging from guest instance step " + actStep.getName());
                Step clonedStepForIntegrationInClonedProcess = actStep.clone();
                if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) {
                    System.err.println("info: merging step successfully.");
                    // die downstream steps vom merge-punkt merken
                    for (Step actStepToResetBecauseOfDependency : clonedProcess
                            .getStepDependent(actStep.getName())) {
                        dependentSteps.put(actStepToResetBecauseOfDependency, "dummy");
                    }

                    // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden
                    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                    if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null
                            && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) {
                        String call5 = ini.get("apps", "pradar-attend") + " -instance "
                                + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb";
                        System.err.println("info: calling: " + call5);
                        try {
                            java.lang.Process sysproc = Runtime.getRuntime().exec(call5);
                        } catch (IOException e) {
                            System.err.println("error: " + e.getMessage());
                        }
                    }
                } else {
                    System.err.println("error: merging step failed.");
                }
            } else {
                System.err.println("debug: because it's not a multistep, ignoring from guest instance step "
                        + actStep.getName());
            }
        }
    }

    // alle steps downstream der merge-positionen resetten
    for (Step actStep : dependentSteps.keySet()) {
        actStep.resetBecauseOfDependency();
    }

    // speichern der ergebnis instanz
    clonedProcess.writeBinary();

    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
    String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir()
            + "/process.pmb";
    System.err.println("info: calling: " + call2);

    try {
        java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
    } catch (IOException e) {
        System.err.println("error: " + e.getMessage());
    }

}

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

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

    //      try//from   w ww. j  ava 2s.  com
    //      {
    //         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.Commitit.java

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

    //      try/*from   w w  w .jav a  2 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
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Commitit.class) + "/" + "../etc/pkraft-commitit.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");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process instance file")
            //            .isRequired()
            .create("instance");

    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg()
            .withDescription("[optional, default: root] process step to commit to")
            //            .isRequired()
            .create("step");

    Option ofile = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[optional] this file will be committed as file. key will be set to 'default'")
            //            .isRequired()
            .create("file");

    Option okey = OptionBuilder.withArgName("KEY").hasArg()
            .withDescription(
                    "[optional, default: default] this string will be considered as the key for the commit.")
            //            .isRequired()
            .create("key");

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

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

    options.addOption(ohelp);
    options.addOption(oinstance);
    options.addOption(ostep);
    options.addOption(ofile);
    options.addOption(okey);
    options.addOption(ovariable);

    /*----------------------------
      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("commit", options);
        System.exit(0);
    }

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

    else if (!(commandline.hasOption("dir")) && !(commandline.hasOption("file"))
            && !(commandline.hasOption("varfile")) && !(commandline.hasOption("varname"))
            && !(commandline.hasOption("varvalue")) && !(commandline.hasOption("variable"))) {
        System.out.println(
                "at least one of these options needed. -dir -file -varfile -variable -varname -varvalue.");
        exiter();
    }

    else if ((commandline.hasOption("varname") && !(commandline.hasOption("varvalue")))
            || (!(commandline.hasOption("varname")) && commandline.hasOption("varvalue"))) {
        System.out.println("use options -varname and -varvalue only in combination with each other.");
        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
    ----------------------------*/

    // setzen des steps
    String stepname = "root";
    if (commandline.hasOption("step")) {
        stepname = commandline.getOptionValue("step");
    }

    // setzen des key
    String key = "default";
    if (commandline.hasOption("key")) {
        key = commandline.getOptionValue("key");
    }

    Process p1 = new Process();

    p1.setInfilebinary(commandline.getOptionValue("instance"));
    System.out.println("info: reading process instance " + commandline.getOptionValue("instance"));
    Process p2 = p1.readBinary();
    p2.setOutfilebinary(commandline.getOptionValue("instance"));

    // step ueber den namen heraussuchen
    Step step = p2.getStep(stepname);
    if (step == null) {
        System.err.println("step not found: " + stepname);
        exiter();
    }

    // den Commit 'by-process-commitit' heraussuchen oder einen neuen Commit dieses Namens erstellen
    Commit commit = step.getCommit("by-hand");
    if (commit == null) {
        commit = new Commit(step);
        commit.setName("by-process-commitit");
    }

    // committen
    if (commandline.hasOption("file")) {
        File file = new File();
        file.setKey(key);
        file.setGlob(commandline.getOptionValue("file"));
        commit.addFile(file);
        commit.doIt();
    }

    if (commandline.hasOption("variable")) {
        Variable variable = new Variable();
        variable.setKey(key);
        variable.setValue(commandline.getOptionValue("variable"));
        commit.addVariable(variable);
        commit.doIt();
    }

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

}

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

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

    /*----------------------------
      get options from ini-file/*  www.  j  a va 2 s  .c  om*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/"
            + "../etc/pkraft-waitinstance.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 oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'")
            //            .isRequired()
            .create("instance");

    Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.")
            //            .isRequired()
            .create("scandir");

    Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription(
            "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.")
            //            .isRequired()
            .create("maxrun");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oscandir);
    options.addOption(omaxrun);

    /*----------------------------
      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("waitinstance", 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
    ----------------------------*/
    Integer maxrun = new Integer(4320);
    String pathInstance = null;
    String pathScandir = null;

    // instance & scandir
    if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) {
        System.err.println("one of the options -instance/-scandir is mandatory");
        exiter();
    } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) {
        System.err.println("both options -instance/-scandir are not allowed");
        exiter();
    } else if (commandline.hasOption("instance")) {
        pathInstance = commandline.getOptionValue("instance");
    } else if (commandline.hasOption("scandir")) {
        pathScandir = commandline.getOptionValue("scandir");
    }

    // maxrun
    if (commandline.hasOption("maxrun")) {
        maxrun = new Integer(commandline.getOptionValue("maxrun"));
    }
    /*----------------------------
      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
    ----------------------------*/

    // scannen nach dem ersten process.pmb 
    if ((pathScandir != null) && (pathInstance == null)) {
        String[] allBinariesOfScanDir = getProcessBinaries(pathScandir);

        if (allBinariesOfScanDir.length == 0) {
            System.err.println("no instance (process.pmb) found in directory tree " + pathScandir);
            exiter();
        } else {
            pathInstance = allBinariesOfScanDir[0];
            System.err.println("found instance: " + pathInstance);
        }
    }

    // ueberpruefen ob instance file existiert
    java.io.File fileInstance = new java.io.File(pathInstance);

    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }

    if (!fileInstance.isFile()) {
        System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath());
        exiter();
    }

    // zeitpunkt wenn spaetestens beendet werden soll
    long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000);

    // logging
    System.err.println("waiting for instance: " + fileInstance.getAbsolutePath());
    System.err.println("checking its status every 5 minutes");
    System.err.println("now is: " + new Timestamp(startInMillis).toString());
    System.err.println("maxrun till: " + new Timestamp(runTill).toString());

    // instanz einlesen
    Process p1 = new Process();
    p1.setInfilebinary(fileInstance.getAbsolutePath());
    Process p2 = p1.readBinary();

    // schleife, die prozess einliest und ueberprueft ob er noch laeuft
    while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) {
        // logging
        System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus());

        // 5 minuten schlafen: 300000 millis
        try {
            Thread.sleep(300000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage)
        if (System.currentTimeMillis() > runTill) {
            System.err
                    .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis()));
            System.exit(2);
        }

        // den prozess frisch einlesen
        p2 = p1.readBinary();
    }

    System.err.println("exiting because instance status is: " + p2.getStatus());
    System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString());
    System.exit(0);

}

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

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

    //      try//from  w  ww. ja  v  a 2s .co m
    //      {
    //         if (args.length != 1)
    //         {
    //            System.out.println("Please specify Inputfile and Outputfile (prozessinstanz.lri)");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify procesdefinition.lrd and processinstance.lri\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Manager.class) + "/" + "../etc/pkraft-manager.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);
        exit = true;
    }

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

    /*----------------------------
      create argument options
    ----------------------------*/
    Option instance = OptionBuilder.withArgName("instance").hasArg()
            .withDescription("[mandatory] process instance file")
            //            .isRequired()
            .create("instance");

    Option stop = OptionBuilder.withArgName("stop")
            //            .hasArg()
            .withDescription("[optional] stops a running manager for given instance")
            //            .isRequired()
            .create("stop");

    Option kill = OptionBuilder.withArgName("kill")
            //            .hasArg()
            .withDescription("[optional] kills all applications that have been started by steps")
            //            .isRequired()
            .create("kill");

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

    options.addOption(help);
    options.addOption(v);
    options.addOption(instance);
    options.addOption(stop);
    options.addOption(kill);

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

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

    else if (line.hasOption("v")) {
        System.out.println("author:  info@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        exit = true;
        System.exit(0);
    }

    else if (!(line.hasOption("instance"))) {
        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()) {
        exit = true;
        System.exit(1);
    }

    /*----------------------------
      business logic
    ----------------------------*/

    Process actualProcess = null;
    try {

        Process p1 = new Process();

        // die dauer des loops festlegen. Dies soll kein standardwert sein, da sonst bei vielen subprozessen die Prozessorlast stark oszilliert
        // zwischen 12 und 17 sekunden
        //         Random rand = new Random(System.currentTimeMillis());
        //         int loop_period_seconds = rand.nextInt((17 - 12) + 1) + 12;
        //         System.err.println("loop period is randomly set to: "+loop_period_seconds);

        fileBinary = new java.io.File(line.getOptionValue("instance"));
        String pathBinary = "";

        if (fileBinary.exists()) {
            pathBinary = fileBinary.getAbsolutePath();
            System.err.println("file does exist: " + pathBinary);
        } else {
            System.err.println("file does not exist: " + fileBinary.getAbsolutePath());
            exiter();
        }

        if (line.hasOption("stop") || line.hasOption("kill")) {
            p1.setInfilebinary(pathBinary);
            Process p2 = p1.readBinary();
            p2.log("debug", "setting new manager-Id (0) to signal actual manager (" + p2.getManagerid()
                    + ") that he is no longer in charge ");
            System.err.println("info: stopping instance");
            System.err.println("debug: setting new manager-Id (0) to signal actual manager ("
                    + p2.getManagerid() + ") that he is no longer in charge ");
            p2.setManagerid(0);
            p2.run = false;
            p2.setOutfilebinary(pathBinary);

            p2.writeBinary();

            if (line.hasOption("kill")) {
                System.err.println("info: killing all steps of instance");
                String returnStringOfKills = p2.kill();
                System.err.println("info: killing returns: " + returnStringOfKills);
            }

            boolean pradar = (!(p2.isWrapper()));

            // pradar checkout
            if (pradar) {
                pradarAttend(p2.getRootdir() + "/process.pmb");
                //               pradarCheckout(p2.getId(), p2.getName(), "0");
            }

            exit = true;
            System.exit(0);
        }

        startZyklischerThread(0);

        // prozessinstanz einlesen
        p1.setInfilebinary(pathBinary);

        managerid = p1.genManagerid();

        Process p2;
        p2 = p1.readBinary();

        // beim aufruf des programms wird erstmal die instanz occupiert
        p2.setManagerid(managerid);

        System.err.println("debug: manager " + managerid + ": occupying instance.");
        p2.log("info", "manager " + managerid + ": occupying instance.");
        p2.log("debug", "manager " + managerid
                + ": setting new manager-id to signal other running managers that they are not longer needed.");

        p2.log("debug", "manager " + managerid + ": setting binary file for input to: " + pathBinary);
        //      System.out.println("setting binary file for input to: "+line.getOptionValue("instance"));

        p2.log("debug", "manager " + managerid + ": reading binary file: " + pathBinary);

        p2.setInfilebinary(pathBinary);
        p2.setOutfilebinary(pathBinary);
        p2.log("debug", "manager " + managerid + ": setting binary file for output: " + pathBinary);

        // instanz auf platte schreiben (um anderen managern zu signalisieren, dass sie nicht mehr gebraucht werden
        //      System.out.println("setting manager-id to: "+managerid);

        p2.log("debug", "manager " + managerid + ": writing process to binary file to occupy instance.");

        // wenn es kein wrapper-prozess ist, dann soll die komunikation mit pradar vom manager uebernommen werden
        boolean pradar = (!(p2.isWrapper()));

        System.err.println("debug: setting instance to run");
        p2.run = true;

        // pradar checkin
        if (pradar && p2.run && p2.touchInMillis == 0) {
            pradarAttend(p2.getRootdir() + "/process.pmb");
            //            p2.log("debug", "pradar-checkin id="+p2.getId()+", process="+p2.getName()+", processversion="+p2.getVersion()+", id2="+p2.getId2()+", parentid="+p2.getParentid()+", resource="+p2.getRootdir()+"/process.pmb");
            //            pradarCheckin(p2.getId(), p2.getName(), p2.getVersion(), p2.getId2(), p2.getParentid(), getPid(), p2.getRootdir()+"/process.pmb");
        }

        System.err.println("debug: writing binary");

        p2.writeBinary();

        // process weiter schubsen
        pushProcessAsFarAsPossible(pathBinary, false);

        //         try
        //         {
        //            // der thread soll so lange schlafen, wie die periode lang ist. die schlafdauer wird mit der anzahl multipliziert, wie oft das loadAverage zu hoch war (max 5)
        //            int faktorForPeriod = Math.min(10, p2.counterLoadAverageTooHigh + 1);
        //
        //            int secondsToSleep = loop_period_seconds * faktorForPeriod;
        //            System.err.println("debug: sleeping for " + secondsToSleep + " seconds");
        //            
        //            int millisecondsToSleep = secondsToSleep*1000;
        //            System.err.println("debug: sleeping for " + millisecondsToSleep + " milliseconds");
        //            
        //            Thread.sleep(millisecondsToSleep);
        //         }
        //         catch (InterruptedException e)
        //         {
        //            // TODO Auto-generated catch block
        //            e.printStackTrace();
        //
        //            // ausgabe in das debugLogFile
        //            exiterException(actualProcess.getOutfilebinary(), e);
        //         }
    } catch (Exception e) {
        if (actualProcess != null) {
            actualProcess.log("fatal", e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
            updateFile(actualProcess);
            e.printStackTrace();

            // ausgabe in das debugLogFile
            exiterException(actualProcess.getOutfilebinary(), e);

        }
        exit = true;

        System.exit(10);
    }
}

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  w w  w .  j av  a  2 s .c o  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());
    }

}