示例#1
0
文件: Q2.java 项目: rlishtaba/jPOS
 private void tidyFileAway(File f, String extension) {
   File rename = new File(f.getAbsolutePath() + "." + extension);
   while (rename.exists()) {
     rename = new File(rename.getAbsolutePath() + "." + extension);
   }
   getLog()
       .warn(
           "Tidying " + f.getAbsolutePath() + " out of the way, by adding ." + extension,
           "It will be called: "
               + rename.getAbsolutePath()
               + " see log above for detail of problem.");
   f.renameTo(rename);
 }
示例#2
0
文件: Installer.java 项目: suever/CTP
  private void updateLinuxServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      Properties props = new Properties();
      String ctpHome = dir.getAbsolutePath();
      cp.appendln(Color.black, "...CTP_HOME: " + ctpHome);
      ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\");
      props.put("CTP_HOME", ctpHome);
      File javaHome = new File(System.getProperty("java.home"));
      String javaBin = (new File(javaHome, "bin")).getAbsolutePath();
      cp.appendln(Color.black, "...JAVA_BIN: " + javaBin);
      javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\");
      props.put("JAVA_BIN", javaBin);

      File linux = new File(dir, "linux");
      File install = new File(linux, "ctpService-ubuntu.sh");
      cp.appendln(Color.black, "Linux service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      bat = replace(bat, props); // do the substitutions
      bat = bat.replace("\r", "");
      setFileText(install, bat);

      // If this is an ISN installation, put the script in the correct place.
      String osName = System.getProperty("os.name").toLowerCase();
      if (programName.equals("ISN") && !osName.contains("windows")) {
        install = new File(linux, "ctpService-red.sh");
        cp.appendln(Color.black, "ISN service installer:");
        cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
        bat = getFileText(install);
        bat = replace(bat, props); // do the substitutions
        bat = bat.replace("\r", "");
        File initDir = new File("/etc/init.d");
        File initFile = new File(initDir, "ctpService");
        if (initDir.exists()) {
          setOwnership(initDir, "edge", "edge");
          setFileText(initFile, bat);
          initFile.setReadable(true, false); // everybody can read //Java 1.6
          initFile.setWritable(true); // only the owner can write //Java 1.6
          initFile.setExecutable(true, false); // everybody can execute //Java 1.6
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the Linux service ctpService.sh file");
    }
  }
示例#3
0
  private static void index_h(String prefix, File file, IndexWriter indexWriter)
      throws IOException {
    Document doc = null;

    if (file.isDirectory()) {
      File files[] = file.listFiles();
      for (File file1 : files) {
        index_h(prefix + FILE_SEPARATOR + file.getName(), file1, indexWriter);
      }
    } else {
      String content = FileUtils.readFileToString(file, "utf-8");

      System.out.println("==============================================================");
      System.out.println("index_h " + content);
      System.out.println("==============================================================");

      String filename = prefix + FILE_SEPARATOR + file.getName();
      String path = file.getAbsolutePath();

      doc = new Document();
      doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED));
      doc.add(new Field("relative_path", filename, Field.Store.YES, Field.Index.NOT_ANALYZED));
      indexWriter.addDocument(doc);
    }
  }
示例#4
0
文件: Installer.java 项目: suever/CTP
  private void updateWindowsServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      File windows = new File(dir, "windows");
      File install = new File(windows, "install.bat");
      cp.appendln(Color.black, "Windows service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      Properties props = new Properties();
      String home = dir.getAbsolutePath();
      cp.appendln(Color.black, "...home: " + home);
      home = home.replaceAll("\\\\", "\\\\\\\\");
      props.put("home", home);

      bat = replace(bat, props);
      setFileText(install, bat);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the windows service install.barfile.");
    }
  }
示例#5
0
文件: Q2.java 项目: rlishtaba/jPOS
 private void initSystemLogger() {
   File loggerConfig = new File(deployDir, LOGGER_CONFIG);
   if (loggerConfig.canRead()) {
     hasSystemLogger = true;
     try {
       register(loggerConfig);
       deploy();
     } catch (Exception e) {
       getLog().warn("init-system-logger", e);
     }
   }
   getLog().info("Q2 started, deployDir=" + deployDir.getAbsolutePath());
 }
