Beispiel #1
0
 public void test_SameFirstChar() throws Exception {
   CommandLine getopt = new CommandLine(rp);
   CommandTwoOptions c = new CommandTwoOptions();
   getopt.execute(c, "commandTwoOptions", new ExtList<String>("-t", "test", "-T", "title"));
   assertEquals("title", c.title);
   assertEquals("test", c.test);
 }
  public static void main(String args[]) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("u", "uniquehits", false, "only output hits with a single mapping");
    options.addOption(
        "s",
        "nosuboptimal",
        false,
        "do not include hits whose score is not equal to the best score for the read");
    CommandLineParser parser = new GnuParser();
    CommandLine cl = parser.parse(options, args, false);
    boolean uniqueOnly = cl.hasOption("uniquehits");
    boolean filterSubOpt = cl.hasOption("nosuboptimal");

    ArrayList<String[]> lines = new ArrayList<String[]>();

    String line;
    String lastRead = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while ((line = reader.readLine()) != null) {
      String pieces[] = line.split("\t");
      if (!pieces[0].equals(lastRead)) {
        printLines(lines, uniqueOnly, filterSubOpt);
        lines.clear();
      }
      lines.add(pieces);
      lastRead = pieces[0];
    }
    printLines(lines, uniqueOnly, filterSubOpt);
  }
Beispiel #3
0
 public void test_SameFirstChar_MaxTwoOptionsWithSameShortcut() throws Exception {
   CommandLine getopt = new CommandLine(rp);
   CommandThreeOptions c = new CommandThreeOptions();
   try {
     getopt.execute(c, "commandThreeOptions", new ExtList<String>());
     fail();
   } catch (Error e) {
   }
 }
Beispiel #4
0
 public void test_SameFirstChar_NoCapitalizedCommands() throws Exception {
   CommandLine getopt = new CommandLine(rp);
   CommandWrongOption c = new CommandWrongOption();
   try {
     getopt.execute(c, "commandWrongOption", new ExtList<String>());
     fail();
   } catch (Error e) {
   }
 }
