Ejemplo n.º 1
0
  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);
  }
Ejemplo n.º 2
0
  private static boolean setOptions(String[] lcommand) {

    Options loptions = new Options();
    loptions.addOption(new Option("d", "debug", false, "print debug information (highly verbose)"));
    loptions.addOption(new Option("o", "stdout", false, "print output files to standard output"));
    loptions.addOption(new Option("w", "warning", false, "print warning messages"));

    CommandLineParser clparser = new PosixParser();
    try {
      cmd = clparser.parse(loptions, lcommand);
    } catch (org.apache.commons.cli.ParseException e) {
      String mytoolcmd = "java -jar stave.jar";
      String myoptlist = " <options> <source files>";
      String myheader = "Convert JavaParser's AST to OpenJDK's AST";
      String myfooter = "More info: https://github.com/pcgomes/javaparser2jctree";

      HelpFormatter formatter = new HelpFormatter();
      // formatter.printUsage( new PrintWriter(System.out,true), 100, "java -jar synctask.jar",
      // loptions );
      // formatter.printHelp( mytoolcmd + myoptlist, myheader, loptions, myfooter, false);
      formatter.printHelp(mytoolcmd + myoptlist, loptions, false);
      return (false);
    }

    return (true);
  }
Ejemplo n.º 3
0
/*	public static String optarg; //TODO import gnu.getopt.Getopt; in ginit()
	public static int optind; //TODO import gnu.getopt.Getopt; in ginit();
	//TODO make long_options(struct)
	private static String[] long_options = { "verbose", "verbose:gc", "verbose:sugar", 
								"verbose:code", "interactive", "typecheck", 
								"start-with", "test", "test-with", "builtin-test", "NULL" };
*/	
	static {
		longOptions = new Options();
		longOptions.addOption(null, "verbose", false, null);
		longOptions.addOption(null, "verbose:gc", false, null);
		longOptions.addOption(null, "verbose:sugar", false, null);
		longOptions.addOption(null, "verbose:code", false, null);
		longOptions.addOption("i", "interactive", false, null);
		longOptions.addOption("c", "typecheck", false, null);
		longOptions.addOption("S", "start-with", true, null);
		longOptions.addOption("T", "test", true, null);
		longOptions.addOption("T", "test-with", true, null);
		longOptions.addOption("B", "builtin-test", true, null);
	}
Ejemplo n.º 4
0
  public static void main(String[] args) {

    String formatstr = "ws [--in][--out][--dd][--sw][-h]";
    Options opt = new Options();
    // opt.addOption(OptionBuilder.withArgName("in").hasArg().withDescription("search for buildfile
    // towards the root of the filesystem and use it").create("O"));
    opt.addOption(
        OptionBuilder.withLongOpt("in")
            .withDescription("file path of those files need to be processed")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("out")
            .withDescription("file path to store result")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("dd")
            .withDescription("file path of dictionary")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("sw")
            .withDescription("file path of stop words")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption("h", "help", false, "print help for the command.");

    if (args.length == 0) {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    } else {
      parse_args(args, formatstr, opt);
    }
  }
Ejemplo n.º 5
0
  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();
    }
  }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
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*/
Ejemplo n.º 8
0
  @SuppressWarnings({"AccessStaticViaInstance"})
  public static Options createCompilationOptions() {
    //
    // Parse the command line

    Options options = new Options();

    options.addOption(
        OptionBuilder.hasArg()
            .withArgName("path")
            .withDescription("Specify where to find the class files - must be first argument")
            .create("classpath"));
    options.addOption(
        OptionBuilder.withLongOpt("classpath")
            .hasArg()
            .withArgName("path")
            .withDescription("Aliases for '-classpath'")
            .create("cp"));
    options.addOption(
        OptionBuilder.withLongOpt("sourcepath")
            .hasArg()
            .withArgName("path")
            .withDescription("Specify where to find the source files")
            .create());
    options.addOption(
        OptionBuilder.withLongOpt("temp")
            .hasArg()
            .withArgName("temp")
            .withDescription("Specify temporary directory")
            .create());
    options.addOption(
        OptionBuilder.withLongOpt("encoding")
            .hasArg()
            .withArgName("encoding")
            .withDescription("Specify the encoding of the user class files")
            .create());
    options.addOption(
        OptionBuilder.hasArg()
            .withDescription("Specify where to place generated class files")
            .create('d'));
    //            options.addOption(OptionBuilder.withLongOpt("strict").withDescription("Turn on
    // strict type safety.").create('s'));
    options.addOption(
        OptionBuilder.withLongOpt("help")
            .withDescription("Print a synopsis of standard options")
            .create('h'));
    options.addOption(
        OptionBuilder.withLongOpt("version").withDescription("Print the version").create('v'));
    options.addOption(
        OptionBuilder.withLongOpt("exception")
            .withDescription("Print stack trace on error")
            .create('e'));
    options.addOption(
        OptionBuilder.withLongOpt("jointCompilation")
            .withDescription("Attach javac compiler to compile .java files")
            .create('j'));
    options.addOption(
        OptionBuilder.withLongOpt("basescript")
            .hasArg()
            .withArgName("class")
            .withDescription("Base class name for scripts (must derive from Script)")
            .create('b'));

    options.addOption(
        OptionBuilder.withArgName("property=value")
            .withValueSeparator()
            .hasArgs(2)
            .withDescription("name-value pairs to pass to javac")
            .create("J"));
    options.addOption(
        OptionBuilder.withArgName("flag")
            .hasArg()
            .withDescription("passed to javac for joint compilation")
            .create("F"));

    options.addOption(
        OptionBuilder.withLongOpt("indy")
            .withDescription("enables compilation using invokedynamic")
            .create());
    options.addOption(
        OptionBuilder.withLongOpt("configscript")
            .hasArg()
            .withDescription("A script for tweaking the configuration options")
            .create());
    return options;
  }
  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();
    }
  }
Ejemplo n.º 10
0
  /**
   * 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());
    }
  }
  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);
    }
  }
Ejemplo n.º 12
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");
      }
    }
  }