Example usage for org.apache.commons.cli GnuParser GnuParser

List of usage examples for org.apache.commons.cli GnuParser GnuParser

Introduction

In this page you can find the example usage for org.apache.commons.cli GnuParser GnuParser.

Prototype

GnuParser

Source Link

Usage

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

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

    Createdoc tmp = new Createdoc();
    /*----------------------------
      get options from ini-file/*from  w  w  w. ja  v a2 s .co  m*/
    ----------------------------*/
    File installDir = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Createdoc.class) + "/..");

    File inifile = new java.io.File(installDir.getAbsolutePath() + "/etc/pkraft-createdoc.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 definition file")
            //            .isRequired()
            .create("definition");

    Option oformat = OptionBuilder.withArgName("format").hasArg()
            .withDescription("[mandatory, default=pdf] output format (pdf|pptx) ").create("format");

    Option ooutput = OptionBuilder.withArgName("output").hasArg().withDescription(
            "[mandatory, default=out.<format>] output file with full documentation of process definition")
            //            .isRequired()
            .create("output");

    ////      Option property = OptionBuilder.withArgName( "property=value" )
    ////            .hasArgs(2)
    ////            .withValueSeparator()
    ////            .withDescription( "use value for given property" )
    ////            .create("D");
    //      
    //      /*----------------------------
    //        create options object
    //      ----------------------------*/
    Options options = new Options();

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

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

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

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

    /*----------------------------
      die variablen festlegen
    ----------------------------*/
    int error = 0;
    String definition = null;
    String format = null;
    String output = null;

    // festlegen von definition
    if (line.hasOption("definition")) {
        definition = line.getOptionValue("definition");
        if (!(new java.io.File(definition).exists())) {
            System.err.println("file does not exist " + definition);
        }
    } else {
        System.err.println("parameter -definition is mandatory");
        error++;
    }

    // festlegen von format
    if (line.hasOption("format")) {
        if (line.getOptionValue("format").matches("pdf|pptx")) {
            format = line.getOptionValue("format");
        } else {
            System.err.println("for -format use only pdf|pptx");
            error++;
        }
    } else {
        format = "pdf";
    }

    // festlegen von output
    if (line.hasOption("output")) {
        output = line.getOptionValue("output");
    } else {
        output = "out." + format;
    }

    // feststellen ob output bereits existiert
    if (new java.io.File(output).exists()) {
        System.err.println("output already exists: " + output);
        error++;
    }

    // aussteigen, falls fehler aufgetaucht sind
    if (error > 0) {
        System.err.println("error(s) occured. try -help for help.");
        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
    ----------------------------*/

    Process process = new Process();
    Reporter report;

    process.setInfilexml(definition);

    System.out.println("info: reading process definition " + definition);

    try {
        process.readXml();
        process.setStepRanks();
    }

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

    //festlegen des temporaeren verzeichnisses fuer die Daten und Pfade erzeugen
    long jetztMillis = System.currentTimeMillis();
    String randomPathJasperFilled = "/tmp/" + jetztMillis + "_jasperFilled";
    String randomPathPng = "/tmp/" + jetztMillis + "_png";
    String randomPathPdf = "/tmp/" + jetztMillis + "_pdf";
    String randomPathPptx = "/tmp/" + jetztMillis + "_pptx";

    new File(randomPathJasperFilled).mkdirs();
    new File(randomPathPng).mkdirs();
    new File(randomPathPdf).mkdirs();
    new File(randomPathPptx).mkdirs();

    //////////////////////////////////////////

    // erstellen der Bilder

    // konfigurieren der processing ansicht
    //      PmodelViewPage page = new PmodelViewPage(process);
    PmodelViewPage page = new PmodelViewPage();
    page.einstellungen.getProcess().setStepRanks();
    page.einstellungen.setSize(100);
    page.einstellungen.setZoom(100);
    //      page.einstellungen.setZoom(8 * 100/process.getMaxLevel());
    page.einstellungen.setTextsize(0);
    page.einstellungen.setRanksize(7);
    page.einstellungen.setWidth(2500);
    page.einstellungen.setHeight(750);
    page.einstellungen.setGravx(10);
    page.einstellungen.setGravy(0);
    page.einstellungen.setRootpositionratiox((float) 0.05);
    page.einstellungen.setRootpositionratioy((float) 0.5);
    page.einstellungen.setProcess(process);

    createContents(page);

    // mit open kann die page angezeigt werden
    if (!(produktiv)) {
        open();
    }

    //      // warten
    //      System.out.println("stabilisierung ansicht: 5 sekunden warten gravitation = "+page.einstellungen.getGravx());
    //      long jetzt5 = System.currentTimeMillis();
    //      while (System.currentTimeMillis() < jetzt5 + 5000)
    //      {
    //         
    //      }
    //
    //      page.einstellungen.setGravx(10);
    //
    // warten
    int wartezeitSeconds = 1;
    if (produktiv) {
        wartezeitSeconds = page.einstellungen.getProcess().getStep().size() * 2;
    }
    System.out.println("stabilisierung ansicht: " + wartezeitSeconds + " sekunden warten gravitation = "
            + page.einstellungen.getGravx());
    long jetzt6 = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt6 + (wartezeitSeconds * 1000)) {

    }

    page.einstellungen.setFix(true);

    // VORBEREITUNG) bild speichern
    processTopologyImagePath = randomPathPng + "/processTopology.png";
    page.savePic(processTopologyImagePath);
    // zuerst 1 sekunde warten, dann autocrop
    long jetzt = System.currentTimeMillis();
    while (System.currentTimeMillis() < jetzt + 1000) {

    }
    new AutoCropBorder(processTopologyImagePath);

    // VORBEREITUNG) fuer jeden step ein bild speichern
    for (Step actualStep : process.getStep()) {

        // root ueberspringen
        //         if (actualStep.isRoot());

        String stepImagePath = randomPathPng + "/step_" + actualStep.getName() + "_Topology.png";

        // Farbe des Steps auf finished (gruen) aendern
        page.einstellungen.getProcess().getRootStep().setStatusOverwrite("waiting");
        actualStep.setStatusOverwrite("finished");

        // etwas warten, bis die farbe bezeichnet wurde
        long jetzt4 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt4 + 500) {

        }

        page.savePic(stepImagePath);
        // zuerst 1 sekunde warten, dann autocrop
        long jetzt3 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt3 + 1000) {

        }
        new AutoCropBorder(stepImagePath);

        stepTopologyImagePath.put(actualStep.getName(), stepImagePath);

        // farbe wieder auf grau aendern
        actualStep.setStatusOverwrite(null);

        System.out.println("erstelle bild fuer step: " + actualStep.getName());

        long jetzt2 = System.currentTimeMillis();
        while (System.currentTimeMillis() < jetzt2 + 1000) {

        }
    }

    page.destroy();

    //////////////////////////////////////////
    report = new Reporter();

    // P03) erstellen des p03
    System.out.println("info: generating p03.");

    String pdfPathP03 = null;
    String pptxPathP03 = null;
    String jasperPathP03 = null;
    String jasperFilledPathP03 = null;

    // P03) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p03") != null) {
        pdfPathP03 = randomPathPdf + "/p03.pdf";
        pptxPathP03 = randomPathPptx + "/p03.pptx";
        jasperPathP03 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p03");
        jasperFilledPathP03 = (randomPathJasperFilled + "/p03.jasperFilled");

        pdfRankFiles.put("0.0.03", pdfPathP03);
        pptxRankFiles.put("0.0.03", pptxPathP03);
    } else {
        System.err.println("no entry 'p03' found in ini file");
        System.exit(1);
    }

    DateFormat dateFormat = new SimpleDateFormat("dd. MM. yyyy");
    Date date = new Date();

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processDatum", dateFormat.format(date));
    report.setParameter("processArchitectLogoImagePath",
            installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "logo"));
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP03, jasperFilledPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP03, pdfPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP03, pptxPathP03);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P05) erstellen des p05
    System.out.println("info: generating p05.");

    String pdfPathP05 = null;
    String pptxPathP05 = null;
    String jasperPathP05 = null;
    String jasperFilledPathP05 = null;

    // P05) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p05") != null) {
        pdfPathP05 = randomPathPdf + "/p05.pdf";
        pptxPathP05 = randomPathPptx + "/p05.pptx";
        jasperPathP05 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p05");
        jasperFilledPathP05 = (randomPathJasperFilled + "/p05.jasperFilled");

        pdfRankFiles.put("0.0.05", pdfPathP05);
        pptxRankFiles.put("0.0.05", pptxPathP05);
    }

    else {
        System.err.println("no entry 'p05' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    try {
        report.fillReportFileToFile(jasperPathP05, jasperFilledPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP05, pdfPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP05, pptxPathP05);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////
    report = new Reporter();

    // P08) erstellen des p08
    System.out.println("info: generating p08.");

    String pdfPathP08 = null;
    String pptxPathP08 = null;
    String jasperPathP08 = null;
    String jasperFilledPathP08 = null;

    // P08) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p08") != null) {
        pdfPathP08 = randomPathPdf + "/p08.pdf";
        pptxPathP08 = randomPathPptx + "/p08.pptx";
        jasperPathP08 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p08");
        jasperFilledPathP08 = (randomPathJasperFilled + "/p08.jasperFilled");

        pdfRankFiles.put("0.0.08", pdfPathP08);
        pptxRankFiles.put("0.0.08", pptxPathP08);
    } else {
        System.err.println("no entry 'p08' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());
    report.setParameter("processDescription", process.getDescription());

    try {
        report.fillReportFileToFile(jasperPathP08, jasperFilledPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP08, pdfPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP08, pptxPathP08);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //System.exit(0);

    //////////////////////////////////////////

    report = new Reporter();

    // P10) erstellen des p10
    System.out.println("info: generating p10.");

    String pdfPathP10 = null;
    String pptxPathP10 = null;
    String jasperPathP10 = null;
    String jasperFilledPathP10 = null;

    // P10) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p10") != null) {
        pdfPathP10 = randomPathPdf + "/p10.pdf";
        pptxPathP10 = randomPathPptx + "/p10.pptx";
        jasperPathP10 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p10");
        jasperFilledPathP10 = (randomPathJasperFilled + "/p10.jasperFilled");

        pdfRankFiles.put("0.0.10", pdfPathP10);
        pptxRankFiles.put("0.0.10", pptxPathP10);
    } else {
        System.err.println("no entry 'p10' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // rootstep holen
    Step rootStep = process.getStep(process.getRootstepname());

    // ueber alle commit iterieren
    for (Commit actualCommit : rootStep.getCommit()) {

        // ueber alle files iterieren
        for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "file");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualFile.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualFile.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualFile.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisFileFromRoot = process.getStepWhichNeedFromRoot("file",
                    actualFile.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisFileFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualFile.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

        // ueber alle variablen iterieren
        for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
            HashMap<String, Object> row = new HashMap<String, Object>();

            // Spalte 'origin'
            row.put("origin", "user/cb2");

            // Spalte 'objectType'
            row.put("objectType", "variable");

            // Spalte 'minOccur'
            row.put("minOccur", "" + actualVariable.getMinoccur());

            // Spalte 'maxOccur'
            row.put("maxOccur", "" + actualVariable.getMaxoccur());

            // Spalte 'objectKey'
            row.put("objectKey", actualVariable.getKey());

            // die steps herausfinden, die dieses file benoetigen
            ArrayList<Step> allStepsThatNeedThisObjectFromRoot = process.getStepWhichNeedFromRoot("variable",
                    actualVariable.getKey());
            String stepnameListe = "";
            for (Step actStep : allStepsThatNeedThisObjectFromRoot) {
                stepnameListe += "\n=> " + actStep.getName();
            }

            // Spalte 'objectDescription'
            row.put("objectDescription", actualVariable.getDescription() + stepnameListe);

            // Datensatz dem report hinzufuegen
            report.addField(row);
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP10, jasperFilledPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP10, pdfPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP10, pptxPathP10);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P20) erstellen des p20
    System.out.println("info: generating p20.");

    String pdfPathP20 = null;
    String pptxPathP20 = null;
    String jasperPathP20 = null;
    String jasperFilledPathP20 = null;

    // P20) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p20") != null) {
        pdfPathP20 = randomPathPdf + "/p20.pdf";
        pptxPathP20 = randomPathPptx + "/p20.pptx";
        jasperPathP20 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p20");
        jasperFilledPathP20 = (randomPathJasperFilled + "/p20.jasperFilled");

        pdfRankFiles.put("0.0.20", pdfPathP20);
        pptxRankFiles.put("0.0.20", pptxPathP20);
    } else {
        System.err.println("no entry 'p20' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // ueber alle steps iterieren (ausser root)
    for (Step actualStep : (ArrayList<Step>) process.getStep()) {

        // ueberspringen wenn es sich um root handelt
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            // ueber alle commit iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // nur die, die toroot=true ( und spaeter auch tosdm=true)
                if (actualCommit.isTorootPresent()) {
                    // ueber alle files iterieren
                    for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'destination'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "file");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualFile.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualFile.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualFile.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualFile.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }

                    // ueber alle variablen iterieren
                    for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                        HashMap<String, Object> row = new HashMap<String, Object>();

                        // Spalte 'objectType'
                        row.put("destination", "user/cb2");

                        // Spalte 'objectType'
                        row.put("objectType", "variable");

                        // Spalte 'minOccur'
                        row.put("minOccur", "" + actualVariable.getMinoccur());

                        // Spalte 'maxOccur'
                        row.put("maxOccur", "" + actualVariable.getMaxoccur());

                        // Spalte 'objectKey'
                        row.put("objectKey", actualVariable.getKey());

                        // Spalte 'objectDescription'
                        row.put("objectDescription",
                                actualVariable.getDescription() + "\n<= " + actualStep.getName());

                        // Datensatz dem report hinzufuegen
                        report.addField(row);
                    }
                }
            }
        }

    }

    try {
        report.fillReportFileToFile(jasperPathP20, jasperFilledPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP20, pdfPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP20, pptxPathP20);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    report = new Reporter();

    // P30) erstellen des p30
    System.out.println("info: generating p30.");

    String pdfPathP30 = null;
    String pptxPathP30 = null;
    String jasperPathP30 = null;
    String jasperFilledPathP30 = null;

    // P30) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p30") != null) {
        pdfPathP30 = randomPathPdf + "/p30.pdf";
        pptxPathP30 = randomPathPptx + "/p30.pptx";
        jasperPathP30 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p30");
        jasperFilledPathP30 = (randomPathJasperFilled + "/p30.jasperFilled");

        pdfRankFiles.put("0.0.30", pdfPathP30);
        pptxRankFiles.put("0.0.30", pptxPathP30);
    } else {
        System.err.println("no entry 'p30' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P1) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    try {
        report.fillReportFileToFile(jasperPathP30, jasperFilledPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP30, pdfPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP30, pptxPathP30);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //      System.exit(0);
    //////////////////////////////////////////

    report = new Reporter();

    // P40) erstellen des p40
    System.out.println("info: generating p40.");

    String pdfPathP40 = null;
    String pptxPathP40 = null;
    String jasperPathP40 = null;
    String jasperFilledPathP40 = null;

    // P40) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
    if (ini.get("pkraft-createdoc", "p40") != null) {
        pdfPathP40 = randomPathPdf + "/p40.pdf";
        pptxPathP40 = randomPathPptx + "/p40.pptx";
        jasperPathP40 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p40");
        jasperFilledPathP40 = (randomPathJasperFilled + "/p40.jasperFilled");

        pdfRankFiles.put("0.0.40", pdfPathP40);
        pptxRankFiles.put("0.0.40", pptxPathP40);
    } else {
        System.err.println("no entry 'p40' found in ini file");
        System.exit(1);
    }

    report.setParameter("processName", process.getName());
    report.setParameter("processVersion", process.getVersion());
    report.setParameter("processArchitectCompany", process.getArchitectCompany());
    report.setParameter("processArchitectName", process.getArchitectName());
    report.setParameter("processArchitectMail", process.getArchitectMail());
    report.setParameter("processCustomerCompany", process.getCustomerCompany());
    report.setParameter("processCustomerName", process.getCustomerName());
    report.setParameter("processCustomerMail", process.getCustomerMail());

    // P40) bild an report melden
    report.setParameter("processTopologyImagePath", processTopologyImagePath);

    // Tabelle erzeugen

    ArrayList<Step> steps = process.getStep();
    for (int x = 0; x < steps.size(); x++) {
        HashMap<String, Object> row = new HashMap<String, Object>();
        Step actualStep = steps.get(x);

        // erste Spalte ist 'rank'
        // um die korrekte sortierung zu erhalten soll der rank-string auf jeweils 2 Stellen erweitert werden
        String[] rankArray = actualStep.getRank().split("\\.");
        Integer[] rankArrayInt = new Integer[rankArray.length];
        for (int y = 0; y < rankArray.length; y++) {
            rankArrayInt[y] = Integer.parseInt(rankArray[y]);
        }
        String rankFormated = String.format("%02d.%02d", rankArrayInt);
        row.put("stepRank", rankFormated);

        // zweite Spalte ist 'stepname'
        row.put("stepName", actualStep.getName());
        //            System.out.println("stepName: "+actualStep.getName());

        // dritte Spalte ist 'Beschreibung'
        row.put("stepDescription", actualStep.getDescription());
        //            System.out.println("stepRank: "+actualStep.getDescription());

        // wenn nicht der root-step, dann row eintragen
        if (!(actualStep.getName().equals(process.getRootstepname()))) {
            report.addField(row);
        }
    }

    try {
        report.fillReportFileToFile(jasperPathP40, jasperFilledPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pdf
    try {
        report.convertFileToPdf(jasperFilledPathP40, pdfPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // export to pptx
    try {
        report.convertFileToPptx(jasperFilledPathP40, pptxPathP40);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    report = null;

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Input Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P51x) erstellen des p51
            System.out.println(
                    "info: generating p51 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP51 = null;
            String pptxPathP51 = null;
            String jasperPathP51 = null;
            String jasperFilledPathP51 = null;

            // P51x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p51") != null) {
                pdfPathP51 = randomPathPdf + "/p5." + stepRank + ".1.pdf";
                pptxPathP51 = randomPathPptx + "/p5." + stepRank + ".1.pptx";
                jasperPathP51 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p51");
                jasperFilledPathP51 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".1", pdfPathP51);
                pptxRankFiles.put(rankFormated + ".1", pptxPathP51);
            } else {
                System.err.println("no entry 'p51' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);
            report.setParameter("stepDescription", actualStep.getDescription());

            String aufruf = "";
            if (actualStep.getWork() != null) {
                // zusammensetzen des scriptaufrufs
                String interpreter = "";

                if (actualStep.getWork().getInterpreter() != null) {
                    interpreter = actualStep.getWork().getInterpreter();
                }

                aufruf = interpreter + " " + actualStep.getWork().getCommand();
                for (Callitem actualCallitem : actualStep.getWork().getCallitem()) {
                    aufruf += " " + actualCallitem.getPar();
                    if (!(actualCallitem.getDel() == null)) {
                        aufruf += actualCallitem.getDel();
                    }
                    if (!(actualCallitem.getVal() == null)) {
                        aufruf += actualCallitem.getVal();
                    }
                }
            } else if (actualStep.getSubprocess() != null) {
                aufruf = ini.get("apps", "pkraft-startinstance");
                aufruf += " --pdomain " + actualStep.getSubprocess().getDomain();
                aufruf += " --pname " + actualStep.getSubprocess().getName();
                aufruf += " --pversion " + actualStep.getSubprocess().getVersion();

                for (Commit actCommit : actualStep.getSubprocess().getStep().getCommit()) {
                    for (de.prozesskraft.pkraft.File actFile : actCommit.getFile()) {
                        aufruf += " --commitfile " + actFile.getGlob();
                    }
                    for (Variable actVariable : actCommit.getVariable()) {
                        aufruf += " --commitvariable " + actVariable.getKey() + "=" + actVariable.getValue();
                    }
                }
            }
            report.setParameter("stepWorkCall", aufruf);

            // P51x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle lists iterieren
            for (List actualList : actualStep.getList()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                row.put("origin", "-");

                // Spalte 'typ'
                row.put("objectType", "wert");

                // Spalte 'minOccur'
                row.put("minOccur", "-");

                // Spalte 'maxOccur'
                row.put("maxOccur", "-");

                // Spalte 'Label'
                row.put("objectKey", actualList.getName());

                // Spalte 'Label'
                String listString = actualList.getItem().toString();
                row.put("objectDescription", listString.substring(1, listString.length() - 1));

                report.addField(row);
            }

            // ueber alle inits iterieren
            for (Init actualInit : actualStep.getInit()) {
                HashMap<String, Object> row = new HashMap<String, Object>();

                // Spalte 'Woher?'
                if (actualInit.getFromstep().equals(process.getRootstepname())) {
                    row.put("origin", "user/cb2");
                } else {
                    row.put("origin", actualInit.getFromstep());
                }

                // Spalte 'typ'
                row.put("objectType", actualInit.getFromobjecttype());

                // Spalte 'minOccur'
                row.put("minOccur", "" + actualInit.getMinoccur());

                // Spalte 'maxOccur'
                row.put("maxOccur", "" + actualInit.getMaxoccur());

                // Spalte 'Label'
                row.put("objectKey", actualInit.getListname());

                // Spalte 'Label'
                row.put("objectDescription", "-");

                report.addField(row);
            }

            try {
                report.fillReportFileToFile(jasperPathP51, jasperFilledPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP51, pdfPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP51, pptxPathP51);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    //////////////////////////////////////////

    // fuer jeden Step einen eigenen Output Report erzeugen

    for (Step actualStep : process.getStep()) {
        // root-step ueberspringen
        if (actualStep.getName().equals(process.getRootstepname())) {
            System.out.println("skipping step root");
        }

        // alle anderen auswerten
        else {

            report = new Reporter();

            // P52x) erstellen des p52
            System.out.println(
                    "info: generating p52 for step " + actualStep.getRank() + " => " + actualStep.getName());

            String stepRank = actualStep.getRank();

            String pdfPathP52 = null;
            String pptxPathP52 = null;
            String jasperPathP52 = null;
            String jasperFilledPathP52 = null;

            // P52x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll
            if (ini.get("pkraft-createdoc", "p52") != null) {
                pdfPathP52 = randomPathPdf + "/p5." + stepRank + ".2.pdf";
                pptxPathP52 = randomPathPptx + "/p5." + stepRank + ".2.pptx";
                jasperPathP52 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p52");
                jasperFilledPathP52 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled";

                String[] rankArray = stepRank.split("\\.");
                Integer[] rankArrayInt = new Integer[rankArray.length];
                for (int x = 0; x < rankArray.length; x++) {
                    rankArrayInt[x] = Integer.parseInt(rankArray[x]);
                }
                String rankFormated = String.format("%03d.%03d", rankArrayInt);

                pdfRankFiles.put(rankFormated + ".2", pdfPathP52);
                pptxRankFiles.put(rankFormated + ".2", pptxPathP52);
            } else {
                System.err.println("no entry 'p52' found in ini file");
                System.exit(1);
            }

            report.setParameter("processName", process.getName());
            report.setParameter("processVersion", process.getVersion());
            report.setParameter("processArchitectCompany", process.getArchitectCompany());
            report.setParameter("processArchitectName", process.getArchitectName());
            report.setParameter("processArchitectMail", process.getArchitectMail());
            report.setParameter("processCustomerCompany", process.getCustomerCompany());
            report.setParameter("processCustomerName", process.getCustomerName());
            report.setParameter("processCustomerMail", process.getCustomerMail());

            report.setParameter("stepName", actualStep.getName());
            report.setParameter("stepRank", stepRank);

            // logfile ermitteln
            String logfile = "-";
            if (actualStep.getWork() != null) {
                if (actualStep.getWork().getLogfile() == null || actualStep.getWork().getLogfile().equals("")) {
                    report.setParameter("stepWorkLogfile", actualStep.getWork().getLogfile());
                }
            } else if (actualStep.getSubprocess() != null) {
                logfile = ".log";
            }
            report.setParameter("stepWorkLogfile", logfile);

            // zusammensetzen der return/exitcode informationen
            String exitInfo = "exit 0 = kein fehler aufgetreten";
            exitInfo += "\nexit >0 = ein fehler ist aufgetreten.";
            if (actualStep.getWork() != null) {
                for (Exit actualExit : actualStep.getWork().getExit()) {
                    exitInfo += "\nexit " + actualExit.getValue() + " = " + actualExit.getMsg();
                }
            }
            report.setParameter("stepWorkExit", exitInfo);

            // P52x) bild an report melden
            report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName()));

            // ueber alle inits iterieren
            for (Commit actualCommit : actualStep.getCommit()) {

                // ueber alle files iterieren
                for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) {

                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "file");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualFile.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualFile.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualFile.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualFile.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

                // ueber alle variablen iterieren
                for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) {
                    HashMap<String, Object> row = new HashMap<String, Object>();

                    // Spalte 'destination'
                    if (actualCommit.isTorootPresent()) {
                        row.put("destination", "user/cb2");
                    } else {
                        row.put("destination", "prozessintern");
                    }

                    // Spalte 'objectType'
                    row.put("objectType", "variable");

                    // Spalte 'minOccur'
                    row.put("minOccur", "" + actualVariable.getMinoccur());

                    // Spalte 'maxOccur'
                    row.put("maxOccur", "" + actualVariable.getMaxoccur());

                    // Spalte 'objectKey'
                    row.put("objectKey", actualVariable.getKey());

                    // Spalte 'objectDescription'
                    row.put("objectDescription", actualVariable.getDescription());

                    // Datensatz dem report hinzufuegen
                    report.addField(row);
                }

            }
            try {
                report.fillReportFileToFile(jasperPathP52, jasperFilledPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pdf
            try {
                report.convertFileToPdf(jasperFilledPathP52, pdfPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // export to pptx
            try {
                report.convertFileToPptx(jasperFilledPathP52, pptxPathP52);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JRException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            report = null;
        }
    }

    // warten bis alles auf platte geschrieben ist
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    // merge and output
    if (format.equals("pdf")) {
        mergePdf(pdfRankFiles, output);
    } else if (format.equals("pptx")) {
        mergePptx(pptxRankFiles, output);
    }

    System.out.println("info: generating process documentation ready.");
    System.exit(0);
}

From source file:com.continuent.tungsten.common.security.PasswordManagerCtrl.java

/**
 * Password Manager entry point//from w w w.  j ava2  s  . co  m
 * 
 * @param argv
 * @throws Exception
 */
public static void main(String argv[]) throws Exception {
    pwd = new PasswordManagerCtrl();

    // --- Options ---
    ClientApplicationType clientApplicationType = null;
    String securityPropertiesFileLocation = null;
    String username = null;
    String password = null;
    CommandLine line = null;

    try {
        CommandLineParser parser = new GnuParser();
        // --- Parse the command line arguments ---

        // --- Help
        line = parser.parse(pwd.helpOptions, argv, true);
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }

        // --- Program command line options
        line = parser.parse(pwd.options, argv);

        // --- Handle options ---

        // --- Optional arguments : Get options ---
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }
        if (line.hasOption(_TARGET_APPLICATION)) // Target Application
        {
            String target = line.getOptionValue(TARGET_APPLICATION);
            clientApplicationType = PasswordManagerCtrl.getClientApplicationType(target);
        }
        if (line.hasOption(_FILE)) // security.properties file location
        {
            securityPropertiesFileLocation = line.getOptionValue(_FILE);
        }
        if (line.hasOption(_AUTHENTICATE)) { // Make sure username + password are provided
            String[] authenticateArgs = line.getOptionValues(_AUTHENTICATE);
            if (authenticateArgs.length < 2)
                throw new MissingArgumentException(authenticate);

            username = authenticateArgs[0];
            password = authenticateArgs[1];
        }
        if (line.hasOption(_CREATE)) { // Make sure username + password are provided
            String[] createArgs = line.getOptionValues(_CREATE);
            if (createArgs.length < 2)
                throw new MissingArgumentException(create);

            username = createArgs[0];
            password = createArgs[1];
        }
        // --- Options to replace values in security.properties file ---
        if (line.hasOption(_ENCRYPTED_PASSWORD))
            pwd.useEncryptedPassword = true;
        if (line.hasOption(_TRUSTSTORE_LOCATION))
            pwd.truststoreLocation = line.getOptionValue(_TRUSTSTORE_LOCATION);
        if (line.hasOption(_TRUSTSTORE_PASSWORD))
            pwd.truststorePassword = line.getOptionValue(_TRUSTSTORE_PASSWORD);
        if (line.hasOption(_KEYSTORE_LOCATION))
            pwd.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION);
        if (line.hasOption(_KEYSTORE_PASSWORD))
            pwd.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD);
        if (line.hasOption(_PASSWORD_FILE_LOCATION))
            pwd.passwordFileLocation = (String) line.getOptionValue(_PASSWORD_FILE_LOCATION);

        try {
            pwd.passwordManager = new PasswordManager(securityPropertiesFileLocation, clientApplicationType);

            AuthenticationInfo authenticationInfo = pwd.passwordManager.getAuthenticationInfo();
            // --- Substitute with user provided options
            if (pwd.useEncryptedPassword != null)
                authenticationInfo.setUseEncryptedPasswords(pwd.useEncryptedPassword);
            if (pwd.truststoreLocation != null)
                authenticationInfo.setTruststoreLocation(pwd.truststoreLocation);
            if (pwd.truststorePassword != null)
                authenticationInfo.setTruststorePassword(pwd.truststorePassword);
            if (pwd.keystoreLocation != null)
                authenticationInfo.setKeystoreLocation(pwd.keystoreLocation);
            if (pwd.keystorePassword != null)
                authenticationInfo.setKeystorePassword(pwd.keystorePassword);
            if (pwd.passwordFileLocation != null)
                authenticationInfo.setPasswordFileLocation(pwd.passwordFileLocation);

            // --- Display summary of used parameters ---
            logger.info("Using parameters: ");
            logger.info("-----------------");
            if (authenticationInfo.getParentPropertiesFileLocation() != null)
                logger.info(MessageFormat.format("security.properties \t = {0}",
                        authenticationInfo.getParentPropertiesFileLocation()));
            logger.info(MessageFormat.format("password_file.location \t = {0}",
                    authenticationInfo.getPasswordFileLocation()));
            logger.info(MessageFormat.format("encrypted.password \t = {0}",
                    authenticationInfo.isUseEncryptedPasswords()));

            // --- Keystore
            if (line.hasOption(_AUTHENTICATE)) {
                logger.info(MessageFormat.format("keystore.location \t = {0}",
                        authenticationInfo.getKeystoreLocation()));
                logger.info(MessageFormat.format("keystore.password \t = {0}",
                        authenticationInfo.getKeystorePassword()));
            }

            // --- Truststore
            if (authenticationInfo.isUseEncryptedPasswords()) {
                logger.info(MessageFormat.format("truststore.location \t = {0}",
                        authenticationInfo.getTruststoreLocation()));
                logger.info(MessageFormat.format("truststore.password \t = {0}",
                        authenticationInfo.getTruststorePassword()));
            }
            logger.info("-----------------");

            // --- AuthenticationInfo consistency check
            // Try to create files if possible
            pwd.passwordManager.try_createAuthenticationInfoFiles();
            authenticationInfo.checkAndCleanAuthenticationInfo();

        } catch (ConfigurationException ce) {
            logger.error(MessageFormat.format(
                    "Could not retrieve configuration information: {0}\nTry to specify a security.properties file location, provide options on the command line, or have the cluster.home variable set.",
                    ce.getMessage()));
            System.exit(EXIT_CODE.EXIT_ERROR.value);
        } catch (ServerRuntimeException sre) {
            logger.error(sre.getLocalizedMessage());
            // AuthenticationInfo consistency check : failed
            DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
        }

        // --- Perform commands ---

        // ######### Authenticate ##########
        if (line.hasOption(_AUTHENTICATE)) {
            try {
                boolean authOK = pwd.passwordManager.authenticateUser(username, password);
                String msgAuthOK = (authOK) ? "SUCCESS" : "FAILED";
                logger.info(
                        MessageFormat.format("Authenticating  {0}:{1} = {2}", username, password, msgAuthOK));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while authenticating user: {0}", e.getMessage()));
            }
        }
        // ######### Create ##########
        if (line.hasOption(_CREATE)) {
            try {
                pwd.passwordManager.setPasswordForUser(username, password);
                logger.info(MessageFormat.format("User created successfuly: {0}", username));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while creating user: {0}", e.getMessage()));
            }
        }

        // ########## DELETE ##########
        else if (line.hasOption(_DELETE)) {
            username = line.getOptionValue(_DELETE);

            try {
                pwd.passwordManager.deleteUser(username);
                logger.info(MessageFormat.format("User deleted successfuly: {0}", username));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while deleting user: {0}", e.getMessage()));
            }
        }

    } catch (ParseException exp) {
        logger.error(exp.getMessage());

        DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
    }
}

From source file:com.telefonica.iot.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.j a va2s  .  c om*/
 * @param args
 */
public static void main(String[] args) {
    try {
        // Print Cygnus starting trace including version
        LOGGER.info("Starting Cygnus, version " + CommonUtils.getCygnusVersion() + "."
                + CommonUtils.getLastCommit());

        // Define the options to be read
        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);

        option = new Option("g", "gui-port", true, "the GUI port");
        option.setRequired(false);
        options.addOption(option);

        option = new Option("t", "polling-interval", true, "polling interval");
        option.setRequired(false);
        options.addOption(option);

        // Read the options
        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("cygnus-flume-ng agent", options, true);
            return;
        } // if

        int apiPort = DEF_MGMT_IF_PORT;

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

        int guiPort = DEF_GUI_PORT;

        if (commandLine.hasOption('g')) {
            guiPort = new Integer(commandLine.getOptionValue('g'));
        } else {
            guiPort = 0; // this disables the GUI for the time being
        } // if else

        int pollingInterval = DEF_POLLING_INTERVAL;

        if (commandLine.hasOption('t')) {
            pollingInterval = new Integer(commandLine.getOptionValue('t'));
        } // 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 e) {
                    LOGGER.error(
                            "Failed to read canonical path for file: " + path + ". Details=" + e.getMessage());
                } // try catch

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

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

        if (reload) {
            LOGGER.debug(
                    "no-reload-conf was not set, thus the configuration file will be polled each 30 seconds");
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, pollingInterval);
            components.add(configurationProvider);
            application = new CygnusApplication(components);
            eventBus.register(application);
        } else {
            LOGGER.debug("no-reload-conf was set, thus the configuration file will only be read this time");
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication();
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        // use the agent name as component name in the logs through log4j Mapped Diagnostic Context (MDC)
        MDC.put(CommonConstants.LOG4J_COMP, commandLine.getOptionValue('n'));

        // start the Cygnus application
        application.start();

        // wait until the references to Flume components are not null
        try {
            while (sourcesRef == null || channelsRef == null || sinksRef == null) {
                LOGGER.info("Waiting for valid Flume components references...");
                Thread.sleep(1000);
            } // while
        } catch (InterruptedException e) {
            LOGGER.error("There was an error while waiting for Flume components references. Details: "
                    + e.getMessage());
        } // try catch

        // start the Management Interface, passing references to Flume components
        LOGGER.info("Starting a Jetty server listening on port " + apiPort + " (Management Interface)");
        mgmtIfServer = new JettyServer(apiPort, guiPort, new ManagementInterface(configurationFile, sourcesRef,
                channelsRef, sinksRef, apiPort, guiPort));
        mgmtIfServer.start();

        // create a hook "listening" for shutdown interrupts (runtime.exit(int), crtl+c, etc)
        Runtime.getRuntime().addShutdownHook(new AgentShutdownHook("agent-shutdown-hook", supervisorRef));

        // start YAFS
        YAFS yafs = new YAFS();
        yafs.start();
    } catch (IllegalArgumentException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } catch (ParseException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } // try catch // try catch
}

From source file:alluxio.yarn.ApplicationMaster.java

/**
 * @param args Command line arguments to launch application master
 *///from   w ww  . j  a  v a2 s  .  c o m
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("num_workers", true, "Number of Alluxio workers to launch. Default 1");
    options.addOption("master_address", true, "(Required) Address to run Alluxio master");
    options.addOption("resource_path", true, "(Required) HDFS path containing the Application Master");

    try {
        LOG.info("Starting Application Master with args {}", Arrays.toString(args));
        final CommandLine cliParser = new GnuParser().parse(options, args);

        YarnConfiguration conf = new YarnConfiguration();
        UserGroupInformation.setConfiguration(conf);
        if (UserGroupInformation.isSecurityEnabled()) {
            String user = System.getenv("ALLUXIO_USER");
            UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
            for (Token token : UserGroupInformation.getCurrentUser().getTokens()) {
                ugi.addToken(token);
            }
            LOG.info("UserGroupInformation: " + ugi);
            ugi.doAs(new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    runApplicationMaster(cliParser);
                    return null;
                }
            });
        } else {
            runApplicationMaster(cliParser);
        }
    } catch (Exception e) {
        LOG.error("Error running Application Master", e);
        System.exit(1);
    }
}