Beispiel #5
0
 public void testSimple() throws Exception {
   CommandLine getopt = new CommandLine(rp);
   C1 c1 = new C1();
   String help =
       getopt.execute(
           c1,
           "c1",
           new ExtList<String>(
               "-f", "-a", "33", "--bb", "bb", "-i", "f1.txt", "-i", "f2.txt", "--", "-a", "--a",
               "a"));
   System.err.println(help);
 }
 public static String[] generateFileNamesFromOptions(CommandLine cli) {
   String[] filenames = cli.getArgs();
   List<String> fileList = new ArrayList<String>(filenames.length);
   boolean errors = false;
   for (String filename : filenames) {
     if (filename.startsWith("@")) {
       try {
         BufferedReader br = new BufferedReader(new FileReader(filename.substring(1)));
         String file;
         while ((file = br.readLine()) != null) {
           fileList.add(file);
         }
       } catch (IOException ioe) {
         System.err.println("error: file not readable: " + filename.substring(1));
         errors = true;
       }
     } else {
       fileList.add(filename);
     }
   }
   if (errors) {
     return null;
   } else {
     return fileList.toArray(new String[fileList.size()]);
   }
 }
  public static void main(String[] args) {
    Options options = new Options();
    options.addOption("v", true, "Input Vector folder"); // yearly vector data
    options.addOption("p", true, "Points folder"); // yearly mds (rotate) output
    options.addOption("d", true, "Destination folder");
    options.addOption("o", true, "Original stock file"); // global 10 year stock file
    options.addOption(
        "s",
        true,
        "Sector file"); // If Histogram true then set this as the folder to histogram output
    options.addOption("h", false, "Gen from histogram");
    options.addOption("e", true, "Extra classes file"); // a file containing fixed classes
    options.addOption("ci", true, "Cluster input file");
    options.addOption("co", true, "Cluster output file");

    CommandLineParser commandLineParser = new BasicParser();
    try {
      CommandLine cmd = commandLineParser.parse(options, args);
      String vectorFile = cmd.getOptionValue("v");
      String pointsFolder = cmd.getOptionValue("p");
      String distFolder = cmd.getOptionValue("d");
      String originalStocks = cmd.getOptionValue("o");
      String sectorFile = cmd.getOptionValue("s");
      boolean histogram = cmd.hasOption("h");
      String fixedClasses = cmd.getOptionValue("e");
      String clusterInputFile = cmd.getOptionValue("ci");
      String clusterOutputFile = cmd.getOptionValue("co");

      LabelApply program =
          new LabelApply(
              vectorFile,
              pointsFolder,
              distFolder,
              originalStocks,
              sectorFile,
              histogram,
              fixedClasses,
              clusterInputFile,
              clusterOutputFile);
      program.process();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  /**
   * Same as main(args) except that exceptions are thrown out instead of causing the VM to exit and
   * the lookup for .groovy files can be controlled
   */
  public static void commandLineCompile(String[] args, boolean lookupUnnamedFiles)
      throws Exception {
    Options options = createCompilationOptions();

    CommandLineParser cliParser = new GroovyPosixParser();

    CommandLine cli;
    cli = cliParser.parse(options, args);

    if (cli.hasOption('h')) {
      displayHelp(options);
      return;
    }

    if (cli.hasOption('v')) {
      displayVersion();
      return;
    }

    displayStackTraceOnError = cli.hasOption('e');

    CompilerConfiguration configuration = generateCompilerConfigurationFromOptions(cli);

    //
    // Load the file name list
    String[] filenames = generateFileNamesFromOptions(cli);
    boolean fileNameErrors = filenames == null;
    if (!fileNameErrors && (filenames.length == 0)) {
      displayHelp(options);
      return;
    }

    fileNameErrors = fileNameErrors && !validateFiles(filenames);

    if (!fileNameErrors) {
      doCompilation(configuration, null, filenames, lookupUnnamedFiles);
    }
  }
 @Override
 protected void parseArgs(CommandLine cli, String[] args)
     throws ParseException, ArrayIndexOutOfBoundsException, HelpException {
   if (args.length == 5) {
     super.parseArgs(cli, args);
     orig_trace_name = args[1];
     dest_trace_name = args[2];
     minTime = Long.parseLong(args[3]);
     maxTime = Long.parseLong(args[4]);
   } else {
     orig_store_file = new File(args[0]);
     dest_store_file = new File(args[1]);
     minTime = Long.parseLong(args[2]);
     maxTime = Long.parseLong(args[3]);
     force = cli.hasOption(forceOption);
   }
 }
Beispiel #10
0
  private static void parse_args(String[] args, String formatstr, Options opt) {
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;

    try {
      cl = parser.parse(opt, args);
    } catch (ParseException e) {
      formatter.printHelp(formatstr, opt); // 如果发生异常,则打印出帮助信息
    }

    if (cl.hasOption("in") && cl.hasOption("out") && cl.hasOption("dd") && cl.hasOption("sw")) {
      String stopWordsPath = cl.getOptionValue("sw");
      String inPath = cl.getOptionValue("in");
      String outPath = cl.getOptionValue("out");
      String dicPath = cl.getOptionValue("dd");
      processOperation(stopWordsPath, inPath, outPath, dicPath);
    } else {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    }
  }
Beispiel #11
0
 /** Parses command line arguments. */
 boolean parseArgs(String args[]) {
   /* Preprocess and expand @file arguments */
   try {
     args = CommandLine.parse(args);
   } catch (FileNotFoundException e) {
     fatalError(formatMsg("error.cant.open", e.getMessage()));
     return false;
   } catch (IOException e) {
     fatalError(e);
     return false;
   }
   /* parse flags */
   int count = 1;
   try {
     String flags = args[0];
     if (flags.startsWith("-")) {
       flags = flags.substring(1);
     }
     for (int i = 0; i < flags.length(); i++) {
       switch (flags.charAt(i)) {
         case 'c':
           if (xflag || tflag || uflag || iflag) {
             usageError();
             return false;
           }
           cflag = true;
           break;
         case 'u':
           if (cflag || xflag || tflag || iflag) {
             usageError();
             return false;
           }
           uflag = true;
           break;
         case 'x':
           if (cflag || uflag || tflag || iflag) {
             usageError();
             return false;
           }
           xflag = true;
           break;
         case 't':
           if (cflag || uflag || xflag || iflag) {
             usageError();
             return false;
           }
           tflag = true;
           break;
         case 'M':
           Mflag = true;
           break;
         case 'v':
           vflag = true;
           break;
         case 'f':
           fname = args[count++];
           break;
         case 'm':
           mname = args[count++];
           break;
         case '0':
           flag0 = true;
           break;
         case 'i':
           if (cflag || uflag || xflag || tflag) {
             usageError();
             return false;
           }
           // do not increase the counter, files will contain rootjar
           rootjar = args[count++];
           iflag = true;
           break;
         case 'e':
           ename = args[count++];
           break;
         case 'p':
           pname = args[count++];
           break;
         default:
           error(formatMsg("error.illegal.option", String.valueOf(flags.charAt(i))));
           usageError();
           return false;
       }
     }
   } catch (ArrayIndexOutOfBoundsException e) {
     usageError();
     return false;
   }
   if (!cflag && !tflag && !xflag && !uflag && !iflag) {
     error(getMsg("error.bad.option"));
     usageError();
     return false;
   }
   /* parse file arguments */
   int n = args.length - count;
   if (n > 0) {
     int k = 0;
     String[] nameBuf = new String[n];
     try {
       for (int i = count; i < args.length; i++) {
         if (args[i].equals("-C")) {
           /* change the directory */
           String dir = args[++i];
           dir = (dir.endsWith(File.separator) ? dir : (dir + File.separator));
           dir = dir.replace(File.separatorChar, '/');
           while (dir.indexOf("//") > -1) {
             dir = dir.replace("//", "/");
           }
           paths.add(dir.replace(File.separatorChar, '/'));
           nameBuf[k++] = dir + args[++i];
         } else {
           nameBuf[k++] = args[i];
         }
       }
     } catch (ArrayIndexOutOfBoundsException e) {
       usageError();
       return false;
     }
     files = new String[k];
     System.arraycopy(nameBuf, 0, files, 0, k);
   } else if (cflag && (mname == null)) {
     error(getMsg("error.bad.cflag"));
     usageError();
     return false;
   } else if (uflag) {
     if ((mname != null) || (ename != null) || (pname != null)) {
       /* just want to update the manifest */
       return true;
     } else {
       error(getMsg("error.bad.uflag"));
       usageError();
       return false;
     }
   }
   return true;
 }
Beispiel #12
0
  /*
   *main function
   */
  public static void main(String args[]) {
    String title1 = " ";
    String publisher_name1 = " ";
    String published_date1 = "";
    String content1 = "";
    int n = 0;
    String str = "";

    // try block starts here
    try {
      Options option = new Options();
      option.addOption("hp", false, "help");
      option.addOption("hlp", false, "help");
      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse(option, args);
      // str=cmd.getArgs()[0];

      /*prints the help message here*/
      if ((cmd.hasOption("hp")) || (cmd.hasOption("hlp"))) {
        System.out.println(
            "this program gets an argument through commandline 'n' number of books. then reads n books from standard input"
                + "and prints them on standard output");

        if (args.length <= 1) {

          // exit the program
          System.exit(0);
        }
      } // close outer if block
      else {
        if (args.length < 1) {

          // if user not gives option  and value of n then prints this message.
          System.out.println(
              "this program gets an argument through commandline 'n' number of books. then reads n books from standard input"
                  + "and prints them on standard output");
          System.exit(0);
        }
      } // close the  outer else block

      str = cmd.getArgs()[0];
      n = Integer.parseInt(str);

    } catch (Exception e) {
      // System.exit(0);
      // if any erroy occurs it catches here
      System.out.println(e);
    }

    int num = 0;
    Scanner sc1 = new Scanner(System.in); /*create an instance of scanner object*/
    Scanner sc = new Scanner(System.in);

    CmdBook b[] = new CmdBook[n]; /* create arraylist of objects of class Book*/
    for (int i = 0; i < n; i++) {

      // initialise the array of objects
      b[i] = new CmdBook();
    }
    for (int i = 0; i < n; i++) {

      /* take input from  standard input*/
      System.out.println("enter the title of the book:");
      title1 = sc.next();

      System.out.println("enter the name of publisher");
      publisher_name1 = sc.next();

      System.out.println("enter published date");
      published_date1 = sc.next();

      System.out.println("how many authors are");
      num = sc1.nextInt();

      ArrayList<String> author_name1 =
          new ArrayList<String>(); /*create an ArrayList author_name1 */

      for (int j = 0; j < num; j++) {

        /*take input */
        System.out.println("enter authorname" + (j + 1));
        author_name1.add(sc.next());
      }

      System.out.println("enter contents of book:");
      content1 = sc.next();

      /* call the method bookdetail with auguments which contains from
       *  standard input
       */

      b[i].bookdetail(title1, publisher_name1, published_date1, content1, author_name1);
    }
    for (int i = 0; i < n; i++) {

      /*call the methode printbook withe no aurgument*/
      b[i].printbook();
    }
  } /*end of main function here*/
Beispiel #13
0
  public void testCommand() throws Exception {
    CommandLine getopt = new CommandLine(rp);
    assertEquals("[cmda, cmdb]", getopt.getCommands(new X()).keySet().toString());

    getopt.execute(new X(), "cmda", Arrays.asList("-e", "help"));
  }
  public static CompilerConfiguration generateCompilerConfigurationFromOptions(CommandLine cli)
      throws IOException {
    //
    // Setup the configuration data

    CompilerConfiguration configuration = new CompilerConfiguration();

    if (cli.hasOption("classpath")) {
      configuration.setClasspath(cli.getOptionValue("classpath"));
    }

    if (cli.hasOption('d')) {
      configuration.setTargetDirectory(cli.getOptionValue('d'));
    }

    if (cli.hasOption("encoding")) {
      configuration.setSourceEncoding(cli.getOptionValue("encoding"));
    }

    if (cli.hasOption("basescript")) {
      configuration.setScriptBaseClass(cli.getOptionValue("basescript"));
    }

    // joint compilation parameters
    if (cli.hasOption('j')) {
      Map<String, Object> compilerOptions = new HashMap<String, Object>();

      String[] opts = cli.getOptionValues("J");
      compilerOptions.put("namedValues", opts);

      opts = cli.getOptionValues("F");
      compilerOptions.put("flags", opts);

      configuration.setJointCompilationOptions(compilerOptions);
    }

    if (cli.hasOption("indy")) {
      configuration.getOptimizationOptions().put("int", false);
      configuration.getOptimizationOptions().put("indy", true);
    }

    if (cli.hasOption("configscript")) {
      String path = cli.getOptionValue("configscript");
      File groovyConfigurator = new File(path);
      Binding binding = new Binding();
      binding.setVariable("configuration", configuration);

      CompilerConfiguration configuratorConfig = new CompilerConfiguration();
      ImportCustomizer customizer = new ImportCustomizer();
      customizer.addStaticStars(
          "org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
      configuratorConfig.addCompilationCustomizers(customizer);

      GroovyShell shell = new GroovyShell(binding, configuratorConfig);
      shell.evaluate(groovyConfigurator);
    }

    return configuration;
  }
Beispiel #15
0
  private static void openAnnotatedJava() {
    // Create list with source code names
    @SuppressWarnings("unchecked")
    Vector<String> myfilelist = new Vector<String>(cmd.getArgList());

    // Table that stores parsed compilation units
    Hashtable<String, CompilationUnit> myjpunitlist = new Hashtable<String, CompilationUnit>();

    // Declare outside, so filename can be used in case of exception.

    // Generate AST with JavaParser
    for (Enumeration<String> e = myfilelist.elements(); e.hasMoreElements(); ) {
      String mysource = "";
      CompilationUnit mycunit = null;

      try {
        // read filename
        mysource = e.nextElement();

        // Compile it with java parser.
        mycunit = JavaParser.parse(new FileInputStream(mysource));

        // Then fix the AST following the JC requirements
        ComplyToJCVisitor myfixervisitor = new ComplyToJCVisitor();
        mycunit = (CompilationUnit) myfixervisitor.visit(mycunit, new Integer(0));

        // creates an input stream and parse it using Java Parser
        myjpunitlist.put(mysource, mycunit);

        if (cmd.hasOption("d")) {
          // ASTDumpVisitor myjpvisitor = new ASTDumpVisitor();
          DumpVisitor myjpvisitor = new DumpVisitor();
          myjpvisitor.visit(myjpunitlist.get(mysource), null);
          System.out.print(myjpvisitor.getSource());
        }
      } catch (com.github.javaparser.ParseException ex) {
        System.out.println("Error: Parsing of Java file failed: " + mysource + ". Exiting...");
        System.exit(1);
      } catch (FileNotFoundException ex) {
        System.out.println("Error: File not found: " + mysource + ". Exiting...");
        System.exit(1);
      }
    }

    // Building internals from Java Compiler
    Context mycontext = new Context();
    JavaCompiler myjcompiler = new JavaCompiler(mycontext);
    JavaFileManager myfilemanager = mycontext.get(JavaFileManager.class);
    // Phase that Javac may go to: Setting code generation
    myjcompiler.shouldStopPolicyIfNoError = CompileState.GENERATE;

    // Table that stores the Java Compiler's ASTs
    List<JCCompilationUnit> ljctreelist = List.<JCCompilationUnit>nil();

    // Convert to Java Parser AST to JCTree AST's
    for (Enumeration<String> e = myjpunitlist.keys(); e.hasMoreElements(); ) {

      // read filename
      String mysource = e.nextElement();

      CompilationUnit myjpunit = myjpunitlist.get(mysource);

      JavaParser2JCTree translator = new JavaParser2JCTree(mycontext);
      AJCCompilationUnit myjctreeunit = (AJCCompilationUnit) translator.visit(myjpunit, myjpunit);

      // Setting additional information for Javac:
      // - Source file. Otherwise it throws a NullPointerException
      myjctreeunit.sourcefile = ((JavacFileManager) myfilemanager).getFileForInput(mysource);

      // Storing in the list
      ljctreelist = ljctreelist.append(myjctreeunit);

      // Debug: Shows how the JCTree AST was generated. Output node types.
      if (cmd.hasOption("d")) {
        try {
          Writer mystdout = new OutputStreamWriter(System.out);
          (new PrintAstVisitor(mystdout, true)).visitTopLevel(myjctreeunit);
          mystdout.flush();
        } catch (Exception z) {
        }
      }
    }

    // Enter (phase I): starting to build symtable
    Enter myenter = Enter.instance(mycontext);
    myenter.main(ljctreelist);
    // Enter (phase II): Finishing to build symtable
    /* MemberEnter mymemberenter = MemberEnter.instance(mycontext);
    mymemberenter.visitTopLevel(myjctreeunit); */

    // Get the todo list generated by Enter phase
    // From now on, the output of a phase is the input of the other.
    Todo mytodo = Todo.instance(mycontext);

    // atrribute: type-checking, name resolution, constant folding
    // flow: deadcode elimination
    // desugar: removes synctactic sugar: inner classes, class literals, assertions, foreachs
    myjcompiler.desugar(myjcompiler.flow(myjcompiler.attribute(mytodo)));

    // generate: produce bytecode or source code. Erases the whole AST
    // myjcompiler.generate(myjcompiler.desugar(myjcompiler.flow(myjcompiler.attribute( mytodo))));

    // Prints the Java program to output files and leave
    for (ListIterator<JCCompilationUnit> i = ljctreelist.listIterator(); i.hasNext(); ) {
      JCCompilationUnit myjctreeunit = i.next();
      try {
        Writer myoutputfile;

        if (cmd.getOptionValue("o") == null) {
          myoutputfile = new FileWriter(FileDescriptor.out);
        } else {
          myoutputfile = new FileWriter(myjctreeunit.sourcefile + ".new");
        }

        (new APretty(myoutputfile, true)).visitTopLevel(myjctreeunit);
        myoutputfile.flush();

      } catch (Exception e) {
        // TODO - Check what to report in case of error.
      }
    }
  }
Beispiel #16
0
 public void testHelp() throws Exception {
   CommandLine getopt = new CommandLine(rp);
   C1 c1 = new C1();
   getopt.execute(c1, "help", new ExtList<String>("c1"));
 }
Beispiel #17
0
  private void parseCmdLine(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption("v", "version", false, "Q2's version");
    options.addOption("d", "deploydir", true, "Deployment directory");
    options.addOption("r", "recursive", false, "Deploy subdirectories recursively");
    options.addOption("h", "help", false, "Usage information");
    options.addOption("C", "config", true, "Configuration bundle");
    options.addOption("e", "encrypt", true, "Encrypt configuration bundle");
    options.addOption("i", "cli", false, "Command Line Interface");
    options.addOption("c", "command", true, "Command to execute");

    try {
      CommandLine line = parser.parse(options, args);
      if (line.hasOption("v")) {
        displayVersion();
        System.exit(0);
      }
      if (line.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("Q2", options);
        System.exit(0);
      }
      if (line.hasOption("c")) {
        cli = new CLI(this, line.getOptionValue("c"), line.hasOption("i"));
      } else if (line.hasOption("i")) cli = new CLI(this, null, true);

      String dir = DEFAULT_DEPLOY_DIR;
      if (line.hasOption("d")) {
        dir = line.getOptionValue("d");
      }
      recursive = line.hasOption("r");
      this.deployDir = new File(dir);
      if (line.hasOption("C")) deployBundle(new File(line.getOptionValue("C")), false);
      if (line.hasOption("e")) deployBundle(new File(line.getOptionValue("e")), true);
    } catch (MissingArgumentException e) {
      System.out.println("ERROR: " + e.getMessage());
      System.exit(1);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  public static void main(String[] args) {
    try {

      // IMPORTANT HINT REGARDING STRING ENCODING
      // in Java all Strings have UTF-8 as default encoding
      // therefore: there are only a few references to UTF-8 encoding in this demo code
      // however, if values are retrieved from a database or another program language is used, then
      // one needs to
      // make sure that the UTF-8 encoding is correctly implemented

      // create CMD line option object
      Options options = new Options();

      // add CMD line options
      options.addOption(
          "o",
          "output-dir",
          true,
          "specify base output directory, if none is specified a new directory will be created in the current path");
      options.addOption(
          "n",
          "number-of-generated-receipts",
          true,
          "specify number of receipts to be randomly generated, 50 is default");
      options.addOption(
          "g",
          "signature-creation-device-cannot-fail",
          false,
          "deactivate glitches in signature-creation-device");
      options.addOption(
          "s",
          "no-signature-certificate-switch",
          false,
          "deactivate switching of signature certificates after 5 receipts");
      options.addOption(
          "t", "no-training-receipts", false, "deactivate random generation of training-receipts");

      /// parse CMD line options
      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse(options, args);

      boolean signatureCreationDeviceAlwaysWorks = cmd.hasOption("g");
      boolean deactivateSignatureCertificateSwitching = cmd.hasOption("s");
      boolean deactivateTrainingReceipts = cmd.hasOption("t");

      String outputParentDirectoryString = cmd.getOptionValue("o");
      if (outputParentDirectoryString == null) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
        outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
      }
      File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
      OUTPUT_PARENT_DIRECTORY.mkdirs();
      System.out.println("Setting workdir to " + OUTPUT_PARENT_DIRECTORY.getAbsolutePath());

      String numberOfReceiptsString = cmd.getOptionValue("n");
      int NUMBER_OF_RECEIPTS = DEFAULT_NUMBER_OF_GENERATED_RECEIPTS;
      if (numberOfReceiptsString != null) {
        NUMBER_OF_RECEIPTS = new Integer(numberOfReceiptsString);
      }

      // TODO add provider independent functionality
      // initialise cryptographic providers
      Security.addProvider(new BouncyCastleProvider());

      // prepare cashbox init parameters
      CashBoxParameters cashBoxParameters = new CashBoxParameters();

      // set parameter for signature certificate switching
      // if > 0 then switch signature certificate after so many signatures
      // this is important for demonstrating the handling of the DEP export format
      // when receipts where signed with multiple signature certificates
      if (deactivateSignatureCertificateSwitching) {
        cashBoxParameters.setChangeSignatureCertificateAfterSoManyReceipts(-1);
      } else {
        cashBoxParameters.setChangeSignatureCertificateAfterSoManyReceipts(10);
      }

      // generate and set random cash box ID ("Kassen-ID")
      // REF TO SPECIFICATION: Detailspezifikation/Abs 4
      String CASH_BOX_ID = "DEMO-CASH-BOX" + Math.round(Math.random() * 1000);
      cashBoxParameters.setCashBoxID(CASH_BOX_ID);

      // set cashbox suite
      // REF TO SPECIFICATION: Detailspezifikation/Abs 2
      // AT0 is used here for demonstration purposes, see Abs 2 for details on AT0
      cashBoxParameters.setRkSuite(RKSuite.R1_AT0);

      // set initial receipt identifier
      // in this demo cashbox integer values are used as receipt identifiers ("Belegnummer"),
      // however the specification does not
      // impose that limit. An arbitrary UTF-8 String could be used, the only requirement is that
      // the same combination of
      // the cashBox ID ("Kassen-ID") and the receipt identifier ("Belegnummer") is NEVER used for
      // more than one receipt
      // using the same multiple times compromises the security of the encrypted turnover value,
      // which might lead
      // to leaked turnover data.
      // REF TO SPECIFICATION: Detailspezifikation/Abs 4, Abs 8, Abs 9, Abs 10
      long initialReceiptIdentifier = Math.round(Math.random() * 1000000);
      cashBoxParameters.setInitialReceiptIdentifier(initialReceiptIdentifier);

      // set DEP module for storing and exporting receipts
      // REF TO SPECIFICATION: Detailspezifikation/Abs 3, 11
      cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());

      // create random AES key for turnover encryption
      // REF TO SPECIFICATION: Detailspezifikation/Abs 4, Abs 8, Abs 9, Abs 10
      cashBoxParameters.setTurnoverKeyAESkey(CashBoxUtils.createAESKey());

      // set up signature module
      // the signature module is composed of an JWS module that create the JSON Web Signature (JWS)
      // and
      // a low level signature module for signing the hash values.
      // REF TO SPECIFICATION: Detailspezifikation/Abs 2, Abs 4, Abs 5, Abs 6

      // JWSModule jwsModule = new OrgBitbucketBcJwsModule();  //requires bouncycastle provider
      JWSModule jwsModule = new ManualJWSModule(); // allows for provider independent use cases
      // set damage flag, which simulates the failure of the signature creation device and the
      // correct handling
      // of this case, obviously this is only suitable for demonstration purposes
      jwsModule.setDamageIsPossible(!signatureCreationDeviceAlwaysWorks);
      jwsModule.setProbabilityOfDamagedSignatureDevice(PROPABILITY_DAMAGED_SIGNATURE_DEVICE);

      jwsModule.setSignatureModule(new DO_NOT_USE_IN_REAL_CASHBOX_DemoSoftwareSignatureModule());
      // jwsModule.setSignatureModule(new PKCS11SignatureModule());

      cashBoxParameters.setJwsModule(jwsModule);

      // set printer module
      // REF TO SPECIFICATION: Detailspezifikation/Abs 12, Abs 13, Abs 14, Abs 15
      PrinterModule printerModule = new SimplePDFPrinterModule();
      cashBoxParameters.setPrinterModule(printerModule);

      // init the cash box with the parameters
      DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

      // init done, start interaction with cashbox
      // create random receipt data that will be handled by the cashbox
      List<RawReceiptData> receipts =
          RandomReceiptGenerator.generateRandomReceipts(NUMBER_OF_RECEIPTS);

      // store first receipt (Startbeleg) in cashbox
      // all taxtype values are set to zero (per default in this demo)
      RawReceiptData firstReceipt = new RawReceiptData();
      demoCashBox.storeReceipt(firstReceipt, false, false);

      // now store the other receipts
      for (RawReceiptData rawReceiptData : receipts) {
        // store receipt within cashbox: (prepare data-to-be-signed, sign with JWS, store signed
        // receipt in DEP)

        // pre-defined chance for a training receipt (just for demo purposes)
        boolean isTrainingReceipt = false;
        if (Math.random() < PROPABILITY_TRAINING_RECEIPT && !deactivateTrainingReceipts) {
          isTrainingReceipt = true;
        }

        // pre-defined chance for a storno receipt
        boolean isStornoReceipt = false;
        if (Math.random() < PROPABILITY_OF_STORNO_RECEIPT) {
          isStornoReceipt = true;
        }
        demoCashBox.storeReceipt(rawReceiptData, isTrainingReceipt, isStornoReceipt);
      }

      // dump machine readable code of receipts (this "code" is used for the QR-codes)
      // REF TO SPECIFICATION: Detailspezifikation/Abs 12
      // dump to File
      File qrCoreRepExportFile = new File(OUTPUT_PARENT_DIRECTORY, "qr-code-rep.txt");
      List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
      PrintWriter writer = new PrintWriter(new FileWriter(qrCoreRepExportFile));
      System.out.println("------------QR-CODE-REP------------");
      for (ReceiptPackage receiptPackage : receiptPackages) {
        System.out.println(receiptPackage.getQRCodeRepresentation());
        writer.println(receiptPackage.getQRCodeRepresentation());
      }
      System.out.println("");
      writer.close();

      // dump OCR code of receipts
      // REF TO SPECIFICATION: Detailspezifikation/Abs 14
      // dump to File
      File ocrCoreRepExportFile = new File(OUTPUT_PARENT_DIRECTORY, "ocr-code-rep.txt");
      writer = new PrintWriter(new FileWriter(ocrCoreRepExportFile));
      System.out.println("------------OCR-CODE-REP------------");
      for (ReceiptPackage receiptPackage : receiptPackages) {
        System.out.println(receiptPackage.getOcrCodeRepresentation());
        writer.println(receiptPackage.getOcrCodeRepresentation());
      }
      System.out.println("");
      writer.close();

      // export DEP from cashbox
      // REF TO SPECIFICATION: Detailspezifikation/Abs 3
      DEPExportFormat depExportFormat = demoCashBox.exportDEP();

      // get JSON rep and dump export format to file/std output
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String exportFormatJSONString = gson.toJson(depExportFormat);
      System.out.println("------------DEP-EXPORT-FORMAT------------");
      System.out.println(exportFormatJSONString);
      System.out.println("");

      // dump DEP export to file
      File depExportFile = new File(OUTPUT_PARENT_DIRECTORY, "dep-export.txt");
      FileOutputStream outputStream = new FileOutputStream(depExportFile);
      outputStream.write(exportFormatJSONString.getBytes());
      outputStream.close();

      // export receipts as PDF (QR-CODE)
      // REF TO SPECIFICATION: Detailspezifikation/Abs 12, Abs 13
      File qrCodeDumpDirectory = new File(OUTPUT_PARENT_DIRECTORY, "qr-code-dir-pdf");
      qrCodeDumpDirectory.mkdirs();
      List<byte[]> printedQRCodeReceipts =
          demoCashBox.printReceipt(receiptPackages, ReceiptPrintType.QR_CODE);
      CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

      // export receipts as PDF (OCR)
      // REF TO SPECIFICATION: Detailspezifikation/Abs 14, Abs 15
      File ocrCodeDumpDirectory = new File(OUTPUT_PARENT_DIRECTORY, "ocr-code-dir-pdf");
      ocrCodeDumpDirectory.mkdirs();
      List<byte[]> printedOCRCodeReceipts =
          demoCashBox.printReceipt(receiptPackages, ReceiptPrintType.OCR);
      CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

      // store signature certificates (so that they can be used for verification purposes)
      // only for demonstration purposes
      List<String> signatureCertificates = new ArrayList<>();
      List<List<String>> certificateChains = new ArrayList<>();
      DEPBelegDump[] belegDumps = depExportFormat.getBelegPackage();
      for (DEPBelegDump depBelegDump : belegDumps) {
        signatureCertificates.add(depBelegDump.getSignatureCertificate());
        certificateChains.add(Arrays.asList(depBelegDump.getCertificateChain()));
      }
      File signatureCertificatesOutputFile =
          new File(OUTPUT_PARENT_DIRECTORY, "signatureCertificates.txt");
      String signatureCertificatesJSON = gson.toJson(signatureCertificates);
      BufferedOutputStream bufferedOutputStream =
          new BufferedOutputStream(new FileOutputStream(signatureCertificatesOutputFile));
      ByteArrayInputStream bIn = new ByteArrayInputStream(signatureCertificatesJSON.getBytes());
      IOUtils.copy(bIn, bufferedOutputStream);
      bufferedOutputStream.close();

      // store certificate chains (so that they can be used for verification purposes)
      // only for demonstration purposes
      File signatureCertificateChainsOutputFile =
          new File(OUTPUT_PARENT_DIRECTORY, "signatureCertificateChains.txt");
      String signatureCertificateChainsJSON = gson.toJson(certificateChains);
      bufferedOutputStream =
          new BufferedOutputStream(new FileOutputStream(signatureCertificateChainsOutputFile));
      bIn = new ByteArrayInputStream(signatureCertificateChainsJSON.getBytes());
      IOUtils.copy(bIn, bufferedOutputStream);
      bufferedOutputStream.close();

      // store AES key as BASE64 String (for demonstration purposes: to allow decryption of turnover
      // value)
      // ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure
      // area
      byte[] aesKey = cashBoxParameters.getTurnoverKeyAESkey().getEncoded();
      String aesKeyBase64 = CashBoxUtils.base64Encode(aesKey, false);
      writer = new PrintWriter(new File(OUTPUT_PARENT_DIRECTORY, "aesKeyBase64.txt"));
      writer.print(aesKeyBase64);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
Beispiel #19
0
	public static String[] ginit(String[] args) {
		if (System.getenv("KONOHA_DEBUG") != null) {
			verboseDebug = true;
			verboseGc = true;
			verboseSugar = true;
			verboseCode = true;
		}
		
		CommandLineParser parser = new BasicParser();
		CommandLine commandLine = null;
		try {
			commandLine = parser.parse(longOptions, args);
		} catch (ParseException e) {
			// TODO
		}
		
		if(commandLine.hasOption("verbose")) {
			verboseDebug = true;
			System.out.println("option vervose");
		}
		if(commandLine.hasOption("verbose:gc")) {
			verboseGc = true;
			System.out.println("option vervose:gc");
		}
		if(commandLine.hasOption("verbose:sugar")) {
			verboseSugar = true;
			System.out.println("option vervose:sugar");
		}
		if(commandLine.hasOption("verbose:code")) {
			verboseCode = true;
			System.out.println("option vervose:code");
		}
		if(commandLine.hasOption("interactive")) {
			interactiveFlag = true;
			System.out.println("option interactive");
		}
		if(commandLine.hasOption("typecheck")) {
			compileonlyFlag = true;
			System.out.println("option typecheck");
		}
		if(commandLine.hasOption("start-with")) {
			startupScript = commandLine.getOptionValue("start-with");
			System.out.println("option start-with");
			System.out.println(" with arg " + startupScript);
		}
		if(commandLine.hasOption("test")) {
			testScript = commandLine.getOptionValue("test");
			System.out.println(" with arg " + testScript);
		}
		if(commandLine.hasOption("test-with")) {
			testScript = commandLine.getOptionValue("test");
			System.out.println(" with arg " + testScript);
		}
		if(commandLine.hasOption("builtin-test")) {
			builtinTest = commandLine.getOptionValue("builtin-test");
			System.out.println(" with arg " + builtinTest);
		}
		return commandLine.getArgs();
	}
  /**
   * Parses the command line arguments and sets the respective fields accordingly. This function
   * sets the input source and target files, the source and target language, the running mode (gb or
   * bb), the additional files required by the GB feature extractor, the rebuild and log options
   *
   * @param args The command line arguments
   */
  public void parseArguments(String[] args) {

    Option help =
        OptionBuilder.withArgName("help")
            .hasArg()
            .withDescription("print project help information")
            .isRequired(false)
            .create("help");

    Option input = OptionBuilder.withArgName("input").hasArgs(3).isRequired(true).create("input");

    Option lang = OptionBuilder.withArgName("lang").hasArgs(2).isRequired(false).create("lang");

    Option feat = OptionBuilder.withArgName("feat").hasArgs(1).isRequired(false).create("feat");

    Option gb =
        OptionBuilder.withArgName("gb")
            .withDescription("GlassBox input files")
            .hasOptionalArgs(2)
            .hasArgs(3)
            .create("gb");

    Option mode =
        OptionBuilder.withArgName("mode")
            .withDescription("blackbox features, glassbox features or both")
            .hasArgs(1)
            .isRequired(true)
            .create("mode");

    Option config =
        OptionBuilder.withArgName("config")
            .withDescription("cofiguration file")
            .hasArgs(1)
            .isRequired(false)
            .create("config");

    Option rebuild = new Option("rebuild", "run all preprocessing tools");
    rebuild.setRequired(false);

    // separate 17 BB from 79 BB
    Option baseline = new Option("baseline", "only 17 baseline feature will be calculated");
    baseline.setRequired(false);

    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    options.addOption(help);
    options.addOption(input);
    options.addOption(mode);
    options.addOption(lang);
    options.addOption(feat);
    options.addOption(gb);
    options.addOption(rebuild);
    options.addOption(config);
    options.addOption(baseline);

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

      if (line.hasOption("config")) {
        resourceManager = new PropertiesManager(line.getOptionValue("config"));
      } else {
        resourceManager = new PropertiesManager();
      }

      if (line.hasOption("input")) {
        // print the value of block-size
        String[] files = line.getOptionValues("input");
        sourceFile = files[0];
        targetFile = files[1];
      }

      if (line.hasOption("lang")) {
        String[] langs = line.getOptionValues("lang");
        sourceLang = langs[0];
        targetLang = langs[1];
      } else {
        sourceLang = resourceManager.getString("sourceLang.default");
        targetLang = resourceManager.getString("targetLang.default");
      }

      if (line.hasOption("gb")) {
        String[] gbOpt = line.getOptionValues("gb");
        for (String s : gbOpt) System.out.println(s);
        if (gbOpt.length > 1) {
          mtSys = MOSES;
          nbestInput = gbOpt[0];
          onebestPhrases = gbOpt[1];
          onebestLog = gbOpt[2];
          gbMode = 1;
        } else {
          File f = new File(gbOpt[0]);
          if (f.isDirectory()) {
            mtSys = IBM;
            wordLattices = gbOpt[0];
            gbMode = 1;
          } else {
            gbMode = 0;
            gbXML = gbOpt[0];
          }
        }
      }

      if (line.hasOption("mode")) {
        String[] modeOpt = line.getOptionValues("mode");
        setMod(modeOpt[0].trim());
        System.out.println(getMod());
        configPath = resourceManager.getString("featureConfig." + getMod());
        System.out.println("feature config:" + configPath);
        featureManager = new FeatureManager(configPath);
      }

      if (line.hasOption("feat")) {
        // print the value of block-size
        features = line.getOptionValue("feat");
        featureManager.setFeatureList(features);
      } else {
        featureManager.setFeatureList("all");
      }

      if (line.hasOption("rebuild")) {
        forceRun = true;
      }

      if (line.hasOption("baseline")) {
        isBaseline = true;
      }

    } catch (ParseException exp) {
      System.out.println("Unexpected exception:" + exp.getMessage());
    }
  }
Beispiel #21
0
  public static void main(String[] args) throws Exception {
    boolean isInteractive = false;
    classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString();
    isJar = (classUrl.indexOf("jar") == 0);
    if (!isJar) {
      System.err.println("Installer can only be run from inside a Myna distribution war file");
      System.exit(1);
    }

    Thread.sleep(1000);

    Console console = System.console();
    String response = null;
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption(
        "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx);
    options.addOption("h", "help", false, "Displays help.");
    options.addOption(
        "w",
        "webroot",
        true,
        "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot);
    options.addOption(
        "l",
        "logfile",
        true,
        "Log file to use. Will be created if it does not exist. Default: ./<context>.log");
    options.addOption(
        "s",
        "servername",
        true,
        "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined");
    // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc.
    // Defaults to DEV" );

    options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port);
    options.addOption(
        "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0");

    options.addOption(
        "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore");
    options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass);
    options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias);

    modeOptions.add("upgrade");
    modeOptions.add("install");
    options.addOption(
        "m",
        "mode",
        true,
        "Mode: one of "
            + modeOptions.toString()
            + ". \n"
            + "\"upgrade\": Upgrades myna installation in webroot and exits. "
            + "\"install\": Unpacks to webroot, and installs startup files");
    options.addOption(
        "u",
        "user",
        true,
        "User to own and run the Myna installation. Only applies to unix installs. Default: nobody");

    HelpFormatter formatter = new HelpFormatter();

    String cmdSyntax = "java -jar myna-X.war -m <mode> [options]";
    try {
      CommandLine line = parser.parse(options, args);
      Option option;
      if (args.length == 0) {
        formatter.printHelp(cmdSyntax, options);
        response = console.readLine("\nContinue with Interactive Install? (y/N)");
        if (response.toLowerCase().equals("y")) {
          isInteractive = true;

        } else System.exit(1);
      }
      // Help
      if (line.hasOption("help")) {
        formatter.printHelp(cmdSyntax, options);
        System.exit(1);
      }
      // mode
      if (line.hasOption("mode")) {
        mode = line.getOptionValue("mode");
        if (!modeOptions.contains(mode)) {
          System.err.println(
              "Invalid Arguments.  Reason: Mode must be in " + modeOptions.toString());
          formatter.printHelp(cmdSyntax, options);
          System.exit(1);
        }
      } else if (isInteractive) {
        option = options.getOption("mode");
        console.printf("\n" + option.getDescription());

        do {
          response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): ");
          if (!response.isEmpty()) mode = response;
        } while (!modeOptions.contains(mode));
      }
      // webroot
      if (line.hasOption("webroot")) {
        webroot = line.getOptionValue("webroot");
      } else if (isInteractive) {
        option = options.getOption("webroot");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): ");
        if (!response.isEmpty()) webroot = response;
      }
      // port
      if (line.hasOption("port")) {
        port = Integer.parseInt(line.getOptionValue("port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): ");
        if (!response.isEmpty()) port = Integer.parseInt(response);
      }
      // context
      if (line.hasOption("context")) {
        webctx = line.getOptionValue("context");

      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("context");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): ");
        if (!response.isEmpty()) webctx = response;
      }
      if (!webctx.startsWith("/")) {
        webctx = "/" + webctx;
      }
      // servername (depends on context)
      if (!webctx.equals("/")) {
        serverName = webctx.substring(1);
      }
      if (line.hasOption("servername")) {
        serverName = line.getOptionValue("servername");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("servername");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): ");
        if (!response.isEmpty()) serverName = response;
      }
      // user
      if (line.hasOption("user")) {
        user = line.getOptionValue("user");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("user");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): ");
        if (!response.isEmpty()) user = response;
      }
      // logfile
      logFile = "myna.log";
      if (!webctx.equals("/")) {
        logFile = webctx.substring(1) + ".log";
      }
      if (line.hasOption("logfile")) {
        logFile = line.getOptionValue("logfile");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("logfile");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): ");
        if (!response.isEmpty()) logFile = response;
      }

      // ssl-port
      if (line.hasOption("ssl-port")) {
        sslPort = Integer.parseInt(line.getOptionValue("ssl-port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ssl-port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): ");
        if (!response.isEmpty()) sslPort = Integer.parseInt(response);
      }
      // ks-pass
      if (line.hasOption("ks-pass")) {
        ksPass = line.getOptionValue("ks-pass");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-pass");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): ");
        if (!response.isEmpty()) ksPass = response;
      }
      // ks-alias
      if (line.hasOption("ks-alias")) {
        ksAlias = line.getOptionValue("ks-alias");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-alias");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): ");
        if (!response.isEmpty()) ksAlias = response;
      }
      // keystore
      String appBase = new File(webroot).getCanonicalPath();
      if (keystore == null) {
        keystore = appBase + "/WEB-INF/myna/myna_keystore";
      }
      if (line.hasOption("keystore")) {
        keystore = line.getOptionValue("keystore");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("keystore");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): ");
        if (!response.isEmpty()) keystore = response;
      }

      javaOpts = line.getArgList();
    } catch (ParseException exp) {
      System.err.println("Invalid Arguments.	Reason: " + exp.getMessage());

      formatter.printHelp(cmdSyntax, options);
      System.exit(1);
    }

    if (isInteractive) {
      System.out.println("\nProceeed with the following settings?:\n");
      System.out.println("mode        = " + mode);
      System.out.println("webroot     = " + webroot);
      if (mode.equals("install")) {
        System.out.println("port        = " + port);
        System.out.println("context     = " + webctx);
        System.out.println("servername  = " + serverName);
        System.out.println("user        = "******"logfile     = " + logFile);
        System.out.println("ssl-port    = " + sslPort);
        System.out.println("ks-pass     = "******"ks-alias    = " + ksAlias);
        System.out.println("keystore    = " + keystore);
      }
      response = console.readLine("Continue? (Y/n)");
      if (response.toLowerCase().equals("n")) System.exit(1);
    }
    File wrFile = new File(webroot);
    webroot = wrFile.toString();
    if (mode.equals("install")) {
      adminPassword = console.readLine("\nCreate an Admin password for this installation: ");
    }
    // unpack myna if necessary
    if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) {
      upgrade(wrFile);
    }

    if (mode.equals("install")) {
      File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties"));
      FileInputStream propertiesFileIS = new FileInputStream(propertiesFile);
      Properties generalProperties = new Properties();
      generalProperties.load(propertiesFileIS);
      propertiesFileIS.close();
      if (!adminPassword.isEmpty()) {
        org.jasypt.util.password.StrongPasswordEncryptor cryptTool =
            new org.jasypt.util.password.StrongPasswordEncryptor();
        generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword));
      }
      generalProperties.setProperty("instance_id", serverName);

      generalProperties.store(
          new java.io.FileOutputStream(propertiesFile), "Myna General Properties");

      String javaHome = System.getProperty("java.home");
      webroot = new File(webroot).getCanonicalPath();
      if (serverName.length() == 0) serverName = "myna";
      if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(
                wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd"));

        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName))
                .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot))
                .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile))
                .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome))
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore))
                .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass))
                .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias));

        File scriptFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd"));

        FileUtils.writeStringToFile(scriptFile, initScript);

        // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor();

        System.out.println(
            "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n");
        System.out.println(
            "\nInit script '" + scriptFile + "' created with the following settings:\n");
        System.out.println("memory=256MB");
        System.out.println("serverName=" + serverName);
        System.out.println("javaHome=" + javaHome);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println(
            "\nEdit and and run the command file in " + scriptFile + " to update this service");

      } else {
        String curUser = java.lang.System.getProperty("user.name");
        if (!curUser.equals("root")) {
          System.out.println("Install mode must be run as root.");
          System.exit(1);
        }

        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script"));
        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", serverName)
                .replaceAll("\\{user\\}", user)
                .replaceAll("\\{webroot\\}", webroot)
                .replaceAll("\\{javahome\\}", javaHome)
                .replaceAll("\\{logfile\\}", logFile)
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", keystore)
                .replaceAll("\\{ksPass\\}", ksPass)
                .replaceAll("\\{ksAlias\\}", ksAlias);

        File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName));

        FileUtils.writeStringToFile(scriptFile, initScript);

        if (new File("/etc/init.d").exists()) {

          exec("chown  -R " + user + " " + webroot);
          exec("chown root " + scriptFile.toString());
          exec("chmod 700 " + scriptFile.toString());
          exec("cp " + scriptFile.toString() + " /etc/init.d/");

          System.out.println(
              "\nInit script '/etc/init.d/"
                  + serverName
                  + "' created with the following settings:\n");
        } else {
          System.out.println(
              "\nInit script '" + scriptFile + "' created with the following settings:\n");
        }

        System.out.println("user="******"memory=256MB");
        System.out.println("server=" + serverName);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println("\nEdit this file to customize startup behavior");
      }
    }
  }
  public static void main(String[] args) {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
      logConfig = "log-config.txt";
    }

    Options options = new Options();
    options.addOption("h", "help", false, "print this message");
    options.addOption("v", "version", false, "output version information and exit");
    options.addOption(OptionBuilder.withDescription("trace mode").withLongOpt("trace").create());
    options.addOption(OptionBuilder.withDescription("debug mode").withLongOpt("debug").create());
    options.addOption(OptionBuilder.withDescription("info mode").withLongOpt("info").create());
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the labelled training set in tabular format (reference annotation)")
            .isRequired()
            .withLongOpt("labelled")
            .create("l"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated unlabelled training set in tabular format (one sentence per line, including id)")
            .isRequired()
            .withLongOpt("unlabelled")
            .create("u"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated roles (phrase table: source language \\t target language)")
            .isRequired()
            .withLongOpt("roles")
            .create("r"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file in which to write the translated labelled training set in tabular format (aligned with the reference annotation)")
            .isRequired()
            .withLongOpt("output")
            .create("o"));
    options.addOption(
        OptionBuilder.withArgName("int")
            .hasArg()
            .withDescription("example from which to start from")
            .withLongOpt("start")
            .create());

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = null;

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

      Properties defaultProps = new Properties();
      try {
        defaultProps.load(new InputStreamReader(new FileInputStream(logConfig), "UTF-8"));
      } catch (Exception e) {
        defaultProps.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
        defaultProps.setProperty(
            "log4j.appender.stdout.layout.ConversionPattern", "[%t] %-5p (%F:%L) - %m %n");
        defaultProps.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
        defaultProps.setProperty("log4j.appender.stdout.Encoding", "UTF-8");
      }

      if (commandLine.hasOption("trace")) {
        defaultProps.setProperty("log4j.rootLogger", "trace,stdout");
      } else if (commandLine.hasOption("debug")) {
        defaultProps.setProperty("log4j.rootLogger", "debug,stdout");
      } else if (commandLine.hasOption("info")) {
        defaultProps.setProperty("log4j.rootLogger", "info,stdout");
      } else {
        if (defaultProps.getProperty("log4j.rootLogger") == null) {
          defaultProps.setProperty("log4j.rootLogger", "info,stdout");
        }
      }
      PropertyConfigurator.configure(defaultProps);

      if (commandLine.hasOption("help") || commandLine.hasOption("version")) {
        throw new ParseException("");
      }

      File labelled = new File(commandLine.getOptionValue("labelled"));
      File unlabelled = new File(commandLine.getOptionValue("unlabelled"));
      File roles = new File(commandLine.getOptionValue("roles"));
      File output = new File(commandLine.getOptionValue("output"));
      try {
        if (commandLine.hasOption("start")) {
          int start = Integer.parseInt(commandLine.getOptionValue("start"));
          new AnnotationMigration(labelled, unlabelled, roles, output, start);
        } else {
          new AnnotationMigration(labelled, unlabelled, roles, output);
        }

      } catch (IOException e) {
        logger.error(e);
      }

    } catch (ParseException exp) {
      if (exp.getMessage().length() > 0) {
        System.err.println("Parsing failed: " + exp.getMessage() + "\n");
      }
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(
          200,
          "java -Dfile.encoding=UTF-8 -cp dist/dirha.jar org.fbk.cit.hlt.dirha.AnnotationMigration",
          "\n",
          options,
          "\n",
          true);
      System.exit(1);
    }
  }