示例#6
0
文件: Q2.java 项目: rlishtaba/jPOS
 private boolean scan() {
   boolean rc = false;
   File file[] = deployDir.listFiles(this);
   // Arrays.sort (file); --apr not required - we use TreeMap
   if (file == null) {
     // Shutting down might be best, how to trigger from within?
     throw new Error("Deploy directory \"" + deployDir.getAbsolutePath() + "\" is not available");
   } else {
     for (File f : file) {
       if (register(f)) rc = true;
     }
   }
   return rc;
 }
示例#7
0
文件: Installer.java 项目: suever/CTP
 // Get the installer program file by looking in the user.dir for [programName]-installer.jar.
 private File getInstallerProgramFile() {
   System.out.println("Looking for the installer program file");
   File programFile;
   try {
     programFile =
         new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
   } catch (Exception ex) {
     String name = getProgramName();
     programFile = new File(name + "-installer.jar");
   }
   programFile = new File(programFile.getAbsolutePath());
   if (programFile.exists()) System.out.println("...found " + programFile);
   else {
     System.err.println("...unable to find the program file " + programFile + "\n...exiting.");
     exit();
   }
   return programFile;
 }
示例#8
0
文件: Q2.java 项目: rlishtaba/jPOS
 private long persist(File f, ObjectName name) {
   long deployed = f.lastModified();
   try {
     Element e = (Element) server.getAttribute(name, "Persist");
     if (e != null) {
       XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
       Document doc = new Document();
       e.detach();
       doc.setRootElement(e);
       File tmp = new File(f.getAbsolutePath() + ".tmp");
       FileWriter writer = new FileWriter(tmp);
       out.output(doc, writer);
       writer.close();
       f.delete();
       tmp.renameTo(f);
       deployed = f.lastModified();
     }
   } catch (Exception ex) {
     log.warn("persist", ex);
   }
   return deployed;
 }
 /**
  * runs the part of speech tagger
  *
  * @param file input file
  * @param lang language
  * @param type source or target
  * @return path to the output file of the POS tagger
  */
 public String runPOS(String file, String lang, String type) {
   String posName = resourceManager.getString(lang + ".postagger");
   String langResPath = input + File.separator + lang;
   File f = new File(file);
   String absoluteSourceFilePath = f.getAbsolutePath();
   String fileName = f.getName();
   String relativeFilePath = langResPath + File.separator + fileName + ".pos";
   String absoluteOutputFilePath = (new File(relativeFilePath)).getAbsolutePath();
   String posSourceTaggerPath = resourceManager.getString(lang + ".postagger.exePath");
   String outPath = "";
   try {
     Class c = Class.forName(posName);
     PosTagger tagger = (PosTagger) c.newInstance();
     tagger.setParameters(
         type, posName, posSourceTaggerPath, absoluteSourceFilePath, absoluteOutputFilePath);
     PosTagger.ForceRun(forceRun);
     outPath = tagger.run();
   } catch (Exception e) {
     e.printStackTrace();
   }
   // returns the path of the output file; this is for convenience only so
   // we do't have to calculate it again
   return outPath;
 }
