public void testCDate() throws ParseException { Date date = new Date(); assertEquals(date, Vba.cDate(date)); assertNull(Vba.cDate(null)); // CInt rounds to the nearest even number try { assertEquals(DateFormat.getDateInstance().parse("Jan 12, 1952"), Vba.cDate("Jan 12, 1952")); assertEquals( DateFormat.getDateInstance().parse("October 19, 1962"), Vba.cDate("October 19, 1962")); assertEquals(DateFormat.getTimeInstance().parse("4:35:47 PM"), Vba.cDate("4:35:47 PM")); assertEquals( DateFormat.getDateTimeInstance().parse("October 19, 1962 4:35:47 PM"), Vba.cDate("October 19, 1962 4:35:47 PM")); } catch (ParseException e) { e.printStackTrace(); fail(); } try { Vba.cDate("Jan, 1952"); fail(); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().indexOf("Jan, 1952") >= 0); } }
// TODO add exception for invalid options private void loadCLO(String[] args) { Options options = new Options(); String[][] clolist = { // {"variable/optionname", "description"}, {"genConfig", "general configuration file location"}, {"inWeightsLoc", "input weights configuration file location"}, {"inDBLoc", "input database file location"}, {"outWeightsLoc", "output weights configuration file location"}, {"outDBLoc", "output database file location"}, {"p3pLocation", "adding to DB: single policy file location"}, {"p3pDirLocation", "adding to DB: multiple policy directory location"}, {"newDB", "create new database in place of old one (doesn't check for existence of old one"}, {"newPolicyLoc", "the policy object to process"}, {"userResponse", "response to specified policy"}, {"userIO", "user interface"}, {"userInit", "initialization via user interface"}, {"policyDB", "PolicyDatabase backend"}, {"cbrV", "CBR to use"}, {"blanketAccept", "automatically accept the user suggestion"}, {"loglevel", "level of things save to the log- see java logging details"}, {"policyDB", "PolicyDatabase backend"}, {"NetworkRType", "Network Resource type"}, {"NetworkROptions", "Network Resource options"}, {"confidenceLevel", "Confidence threshold for consulting a networked resource"}, {"useNet", "use networking options"}, {"loglocation", "where to save the log file"}, {"loglevel", "the java logging level to use. See online documentation for enums."} }; for (String[] i : clolist) { options.addOption(i[0], true, i[1]); } CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error parsing commandline arguments."); e.printStackTrace(); System.exit(3); } /* for(String i : args) { System.err.println(i); } */ for (String[] i : clolist) { if (cmd.hasOption(i[0])) { System.err.println("found option i: " + i); genProps.setProperty(i[0], cmd.getOptionValue(i[0])); } } System.err.println(genProps); }
public Segment(ByteBuf bb, int len, IParse<T> sjparse) { this.len = len; this.sjparse = sjparse; try { value = sjparse.parse(bb, len); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Creates a SessionDescription populated with the information contained within the string * parameter. * * <p>Note: unknown field types should not cause exceptions. * * @param s s - the sdp message that is to be parsed. * @throws SdpParseException SdpParseException - if there is a problem parsing the String. * @return a populated SessionDescription object. */ public SessionDescription createSessionDescription(String s) throws SdpParseException { try { SDPAnnounceParser sdpParser = new SDPAnnounceParser(s); return sdpParser.parse(); } catch (ParseException e) { e.printStackTrace(); throw new SdpParseException(0, 0, "Could not parse message"); } }
@Override public long fromString(String timestamp, String format) { DateFormat formatter = new SimpleDateFormat(format); try { Date date = formatter.parse(timestamp); return date.getTime() / 1000; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0L; }
@Override public void init() { File config_file = new File(configFilePath); try { GraphicConfigurationParser.read(config_file, tower); } catch (ParseException e) { System.out.println("Erreur. Le fichier de configuration contient une erreur syntaxique."); e.printStackTrace(); } System.out.println(configurations.size() + " configuration(s) graphique(s) ont �t� charg�es."); }
/** * Unit testing method * * @param args The args array. */ public static void main(String[] args) { String prop = new String("Block ?x, Block ?y, Car ?z"); GParser p = new GParser(new StringReader(prop)); TParaList v = null; try { v = p.ParaList(); } catch (ParseException ex) { System.out.println("Error Parsing ParaList"); ex.printStackTrace(); return; } System.out.println(v.types); System.out.println(v.vars); }
public void test11457() { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("verbose").create()); String[] args = new String[] {"--verbose"}; CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); assertTrue(cmd.hasOption("verbose")); } catch (ParseException exp) { exp.printStackTrace(); fail("Unexpected Exception: " + exp.getMessage()); } }
public static String getDateTaken(File file) { Directory exifDirectory = getMetaDirectory(file); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); // original format if (exifDirectory != null) { String dateStr = exifDirectory.getString(ExifDirectory.TAG_DATETIME_ORIGINAL); Date date = formatter.parse(dateStr); formatter = new SimpleDateFormat("MM/dd/yyyy"); // desired format return formatter.format(date); } return "no date picture taken info"; } catch (ParseException e) { e.printStackTrace(); } return "error occurred while getting the date"; }
public static void main(String[] args) { Scanner in = new Scanner(System.in); String time = in.next(); // Set format for input and output SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ssa"); SimpleDateFormat out = new SimpleDateFormat("HH:mm:ss"); try { Date inTime = sdf.parse(time); System.out.println(out.format(inTime)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void main(String[] args) { Options options = KeyGenCLI.buildOptions(); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); String service = commandLine.getOptionValue("service"); String key = Crypto.generateAes128KeyWithSeed(service); if (key == null) { throw new Exception("Key was not generated!"); } JSONObject keyObject = new JSONObject(); keyObject.put("name", service); keyObject.put("data", key); System.out.println(String.format("Key: `%s`\n", key)); System.out.println("Key object:"); System.out.println(keyObject.toString()); } catch (MissingOptionException e) { System.out.println("Missing required option(s)!"); helpFormatter.printHelp( "\nKeyGenCLI", "This tool generates a unique key and prints the result.", options, "", true); } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized option!"); helpFormatter.printHelp( "\nKeyGenCLI", "This tool generates a unique key and prints the result.", options, "", true); } catch (ParseException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void run() { while (true) { DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); try { socket.receive(packet); synchronized (messages) { messages.add(new Message(packet.getData())); } } catch (IOException e) { System.err.println("Error while receiving message: " + e.getMessage()); } catch (ParseException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
@Override public long fromString(String timestamp) { // Exige que o fuso horário seja UTC por enquanto: String timezone = "UTC"; int tzk = timestamp.indexOf(timezone); assert tzk >= 0; timestamp = timestamp.substring(0, tzk).trim(); DateFormat formatter = new SimpleDateFormat(DEFAULT_FORMAT); formatter.setTimeZone(TimeZone.getTimeZone(timezone)); try { Date date = formatter.parse(timestamp); return date.getTime() / 1000; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0L; } }
public void testFormatDateTime() { try { Date date = DateFormat.getDateTimeInstance().parse("October 19, 1962 4:35:47 PM"); assertEquals("Oct 19, 1962 4:35:47 PM", Vba.formatDateTime(date)); assertEquals("Oct 19, 1962 4:35:47 PM", Vba.formatDateTime(date, 0)); assertEquals("October 19, 1962", Vba.formatDateTime(date, 1)); assertEquals("10/19/62", Vba.formatDateTime(date, 2)); String datestr = Vba.formatDateTime(date, 3); assertNotNull(datestr); // skip the timezone so this test runs everywhere // in EST, this string is "4:35:47 PM EST" assertTrue(datestr.startsWith("4:35:47 PM")); assertEquals("4:35 PM", Vba.formatDateTime(date, 4)); } catch (ParseException e) { e.printStackTrace(); fail(); } }
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(); } }
public static MatrixNodeI valueOf(SmartMatrix m) { StringBuffer sb = new StringBuffer(); sb.append('['); for (int i = 0; i < m.getDimR(); ++i) { if (i != 0) sb.append(','); sb.append('['); for (int j = 0; j < m.getDimC(); ++j) { if (j != 0) sb.append(','); sb.append(m.getEntry(i, j)); } sb.append(']'); } sb.append(']'); Node r = null; try { r = jep.parse(sb.toString()); } catch (ParseException e) { e.printStackTrace(); } return (MatrixNodeI) r; }
/** * @return a double parsed from the value associated with the given key in the given Properties. * returns "def" in key wasn't found, or if a parsing error occured. If "value" contains a "%" * sign, we use a <code>NumberFormat.getPercentInstance</code> to convert it to a double. */ public static double parseProperty(Properties preferences, String key, double def) { NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor String val = preferences.getProperty(key); if (val == null) return def; if (val.indexOf("%") == -1) { // not in percent format ! try { return Double.parseDouble(val); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return def; } } // else it's a percent format -> parse it try { Number n = formatPercent.parse(val); return n.doubleValue(); } catch (ParseException ex) { ex.printStackTrace(); return def; } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int l = 0; int k = 0; // String carID = request.getParameter("reservation"); String carCategory = request.getParameter("carCategory"); String carID = request.getParameter("carID"); String start_date_string = request.getParameter("startDate"); String end_date_string = request.getParameter("endDate"); // String start_time_string = request.getParameter("startTime"); // String end_time_string = request.getParameter("endTime"); // start_date_string = start_date_string + start_time_string; // end_date_string = end_date_string + end_time_string; PrintWriter out = response.getWriter(); out.println(start_date_string); try { Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse((start_date_string).trim()); Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse((end_date_string).trim()); // Date startDate = new // SimpleDateFormat("yyyy-MM-ddhh:mm").parse((start_date_string).trim()); // Date endDate = new SimpleDateFormat("yyyy-MM-ddhh:mm").parse((end_date_string).trim()); int diffInDays = (int) ((startDate.getTime() - endDate.getTime()) / (1000 * 60 * 60 * 24)); out.print("the difference is these many days: "); out.println(diffInDays); DB db = mongo.getDB("practice"); DBCollection reservations = db.getCollection("reservations"); DBCursor dbCursor = null; dbCursor = reservations.find(); if (!dbCursor.hasNext()) { out.println("Database is empty"); BasicDBObject doc = new BasicDBObject("carCategory", carCategory) .append("carID", carID) .append("start_date_string", start_date_string) .append("end_date_string", end_date_string); reservations.insert(doc); k = 1; } while (dbCursor.hasNext()) { BasicDBObject bobj = (BasicDBObject) dbCursor.next(); String temp_car_id = (bobj.getString("carID")).trim(); if (temp_car_id.equals(carID)) { String start_date_string_db = (bobj.getString("start_date_string")).trim(); String end_date_string_db = (bobj.getString("end_date_string")).trim(); Date startDate_db = new SimpleDateFormat("yyyy-MM-dd").parse((start_date_string_db).trim()); Date endDate_db = new SimpleDateFormat("yyyy-MM-dd").parse((end_date_string_db).trim()); boolean c1 = startDate.after(startDate_db) && startDate.before(endDate_db); // if(c1)out.println("c1 is true"); // else out.println("c1 is not true"); boolean c2 = endDate.after(startDate_db) && endDate.before(endDate_db); // if(c2)out.println("c2 is true"); // else out.println("c2 is not true"); boolean c3 = startDate_db.after(startDate) && startDate_db.before(endDate); // if(c3)out.println("c3 is true"); // else out.println("c3 is not true"); boolean c4 = endDate_db.after(startDate) && endDate_db.before(endDate); // if(c4)out.println("c4 is true"); // else out.println("c4 is not true"); boolean c5 = (c1 || c2 || c3 || c4); if (c5) { l = l + 1; // out.print(l); // out.println("th loop"); } } } if (l > 0) { out.println("reservation not possible"); } if ((l == 0) && (k == 0)) { BasicDBObject doc = new BasicDBObject("carID", carID) .append("start_date_string", start_date_string) .append("end_date_string", end_date_string); reservations.insert(doc); } } catch (ParseException e) { e.printStackTrace(); } // BasicDBObject query = new BasicDBObject(); // query.put("username", n); // query.put("password", p); // // If the collection does not exists, MongoDB will create it for you // DBCollection loindet = db.getCollection("loindet"); // // collection selected successfully. // DBCursor cursor = loindet.find(query); // //int cnt = 0; // int cnt = loindet.find(query).count(); // if(cnt!=0) // { // PrintWriter out = response.getWriter(); // //out.println("okay"); // HttpSession session = request.getSession(); // session.setAttribute( "sUserName", n ); // response.sendRedirect("index.jsp"); // } // if(cnt == 0) // { // response.sendRedirect("login.jsp"); // } } catch (MongoException e) { e.printStackTrace(); } }
public static void main(String[] args) { Options options = new Options(); options.addOption("h", false, "Print this help"); options.addOption("t", false, "Test mode. Doesn't write anything to the database."); options.addOption("v", false, "Verbose mode. Use if you like lots of tasty output."); Option metadataFileOption = OptionBuilder.withArgName("file") .hasArg() .withDescription("Process multiple reports using a StatsDB metadata table file") .create("m"); options.addOption(metadataFileOption); Option inputFileOption = OptionBuilder.withArgName("file") .hasArg() .withDescription("Use given input report file") .create("f"); options.addOption(inputFileOption); Option parserTypeOption = OptionBuilder.withArgName("fastqc,other") .hasArg() .withDescription("Use specified parser type") .create("p"); options.addOption(parserTypeOption); Option runNameOption = OptionBuilder.withArgName("run") .hasArg() .withDescription("Associate the report with a given run name") .create("r"); options.addOption(runNameOption); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("statsdb.jar", options); } QcReportParser<File> qcParser = null; if (line.hasOption("p")) { String parserType = line.getOptionValue("p"); if ("".equals(parserType) || "fastqc".equals(parserType)) { qcParser = new FastQCReportParser(); } else if ("other".equals(parserType)) { log.error("Unsupported option 'other'. Please specify a parser type."); System.exit(1); } } else { log.info("No parser type specified. Using FASTQC as the default report type."); qcParser = new FastQCReportParser(); } List<QCAnalysis> qcas = new ArrayList<>(); if (line.hasOption("m")) { File inputfile = new File(line.getOptionValue("m")); if (!inputfile.exists()) { log.error("No input metadata file specified."); System.exit(1); } else { AnalysisMetadataParser amp = new AnalysisMetadataParser(); List<QCAnalysis> pqcas = amp.parseMetadataFile(inputfile); for (QCAnalysis pqca : pqcas) { try { String path = pqca.getProperty("path_to_analysis"); File reportFileToParse = new File(path); if (reportFileToParse.exists()) { qcParser.parseReport(reportFileToParse, pqca); } } catch (QCAnalysisException e) { log.error( "Cannot use metadata file - no property 'path_to_analysis' available. For each report line, this " + "should point to the file path where the report file is located."); System.exit(1); } } qcas.addAll(pqcas); } } else if (line.hasOption("f")) { File inputfile = new File(line.getOptionValue("f")); if (!inputfile.exists()) { log.error("No input report file specified."); System.exit(1); } else { QCAnalysis qca = new DefaultQCAnalysis(); if (line.hasOption("r")) { qca.addProperty("run", line.getOptionValue("r")); } else { log.warn( "No run name specified. Parsed report metrics will only be queryable on raw read filename."); } qcParser.parseReport(inputfile, qca); qcas.add(qca); } } else { log.error("No input metadata or report file specified."); System.exit(1); } for (QCAnalysis qca : qcas) { if (line.hasOption("v")) { log.info("Parsed general values:"); for (Map.Entry<String, String> p : qca.getGeneralValues().entrySet()) { log.info("\t\\_ " + p.getKey() + ":" + p.getValue()); } log.info("Parsed partition values:"); for (PartitionValue p : qca.getPartitionValues()) { log.info( "\t\\_ " + p.getKey() + ":" + p.getValue() + ":" + p.getPosition() + ":" + p.getSize()); } log.info("Parsed position values:"); for (PositionValue p : qca.getPositionValues()) { log.info("\t\\_ " + p.getKey() + ":" + p.getValue() + ":" + p.getPosition()); } } if (!line.hasOption("t")) { // write stuff to the database log.info("Writing analysis report to the database:"); try { ApplicationContext context = new ClassPathXmlApplicationContext("db-config.xml"); QCAnalysisStore store = (QCAnalysisStore) context.getBean("qcAnalysisStore"); if (line.hasOption("v")) { store.setVerbose(true); } store.insertAnalysis(qca); log.info("SUCCESS"); } catch (QCAnalysisException e) { log.error("FAIL: Cannot insert analysis into the database: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (DataAccessException e) { log.error("FAIL: Error inserting analysis into the database: " + e.getMessage()); e.printStackTrace(); System.exit(1); } } } } catch (ParseException e) { log.error("Parsing failed. Reason: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (QCAnalysisException e) { log.error("Unable to parse QC report: " + e.getMessage()); e.printStackTrace(); System.exit(1); } 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(); } }
public FormatTestFrame() { JPanel buttonPanel = new JPanel(); okButton = new JButton("Ok"); buttonPanel.add(okButton); add(buttonPanel, BorderLayout.SOUTH); mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(0, 3)); add(mainPanel, BorderLayout.CENTER); JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField.setValue(new Integer(100)); addRow("Number:", intField); JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField2.setValue(new Integer(100)); intField2.setFocusLostBehavior(JFormattedTextField.COMMIT); addRow("Number (Commit behavior):", intField2); JFormattedTextField intField3 = new JFormattedTextField( new InternationalFormatter(NumberFormat.getIntegerInstance()) { protected DocumentFilter getDocumentFilter() { return filter; } }); intField3.setValue(new Integer(100)); addRow("Filtered Number", intField3); JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField4.setValue(new Integer(100)); intField4.setInputVerifier( new InputVerifier() { public boolean verify(JComponent component) { JFormattedTextField field = (JFormattedTextField) component; return field.isEditValid(); } }); addRow("Verified Number:", intField4); JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance()); currencyField.setValue(new Double(10)); addRow("Currency:", currencyField); JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance()); dateField.setValue(new Date()); addRow("Date (default):", dateField); DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT); format.setLenient(false); JFormattedTextField dateField2 = new JFormattedTextField(format); dateField2.setValue(new Date()); addRow("Date (short, not lenient):", dateField2); try { DefaultFormatter formatter = new DefaultFormatter(); formatter.setOverwriteMode(false); JFormattedTextField urlField = new JFormattedTextField(formatter); urlField.setValue(new URL("http://java.sun.com")); addRow("URL:", urlField); } catch (MalformedURLException ex) { ex.printStackTrace(); } try { MaskFormatter formatter = new MaskFormatter("###-##-####"); formatter.setPlaceholderCharacter('0'); JFormattedTextField ssnField = new JFormattedTextField(formatter); ssnField.setValue("078-05-1120"); addRow("SSN Mask:", ssnField); } catch (ParseException ex) { ex.printStackTrace(); } JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter()); ipField.setValue(new byte[] {(byte) 130, 65, 86, 66}); addRow("IP Address:", ipField); pack(); }
/* main method */ public DefaultParam importCommandLine() { /* Assigning Parameter ID to an ascending number */ putParameterID(); /* Assigning parameter descriptions to each parameter ID */ addParameterInfo(); /* need a Object parser of PosixParser class for the function parse of CommandLine class */ PosixParser parser = new PosixParser(); /* print out help information */ HelpParam help = new HelpParam(parameter, parameterMap); /* check each parameter for assignment */ try { long input_limit = -1; int threads = Runtime.getRuntime().availableProcessors(); /* Set Object cl of CommandLine class for Parameter storage */ CommandLine cl = parser.parse(parameter, arguments, true); if (cl.hasOption(HELP)) { help.printStatisticerHelp(); System.exit(0); } if (cl.hasOption(HELP2)) { help.printStatisticerHelp(); System.exit(0); } if (cl.hasOption(VERSION)) { System.exit(0); } /* Checking all parameters */ String value; if ((value = cl.getOptionValue(PARTITIONS)) != null) { param.partitions = Integer.decode(value); } if ((value = cl.getOptionValue(COLUMN)) != null) { param.columns = value; param.columnStart = Integer.decode(value.split("-")[0]); param.columnEnd = Integer.decode(value.split("-")[1]); } else { param.columnStart = Integer.decode(param.columns.split("-")[0]); param.columnEnd = Integer.decode(param.columns.split("-")[1]); } if (cl.hasOption(CACHE)) { param.cache = true; } if ((value = cl.getOptionValue(INPUT_VCF)) != null) { param.inputFqPath = value; } else if ((value = cl.getOptionValue(INPUT_TAB)) != null) { param.inputFqPath = value; } else { help.printStatisticerHelp(); System.exit(0); // throw new IOException("Input file not specified.\nUse -help for list of // options"); } /* not applicable for HDFS and S3 */ /* using TextFileBufferInput for such purpose */ // File inputFastq = new File(param.inputFqPath).getAbsoluteFile(); // if (!inputFastq.exists()){ // err.println("Input query file not found."); // return; // i } if ((value = cl.getOptionValue(OUTPUT_LINE)) != null) { param.outputPath = value; } else { help.printStatisticerHelp(); info.readMessage("Output file not set with -outfile options"); info.screenDump(); System.exit(0); } File outfile = new File(param.outputPath).getAbsoluteFile(); if (outfile.exists()) { info.readParagraphedMessages( "Output file : \n\t" + param.outputPath + "\nalready exists, will be overwrite."); info.screenDump(); Runtime.getRuntime().exec("rm -rf " + param.outputPath); } } catch (IOException e) { // Don`t catch this, NaNaNaNa, U can`t touch this. info.readMessage("Parameter settings incorrect."); info.screenDump(); e.printStackTrace(); System.exit(0); } catch (RuntimeException e) { info.readMessage("Parameter settings incorrect."); info.screenDump(); e.printStackTrace(); System.exit(0); } catch (ParseException e) { info.readMessage("Parameter settings incorrect."); info.screenDump(); e.printStackTrace(); System.exit(0); } return param; }