Beispiel #23
0
  private void loadArgs(String[] args) throws ParameterProblem {

    logger.debug("Parsing command line arguments");
    final CommandLineParser parser = new PosixParser();

    final Opts opts = new Opts();
    final CommandLine line;
    try {
      line = parser.parse(opts.getOptions(), args);
    } catch (ParseException e) {
      throw new ParameterProblem(e.getMessage(), e);
    }

    // figure action first
    AdminAction theAction = null;
    for (AdminAction a : AdminAction.values()) {
      if (line.hasOption(a.option())) {
        if (theAction == null) {
          theAction = a;
        } else {
          throw new ParameterProblem("You may only specify a single action");
        }
      }
    }

    if (theAction == null) {
      throw new ParameterProblem("You must specify an action");
    }

    this.action = theAction;
    logger.debug("Action: " + theAction);

    // short circuit for --help arg
    if (theAction == AdminAction.Help) {
      return;
    }

    // then action-specific arguments
    if (theAction == AdminAction.AddNodes || theAction == AdminAction.UpdateNodes) {
      this.hosts = parseHosts(line.getOptionValue(theAction.option()));

      if (line.hasOption(Opts.MEMORY)) {
        final String memString = line.getOptionValue(Opts.MEMORY);
        if (memString == null || memString.trim().length() == 0) {
          throw new ParameterProblem("Node memory value is empty");
        }
        this.nodeMemory = parseMemory(memString);
        this.nodeMemoryConfigured = true;
      }

      if (line.hasOption(Opts.NETWORKS)) {
        this.nodeNetworks = line.getOptionValue(Opts.NETWORKS);
      }

      if (line.hasOption(Opts.POOL)) {
        String pool = line.getOptionValue(Opts.POOL);
        if (pool == null || pool.trim().length() == 0) {
          throw new ParameterProblem("Node pool value is empty");
        }
        this.nodePool = pool.trim();
      }

      final boolean active = line.hasOption(Opts.ACTIVE);
      final boolean inactive = line.hasOption(Opts.INACTIVE);

      if (active && inactive) {
        throw new ParameterProblem(
            "You cannot specify both " + Opts.ACTIVE_LONG + " and " + Opts.INACTIVE_LONG);
      }

      if (active) {
        this.nodeActiveConfigured = true;
      }
      if (inactive) {
        this.nodeActive = false;
        this.nodeActiveConfigured = true;
      }

    } else if (theAction == AdminAction.RemoveNodes) {
      this.hosts = parseHosts(line.getOptionValue(theAction.option()));
    } else if (theAction == AdminAction.ListNodes) {
      final String hostArg = line.getOptionValue(AdminAction.ListNodes.option());
      if (hostArg != null) {
        this.hosts = parseHosts(hostArg);
      }
    } else if (theAction == AdminAction.PoolAvailability) {
      if (line.hasOption(Opts.POOL)) {
        final String pool = line.getOptionValue(Opts.POOL);
        if (pool == null || pool.trim().length() == 0) {
          throw new ParameterProblem("Pool name value is empty");
        }
        this.nodePool = pool;
      }
      if (line.hasOption(Opts.FREE)) {
        this.inUse = RemoteNodeManagement.FREE_ENTRIES;
      }
      if (line.hasOption(Opts.USED)) {
        this.inUse = RemoteNodeManagement.USED_ENTRIES;
      }
    }

    // finally everything else
    if (!line.hasOption(Opts.CONFIG)) {
      throw new ParameterProblem(Opts.CONFIG_LONG + " option is required");
    }
    String config = line.getOptionValue(Opts.CONFIG);
    if (config == null || config.trim().length() == 0) {
      throw new ParameterProblem("Config file path is invalid");
    }
    super.configPath = config.trim();

    final boolean batchMode = line.hasOption(Opts.BATCH);
    final boolean json = line.hasOption(Opts.JSON);

    final Reporter.OutputMode mode;
    if (batchMode && json) {
      throw new ParameterProblem(
          "You cannot specify both " + Opts.BATCH_LONG + " and " + Opts.JSON_LONG);
    } else if (batchMode) {
      mode = Reporter.OutputMode.Batch;
    } else if (json) {
      mode = Reporter.OutputMode.Json;
    } else {
      mode = Reporter.OutputMode.Friendly;
    }

    final String[] fields;
    if (line.hasOption(Opts.REPORT)) {
      fields = parseFields(line.getOptionValue(Opts.REPORT), theAction);
    } else {
      fields = theAction.fields();
    }

    String delimiter = null;
    if (line.hasOption(Opts.DELIMITER)) {
      delimiter = line.getOptionValue(Opts.DELIMITER);
    }

    this.reporter = new Reporter(mode, fields, delimiter);

    if (line.hasOption(Opts.OUTPUT)) {
      final String filename = line.getOptionValue(Opts.OUTPUT);
      final File f = new File(filename);
      try {
        this.outStream = new FileOutputStream(f);
      } catch (FileNotFoundException e) {
        throw new ParameterProblem(
            "Specified output file could not be opened for writing: " + f.getAbsolutePath(), e);
      }
    } else {
      this.outStream = System.out;
    }

    final List leftovers = line.getArgList();
    if (leftovers != null && !leftovers.isEmpty()) {
      throw new ParameterProblem(
          "There are unrecognized arguments, check -h to make "
              + "sure you are doing the intended thing: "
              + leftovers.toString());
    }
  }