From source file:net.antidot.semantic.rdf.rdb2rdf.main.Db2triples.java

public static void main(String[] args) {
    // Get all options
    Options options = new Options();
    Options r2rmlOptions = new Options();
    Options dmOptions = new Options();
    options.addOption(modeOpt);//from   w w w. j a v  a 2  s.  c  om
    options.addOption(userNameOpt);
    r2rmlOptions.addOption(userNameOpt);
    dmOptions.addOption(userNameOpt);
    options.addOption(passwordOpt);
    r2rmlOptions.addOption(passwordOpt);
    dmOptions.addOption(passwordOpt);
    options.addOption(URLOpt);
    r2rmlOptions.addOption(URLOpt);
    dmOptions.addOption(URLOpt);
    options.addOption(driverOpt);
    r2rmlOptions.addOption(driverOpt);
    dmOptions.addOption(driverOpt);
    options.addOption(dbOpt);
    r2rmlOptions.addOption(dbOpt);
    dmOptions.addOption(dbOpt);
    options.addOption(baseURIOpt);
    r2rmlOptions.addOption(baseURIOpt);
    dmOptions.addOption(baseURIOpt);
    options.addOption(forceOpt);
    r2rmlOptions.addOption(forceOpt);
    dmOptions.addOption(forceOpt);
    options.addOption(nativeOpt);
    r2rmlOptions.addOption(nativeOpt);
    dmOptions.addOption(nativeOpt);
    options.addOption(nativeStoreNameOpt);
    r2rmlOptions.addOption(nativeStoreNameOpt);
    dmOptions.addOption(nativeStoreNameOpt);
    options.addOption(outputOpt);
    r2rmlOptions.addOption(outputOpt);
    dmOptions.addOption(outputOpt);
    options.addOption(transformSPARQLFile);
    dmOptions.addOption(transformSPARQLFile);
    options.addOption(transformOutputFile);
    dmOptions.addOption(transformOutputFile);
    options.addOption(rdfFormat);
    r2rmlOptions.addOption(rdfFormat);
    dmOptions.addOption(rdfFormat);
    options.addOption(versionOpt);
    dmOptions.addOption(versionOpt);
    options.addOption(r2rmlFileOpt);
    r2rmlOptions.addOption(r2rmlFileOpt);

    // Init parameters
    String mode = null;
    String userName = null;
    String password = null;
    String url = null;
    DriverType driver = null;
    String dbName = null;
    String baseURI = null;
    boolean useNativeStore = false;
    boolean forceExistingRep = false;
    String nativeOutput = null;
    String output = null;
    String sparql = null;
    String sparqlOutput = null;
    String format = null;
    String r2rmlFile = null;
    int int_version = 1;

    // RDF Format output
    RDFFormat rdfFormat = RDFFormat.TURTLE; // Turtle by default
    // Norm version
    Version version = Version.WD_20120529;

    // Option parsing
    // Create the parser
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        // Database settings
        // Mode
        if (!line.hasOption("mode")) {
            // automatically generate the help statement
            log.error("Mode is required. Use -m option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(projectName, options);
            System.exit(-1);
        } else {
            mode = line.getOptionValue("mode");
            if (!mode.equals("r2rml") && !mode.equals("dm")) {
                log.error("Unkonw mode. Please select 'r2rml' or 'dm' mode.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectName, options);
                System.exit(-1);
            }
        }
        // user name
        if (!line.hasOption("user")) {
            // automatically generate the help statement
            log.error("User name is required. Use -u option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            userName = line.getOptionValue("user");
        }
        // password
        if (!line.hasOption("pass")) {
            // automatically generate the help statement
            log.error("Password is required. Use -p option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            password = line.getOptionValue("pass");
        }
        // Database URL
        url = line.getOptionValue("url", "jdbc:mysql://localhost/");
        // driver
        driver = new DriverType(line.getOptionValue("driver", defaultDriver.getDriverName()));
        // Database name
        if (!line.hasOption("database")) {
            // automatically generate the help statement
            log.error("Database name is required. Use -b option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            dbName = line.getOptionValue("database");
        }
        // Base URI
        baseURI = line.getOptionValue("base_uri", "http://foo.example/DB/");
        // Use of native store ?
        useNativeStore = line.hasOption("n");
        // Name of native store
        if (useNativeStore && !line.hasOption("native_output")) {
            // automatically generate the help statement
            log.error("Native triplestore path is required. Use -n option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            nativeOutput = line.getOptionValue("native_output");
        }
        // Force loading of repository
        forceExistingRep = line.hasOption("f");
        // Output
        output = line.getOptionValue("output", "output.ttl");
        // SPARQL transformation
        if (line.hasOption("sparql")) {
            if (!mode.equals("dm")) {
                log.warn("sparql option is required only for 'dm' mode : it will be ignored...");
            } else {
                sparql = line.getOptionValue("sparql");
                sparqlOutput = line.getOptionValue("sparql_output", "output_sparql.ttl");
            }
        }
        // RDF Format
        if (line.hasOption("format")) {
            format = line.getOptionValue("format");
            if (format.equals("TURTLE"))
                rdfFormat = RDFFormat.TURTLE;
            else if (format.equals("RDFXML"))
                rdfFormat = RDFFormat.RDFXML;
            else if (format.equals("NTRIPLES"))
                rdfFormat = RDFFormat.NTRIPLES;
            else if (!format.equals("N3")) {
                log.error("Unknown RDF format. Please use RDFXML, TURTLE, N3 or NTRIPLES.");
                HelpFormatter formatter = new HelpFormatter();
                if (mode.equals("r2rml")) {
                    formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                } else {
                    formatter.printHelp(projectNameDirectMappingMode, dmOptions);
                }
                System.exit(-1);
            }
        }
        // Norm version
        if (line.hasOption("version")) {
            if (!mode.equals("dm")) {
                log.warn("version option is required only for 'dm' mode : it will be ignored...");
            }
            switch (int_version) {
            case 1:
                version = Version.WD_20120529;
                break;
            case 2:
                version = Version.WD_20110324;
                // Check DB compatibilities
                if (!(driver.equals(DriverType.MysqlDriver) || driver.equals(DriverType.PostgreSQL))) {
                    log.error(
                            "Db2triples in Direct Mapping mode does'nt support this driver for the Working Draft"
                                    + " of 23 March 2011 (only MySQL and PostGreSQL for this time). "
                                    + "You can set the version option to select Working Draft of 20 September 2011.");
                    System.exit(-1);
                }
                break;
            default:
                break;
            }
        }
        // r2rml instance
        if (mode.equals("r2rml")) {
            if (!line.hasOption("r2rml_file")) {
                log.error("R2RML config file is required. Use -r option to set it.");
                // automatically generate the help statement
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                System.exit(-1);
            } else {
                r2rmlFile = line.getOptionValue("r2rml_file");
                File r2rmlFileTest = new File(r2rmlFile);
                if (!r2rmlFileTest.exists()) {
                    log.error("R2RML file does not exists.");
                    System.exit(-1);
                }
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        log.error("Parsing failed. Reason : " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(projectName, options);
        System.exit(-1);
    }

    // Open test database
    Connection conn = null;
    try {
        // Connect database
        conn = SQLConnector.connect(userName, password, url + dbName, driver);

        // Generate RDF graph
        SesameDataSet g = null;
        // Check nature of storage (memory by default)
        if (useNativeStore) {
            File pathToNativeOutputDir = new File(nativeOutput);
            if (pathToNativeOutputDir.exists() && !forceExistingRep) {
                log.error("Directory " + pathToNativeOutputDir
                        + "  already exists. Use -f option to force loading of existing repository.");
                System.exit(-1);
            }
            // Extract database model according to convert mode
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, nativeOutput, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, nativeOutput);
            }
        } else {
            File outputFile = new File(output);
            if (outputFile.exists() && !forceExistingRep) {
                log.error("Output file " + outputFile.getAbsolutePath()
                        + " already exists. Please remove it or modify ouput name option.");
                System.exit(-1);
            }
            // Extract database model
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, null);
            }
            // Dump graph
            log.info("Serialize RDF graph...");
            g.dumpRDF(output, rdfFormat);
            log.info("RDF graph serialized into " + outputFile.getAbsolutePath());
        }
        if (sparql != null && mode.equals("dm")) {
            log.info("Execute SPARQL transformation...");
            Long start = System.currentTimeMillis();
            String result = g.runSPARQLFromFile(sparql, rdfFormat);
            SesameDataSet gResult = new SesameDataSet();
            gResult.addString(result, rdfFormat);
            gResult.dumpRDF(sparqlOutput, rdfFormat);

            Float stop = Float.valueOf(System.currentTimeMillis() - start) / 1000;
            log.info("Direct Mapping SPARQL query executed in " + stop + " seconds.");
            log.info("[DirectMapping:main] Number of triples after transformation : " + gResult.getSize());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // Close db connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.mybox.mybox.Server.java

/**
 * Handle the command line args and instantiate the Server
 * @param args/*from www.  j av  a2 s.com*/
 */
public static void main(String args[]) {

    Options options = new Options();
    options.addOption("c", "config", true, "configuration file");
    //    options.addOption("d", "database", true, "accounts database file"); // TODO: handle in config?
    options.addOption("a", "apphome", true, "application home directory");
    options.addOption("h", "help", false, "show help screen");
    options.addOption("V", "version", false, "print the Mybox version");

    CommandLineParser line = new GnuParser();
    CommandLine cmd = null;

    try {
        cmd = line.parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.class.getName(), options);
        return;
    }

    if (cmd.hasOption("V")) {
        Client.printMessage("version " + Common.appVersion);
        return;
    }

    if (cmd.hasOption("a")) {
        String appHomeDir = cmd.getOptionValue("a");
        try {
            Common.updatePaths(appHomeDir);
        } catch (FileNotFoundException e) {
            printErrorExit(e.getMessage());
        }

        updatePaths();
    }

    String configFile = defaultConfigFile;
    //    String accountsDBfile = defaultAccountsDbFile;

    if (cmd.hasOption("c")) {
        configFile = cmd.getOptionValue("c");
    }

    File fileCheck = new File(configFile);
    if (!fileCheck.isFile())
        Server.printErrorExit("Config not found: " + configFile + "\nPlease run ServerSetup");

    //    if (cmd.hasOption("d")){
    //      accountsDBfile = cmd.getOptionValue("d");
    //    }
    //
    //    fileCheck = new File(accountsDBfile);
    //    if (!fileCheck.isFile())
    //      Server.printErrorExit("Error: account database not found " + accountsDBfile);

    Server server = new Server(configFile);
}

From source file:at.gv.egiz.pdfas.cli.Main.java

public static void main(String[] args) {
    // create the command line parser

    CommandLineParser parser = new GnuParser();
    ModeOfOperation mode = ModeOfOperation.INVALID;
    try {//  www .ja  v  a2  s.c  o m
        CommandLine cli = parser.parse(createOptions(), args);

        if (cli.hasOption(CLI_ARG_DEPLOY_SHORT)) {
            PdfAsFactory.deployDefaultConfiguration(new File(STANDARD_CONFIG_LOCATION));
            System.out.println("Configuration was deployed to: " + STANDARD_CONFIG_LOCATION);
        }

        if (cli.hasOption(CLI_ARG_MODE_SHORT)) {
            String modevalue = cli.getOptionValue(CLI_ARG_MODE_SHORT);
            if (modevalue.toLowerCase().trim().equals("sign")) {
                mode = ModeOfOperation.SIGN;
            } else if (modevalue.toLowerCase().trim().equals("verify")) {
                mode = ModeOfOperation.VERIFY;
            } else {
                throw new ParseException("Invalid value for option " + CLI_ARG_MODE_SHORT + ": " + modevalue);
            }
        }

        if (cli.hasOption(CLI_ARG_HELP_SHORT)) {
            usage();
            System.exit(0);
        }

        if (mode == ModeOfOperation.INVALID && !cli.hasOption(CLI_ARG_DEPLOY_SHORT)) {
            usage();
        } else if (mode == ModeOfOperation.SIGN) {
            perform_sign(cli);
        } else if (mode == ModeOfOperation.VERIFY) {
            perform_verify(cli);
        }
    } catch (ParseException e) {
        System.err.println("Invalid arguments: " + e.getMessage());
        usage();
        System.exit(-1);
    } catch (PDFASError e) {
        System.err.println("PDF-AS Error: [" + e.getCode() + "]" + e.getMessage());
        Iterator<Entry<String, String>> infoIt = e.getProcessInformations().entrySet().iterator();

        while (infoIt.hasNext()) {
            Entry<String, String> infoEntry = infoIt.next();
            logger.debug("Process Information: {} = {}", infoEntry.getKey(), infoEntry.getValue());
        }
        e.printStackTrace(System.err);
        System.exit(-1);
    } catch (Throwable e) {
        System.err.println("Unhandled PDF-AS Error: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:com.kactech.otj.examples.Faucet.java

public static void main(String[] args) throws Exception {
    String channel = "#opentransactions"
    //"#kactech_test"
    ////  w ww .  j a va  2s . co  m
    ;
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println("Command-line parsing error: " + e.getMessage());
        help();
        System.exit(-1);
    }
    if (cmd.hasOption('h')) {
        help();
        System.exit(0);
    }
    if (cmd.hasOption('c'))
        channel = cmd.getOptionValue('c');
    Utils.init();
    client = new EClient(new File("faucet_client"), ExamplesUtils.findServer("OT 8coin")
    //ExamplesUtils.findServer("van")
    );
    client.setAssetType(ExamplesUtils.findAsset("silver").assetID);

    client.init();
    PircBotX bot = new PircBotX();

    bot.setName("OTjFaucet");
    bot.setLogin("fast");
    bot.setVerbose(true);
    bot.setAutoNickChange(true);
    bot.setCapEnabled(true);

    final IrcListener listener = new IrcListener(bot, client);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            if (client == null)
                return;
            client.saveState();
            try {
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                client = null;
            }
            try {
                listener.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));
    bot.getListenerManager().addListener(listener);
    try {
        bot.connect("irc.freenode.net");
        bot.joinChannel(channel);
        if (false)
            while (true) {
                Thread.sleep(1000);
            }
        //bot.quitServer("end of test");

        while (bot.isConnected())
            Thread.sleep(100);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        System.out.println("finally");
        bot.disconnect();
        client.saveState();
        client.close();
        client = null;
    }
}

From source file:eu.irreality.age.SwingAetheriaGameLoaderInterface.java

public static void main(String[] args) {

    if (args.length > 0) {
        //parse command line

        Option sdi = new Option("sdi", "use single-document interface");
        Option worldFile = OptionBuilder.withArgName("file").hasArg()
                .withDescription("The world file or URL to play").withLongOpt("worldfile").create("w");
        /*/* w w w  . ja v  a2  s .c  om*/
        Option worldUrl = OptionBuilder.withArgName( "url" )
           .hasArg()
           .withDescription(  "The world URL to play" )
           .create( "worldurl" );   */
        Option logFile = OptionBuilder.withArgName("file").hasArg()
                .withDescription("Log file to load the game from (requires a world file)")
                .withLongOpt("logfile").create("l");
        Option stateFile = OptionBuilder.withArgName("file").hasArg()
                .withDescription("State file to load the game from (requires a world file)")
                .withLongOpt("statefile").create("s");
        Option errorLog = OptionBuilder.withArgName("errorlog").hasArg()
                .withDescription("A file to append the error output to").withLongOpt("errorlog").create("e");

        Option saveDir = OptionBuilder.withArgName("pathToDir").hasArg()
                .withDescription("Path to the directory where saves will be stored by default")
                .withLongOpt("savedir").create("d");

        Options options = new Options();

        options.addOption(sdi);
        options.addOption(worldFile);
        //options.addOption( worldUrl );
        options.addOption(logFile);
        options.addOption(stateFile);
        options.addOption(errorLog);
        options.addOption(saveDir);

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

            String desiredWorldFile = null;
            //String desiredWorldUrl = null;
            String desiredLogFile = null;
            String desiredStateFile = null;

            String errorLogFile = null;

            String saveDirPath = null;

            if (line.hasOption("e"))
                errorLogFile = line.getOptionValue("e");

            if (line.hasOption("s"))
                desiredStateFile = line.getOptionValue("s");
            if (line.hasOption("l"))
                desiredLogFile = line.getOptionValue("l");
            if (line.hasOption("w"))
                desiredWorldFile = line.getOptionValue("w");

            if (line.hasOption("d"))
                saveDirPath = line.getOptionValue("sd");

            //first, redirect std. error if necessary
            if (errorLogFile != null)
                redirectStandardError(errorLogFile);

            //set save dir if requested
            if (saveDirPath != null) {
                Paths.setSaveDir(saveDirPath);
            }

            //if ( line.hasOption("worldurl") ) desiredWorldFile = line.getOptionValue("worldurl");
            if (desiredWorldFile == null /*&& desiredWorldUrl == null*/ && line.getArgs().length > 0)
                desiredWorldFile = line.getArgs()[0];
            boolean desiredSdi = line.hasOption("sdi"); //Boolean.valueOf( line.getOptionValue("sdi") ).booleanValue();       

            if (SwingAetheriaGUI.getInstance() != null && !desiredSdi) {
                //abrir un fichero en una instancia de AGE ya abierta
                System.out.println("Opening file in existing instance...");
                createLocalGameFromFile(desiredWorldFile, true, desiredLogFile != null, desiredLogFile,
                        desiredStateFile);
                return;
            } else {

                System.out.println("Working directory: " + Paths.getWorkingDirectory());
                setLookAndFeel();

                if (!desiredSdi) {
                    new SwingAetheriaGUI();
                    if (desiredWorldFile != null)
                        createLocalGameFromFile(desiredWorldFile, !desiredSdi, desiredLogFile != null,
                                desiredLogFile, desiredStateFile);
                } else {
                    if (desiredWorldFile != null)
                        createLocalGameFromFile(desiredWorldFile, !desiredSdi, desiredLogFile != null,
                                desiredLogFile, desiredStateFile);
                    else
                        SwingSDIInterface.main(args); //args does nothing in this case, really
                }
            }

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

    } else {
        setLookAndFeel();
        new SwingAetheriaGUI();
    }

    /*
    if ( args.length > 0 && SwingAetheriaGUI.getInstance() != null )
    {
       //abrir un fichero en una instancia de AGE ya abierta
       System.out.println("Opening file in existing instance...");
       createLocalGameFromFile(args[0]);
       return;
    }
    */

    /*
    if ( args.length > 0 )
    {
       System.out.println("Opening file in newly created instance...");
       createLocalGameFromFile(args[0]);
    }
    */

}

From source file:net.certifi.audittablegen.AuditTableGen.java

public static void main(String[] args) {
    Properties prop;/*  w  w  w  .  ja  v  a2  s.  c o  m*/
    Options options = new Options();
    options.addOption("h", "help", false, "display this message");
    options.addOption("d", "database", true, "Name of the database to connect to");
    options.addOption("s", "server", true, "Name of the Server to connect to");
    options.addOption("driver", true, "specifiy jdbc driver. Only used if can't resolve from url");
    options.addOption("u", "username", true, "DB server login username");
    options.addOption("p", "password", true, "DB server login password");
    options.addOption("f", "filename", true, "name of file to store the script");
    options.addOption("schema", true, "name of the target schema");
    options.addOption("url", true, "full url to DB.  Overrides -d, -s");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd;
    AuditTableGen atg;
    DataSource ds;

    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            usage(options);
            return;
        }

        prop = getRunTimeProperties(cmd);

        if (!prop.getProperty("validArgs", "false").equals("true")) {
            usage(options);
            return;
        }

    } catch (ParseException ex) {
        logger.error("Error", ex);
        throw Throwables.propagate(ex);
        //            System.exit(1);
        //            return; //return here just to make the compiler shut-up
    }

    try {
        ds = getRunTimeDataSource(prop);
        atg = new AuditTableGen(ds, prop.getProperty("schema", null));
        //logger.info(atg.getDataSourceInfo());

        //DataSourceDMR dsDMR = GetDataSourceDMR (cmd);
        //            Connection conn = GetConnection.ConnectionFromOptions(prop);
        //            TestConnection.GetData(conn);
        //            conn.close(); 
    } catch (Exception ex) {
        logger.error("Error", ex);
        throw Throwables.propagate(ex);
    }

    Boolean result = atg.updateAuditTables();

    logger.info("Done.");
}