示例#10
0
文件: Installer.java 项目: suever/CTP
  /**
   * Class constructor; creates a new Installer object, displays a JFrame introducing the program,
   * allows the user to select an install directory, and copies files from the jar into the
   * directory.
   */
  public Installer(String args[]) {
    // Inputs are --install-dir INSTALL_DIR
    for (int k = 0; k < args.length; k = k + 2) {

      switch (args[k]) {
        case "--install-dir":
          directory = new File(args[k + 1]);
          System.out.println(directory);
          break;
        case "--port":
          port = Integer.parseInt(args[k + 1]);
          break;
      }
    }

    cp = new Stream();

    // Find the installer program so we can get to the files.
    installer = getInstallerProgramFile();
    String name = installer.getName();
    programName = (name.substring(0, name.indexOf("-"))).toUpperCase();

    // Get the installation information
    thisJava = System.getProperty("java.version");
    thisJavaBits = System.getProperty("sun.arch.data.model") + " bits";

    // Find the ImageIO Tools and get the version
    String javaHome = System.getProperty("java.home");
    File extDir = new File(javaHome);
    extDir = new File(extDir, "lib");
    extDir = new File(extDir, "ext");
    File clib = getFile(extDir, "clibwrapper_jiio", ".jar");
    File jai = getFile(extDir, "jai_imageio", ".jar");
    imageIOTools = (clib != null) && clib.exists() && (jai != null) && jai.exists();
    if (imageIOTools) {
      Hashtable<String, String> jaiManifest = getManifestAttributes(jai);
      imageIOVersion = jaiManifest.get("Implementation-Version");
    }

    // Get the CTP.jar parameters
    Hashtable<String, String> manifest = getJarManifestAttributes("/CTP/libraries/CTP.jar");
    programDate = manifest.get("Date");
    buildJava = manifest.get("Java-Version");

    // Get the util.jar parameters
    Hashtable<String, String> utilManifest = getJarManifestAttributes("/CTP/libraries/util.jar");
    utilJava = utilManifest.get("Java-Version");

    // Get the MIRC.jar parameters (if the plugin is present)
    Hashtable<String, String> mircManifest = getJarManifestAttributes("/CTP/libraries/MIRC.jar");
    if (mircManifest != null) {
      mircJava = mircManifest.get("Java-Version");
      mircDate = mircManifest.get("Date");
      mircVersion = mircManifest.get("Version");
    }

    // Set up the installation information for display
    if (imageIOVersion.equals("")) {
      imageIOVersion = "<b><font color=\"red\">not installed</font></b>";
    } else if (imageIOVersion.startsWith("1.0")) {
      imageIOVersion = "<b><font color=\"red\">" + imageIOVersion + "</font></b>";
    }
    if (thisJavaBits.startsWith("64")) {
      thisJavaBits = "<b><font color=\"red\">" + thisJavaBits + "</font></b>";
    }
    boolean javaOK = (thisJava.compareTo(buildJava) >= 0);
    javaOK &= (thisJava.compareTo(utilJava) >= 0);
    javaOK &= (thisJava.compareTo(mircJava) >= 0);
    if (!javaOK) {
      thisJava = "<b><font color=\"red\">" + thisJava + "</font></b>";
    }

    if (directory == null) exit();

    // Point to the parent of the directory in which to install the program.
    // so the copy process works correctly for directory trees.
    //
    // If the user has selected a directory named "CTP",
    // then assume that this is the directory in which
    // to install the program.
    //
    // If the directory is not CTP, see if it is called "RSNA" and contains
    // the Launcher program, in which case we can assume that it is an
    // installation that was done with Bill Weadock's all-in-one installer for Windows.
    //
    // If neither of those cases is true, then this is already the parent of the
    // directory in which to install the program
    if (directory.getName().equals("CTP")) {
      directory = directory.getParentFile();
    } else if (directory.getName().equals("RSNA")
        && (new File(directory, "Launcher.jar")).exists()) {
      suppressFirstPathElement = true;
    }

    // Cleanup old releases
    cleanup(directory);

    // Get a port for the server.
    if (port < 0) {
      if (checkServer(-port, false)) {
        System.err.println(
            "CTP appears to be running.\nPlease stop CTP and run the installer again.");
        System.exit(0);
      }
    }

    // Now install the files and report the results.
    int count =
        unpackZipFile(installer, "CTP", directory.getAbsolutePath(), suppressFirstPathElement);
    if (count > 0) {
      // Create the service installer batch files.
      updateWindowsServiceInstaller();
      updateLinuxServiceInstaller();

      // If this was a new installation, set up the config file and set the port
      installConfigFile(port);

      // Make any necessary changes in the config file to reflect schema evolution
      fixConfigSchema();

      System.out.println("Installation complete.");
      System.out.println(programName + " has been installed successfully.");
      System.out.println(count + " files were installed.");
    } else {
      System.err.println("Installation failed.");
      System.err.println(programName + " could not be fully installed.");
    }
    if (!programName.equals("ISN") && startRunner(new File(directory, "CTP"))) System.exit(0);
  }
  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();
    }
  }
示例#12
0
文件: Q2.java 项目: rlishtaba/jPOS
 private void deleteFile(File f, String iuuid) {
   f.delete();
   getLog()
       .info(String.format("Deleted transient descriptor %s (%s)", f.getAbsolutePath(), iuuid));
 }
示例#13
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());
    }
  }