List of usage examples for java.util List size
int size();
From source file:eu.fbk.utils.lsa.util.Anvur.java
public static void main(String[] args) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "log-config.txt"; }/*from w w w . ja va 2s. co m*/ PropertyConfigurator.configure(logConfig); /* if (args.length != 2) { log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir"); System.exit(1); } File l = new File(args[1]); if (!l.exists()) { l.mkdir(); } List<String[]> list = readText(new File(args[0])); String oldCategory = ""; for (int i=0;i<list.size();i++) { String[] s = list.get(i); if (!oldCategory.equals(s[0])) { File f = new File(args[1] + File.separator + s[0]); boolean b = f.mkdir(); logger.debug(f + " created " + b); } File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt"); logger.debug("writing " + g + "..."); PrintWriter pw = new PrintWriter(new FileWriter(g)); //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); if (s.length == 5) { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' '))); } else { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); } pw.flush(); pw.close(); } // end for i */ if (args.length != 7) { System.out.println(args.length); System.out.println( "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n"); System.exit(1); } // DecimalFormat dec = new DecimalFormat("#.00"); File Ut = new File(args[0] + "-Ut"); File Sk = new File(args[0] + "-S"); File r = new File(args[0] + "-row"); File c = new File(args[0] + "-col"); File df = new File(args[0] + "-df"); double threshold = Double.parseDouble(args[1]); int size = Integer.parseInt(args[2]); int dim = Integer.parseInt(args[3]); boolean rescaleIdf = Boolean.parseBoolean(args[4]); //"author_check"0, "authors"1, "title"2, "year"3, "pubtype"4, "publisher"5, "journal"6, "volume"7, "number"8, "pages"9, "abstract"10, "nauthors", "citedby" String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume", "number", "pages", "abstract", "nauthors", "citedby" //author_id authors title year pubtype publisher journal volume number pages abstract nauthors citedby }; String name = buildName(labels, args[6]); File bwf = new File(args[5] + name + "-bow.txt"); PrintWriter bw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8"))); File bdf = new File(args[5] + name + "-bow.csv"); PrintWriter bd = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8"))); File lwf = new File(args[5] + name + "-ls.txt"); PrintWriter lw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8"))); File ldf = new File(args[5] + name + "-ls.csv"); PrintWriter ld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8"))); File blwf = new File(args[5] + name + "-bow+ls.txt"); PrintWriter blw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8"))); File bldf = new File(args[5] + name + "-bow+ls.csv"); PrintWriter bld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8"))); File logf = new File(args[5] + name + ".log"); PrintWriter log = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8"))); //System.exit(0); LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf); LSSimilarity lss = new LSSimilarity(lsm, size); List<String[]> list = readText(new File(args[5])); // author_check authors title year pubtype publisher journal volume number pages abstract nauthors citedby //header for (int i = 0; i < list.size(); i++) { String[] s1 = list.get(i); String t1 = s1[0].toLowerCase(); bw.print("\t"); lw.print("\t"); blw.print("\t"); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); } // end for i bw.print("\n"); lw.print("\n"); blw.print("\n"); for (int i = 0; i < list.size(); i++) { logger.info(i + "\t"); String[] s1 = list.get(i); String t1 = buildText(s1, args[6]); BOW bow1 = new BOW(t1); logger.info(bow1); Vector d1 = lsm.mapDocument(bow1); d1.normalize(); log.println("d1:" + d1); Vector pd1 = lsm.mapPseudoDocument(d1); pd1.normalize(); log.println("pd1:" + pd1); Vector m1 = merge(pd1, d1); log.println("m1:" + m1); // write the orginal line for (int j = 0; j < s1.length; j++) { bd.print(s1[j]); bd.print("\t"); ld.print(s1[j]); ld.print("\t"); bld.print(s1[j]); bld.print("\t"); } // write the bow, ls, and bow+ls vectors bd.println(d1); ld.println(pd1); bld.println(m1); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); for (int j = 0; j < i + 1; j++) { bw.print("\t"); lw.print("\t"); blw.print("\t"); } // end for j for (int j = i + 1; j < list.size(); j++) { logger.info(i + "\t" + j); String[] s2 = list.get(j); String t2 = buildText(s2, args[6]); BOW bow2 = new BOW(t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2); Vector d2 = lsm.mapDocument(bow2); d2.normalize(); log.println("d2:" + d2); Vector pd2 = lsm.mapPseudoDocument(d2); pd2.normalize(); log.println("pd2:" + pd2); Vector m2 = merge(pd2, d2); log.println("m2:" + m2); float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2)); float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2)); float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2)); bw.print("\t"); bw.print(dec.format(cosVSM)); lw.print("\t"); lw.print(dec.format(cosLSM)); blw.print("\t"); blw.print(dec.format(cosBOWLSM)); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM); } bw.print("\n"); lw.print("\n"); blw.print("\n"); } // end for i logger.info("wrote " + bwf); logger.info("wrote " + bwf); logger.info("wrote " + bdf); logger.info("wrote " + lwf); logger.info("wrote " + ldf); logger.info("wrote " + blwf); logger.info("wrote " + bldf); logger.info("wrote " + logf); ld.close(); bd.close(); bld.close(); bw.close(); lw.close(); blw.close(); log.close(); }
From source file:de.unisb.cs.st.javaslicer.slicing.Slicer.java
public static void main(String[] args) throws InterruptedException { Options options = createOptions();// w w w . j av a 2 s .c om CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 2) { printHelp(options, System.err); System.exit(-1); } // ?? 1. ? 2.? File traceFile = new File(additionalArgs[0]); String slicingCriterionString = additionalArgs[1]; Long threadId = null; if (cmdLine.hasOption('t')) { // the interesting thread id for slicing try { threadId = Long.parseLong(cmdLine.getOptionValue('t')); } catch (NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } TraceResult trace; try { trace = TraceResult.readFrom(traceFile); } catch (IOException e) { System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e); System.exit(-1); return; } List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion //slicingCriterionString get from additionalArgs[1] try { sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses()); } catch (IllegalArgumentException e) { System.err.println("Error parsing slicing criterion: " + e.getMessage()); System.exit(-1); return; } List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } // threadID is used to mark the interesting thread ThreadId tracing = null; for (ThreadId t : threads) { if (threadId == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadId.longValue()) { tracing = t; } } if (tracing == null) { System.err.println(threadId == null ? "Couldn't find the main thread." : "The thread you specified was not found."); System.exit(-1); return; } long startTime = System.nanoTime(); Slicer slicer = new Slicer(trace); if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing slicer.addProgressMonitor(new ConsoleProgressMonitor()); boolean multithreaded; if (cmdLine.hasOption("multithreaded")) { String multithreadedStr = cmdLine.getOptionValue("multithreaded"); multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr)); } else { multithreaded = Runtime.getRuntime().availableProcessors() > 1; } boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. slicer.addSliceVisitor(collector); // zhushi by yhb if (warnUntracedMethods) slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!! Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector long endTime = System.nanoTime(); Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution // show the slicing result System.out.println("The dynamic slice for criterion " + sc + ":"); for (Instruction insn : sliceArray) { System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(), insn.getMethod().getName(), insn.getLineNumber(), insn.toString()); } System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); }
From source file:edu.monash.merc.system.parser.GPMDbParser.java
public static void main(String[] arg) throws Exception { String filename = "./testData/human_all_chr.mod.txt"; //String filename = "./testData/nta_hs_all_chr.mod.txt"; //String filename = "./testData/lys_hs_all_chr.mod.txt"; FileInputStream fileInputStream = new FileInputStream(new File(filename)); GPMDbParser parser = new GPMDbParser(); GPMDbBean gpmDbBean = parser.parse(fileInputStream, "utf-8", GPMDbType.GPMDB_LYS); List<GPMDbEntryBean> gpmDbEntryBeans = gpmDbBean.getPgmDbEntryBeans(); for (GPMDbEntryBean gpmDbEntryBean : gpmDbEntryBeans) { AccessionBean identifiedAcBean = gpmDbEntryBean.getIdentifiedAccessionBean(); System.out.println("============== ensp : " + identifiedAcBean.getAccession()); GeneBean geneBean = gpmDbEntryBean.getGeneBean(); System.out.println("================= gene symbol : " + geneBean.getDisplayName() + " desc: " + geneBean.getDescription()); List<DbSourceAcEntryBean> dbSourceAcEntryBeans = gpmDbEntryBean.getDbSourceAcEntryBeans(); for (DbSourceAcEntryBean dbSourceAcEntryBean : dbSourceAcEntryBeans) { AccessionBean accessionBean = dbSourceAcEntryBean.getAccessionBean(); System.out.println("============ accession: " + accessionBean.getAccession() + " type: " + accessionBean.getAcType()); DBSourceBean dbSourceBean = dbSourceAcEntryBean.getDbSourceBean(); System.out.println("============ dbsource: " + dbSourceBean.getDbName()); }/*from w ww . ja v a2 s .c o m*/ List<PTMEvidenceBean> ptmEvidenceBeans = gpmDbEntryBean.getPtmEvidenceBeans(); System.out.println("========== ptm evidence bean size: " + ptmEvidenceBeans.size()); for (PTMEvidenceBean ptmEvidenceBean : ptmEvidenceBeans) { TPBDataTypeBean tpbDataTypeBean = ptmEvidenceBean.getTpbDataTypeBean(); System.out.println("============ tpb data type: " + tpbDataTypeBean.getDataType()); System.out.println("============ pos: " + ptmEvidenceBean.getPos() + " obs: " + ptmEvidenceBean.getEvidenceValue()); System.out.println("============ color : " + ptmEvidenceBean.getColorLevel()); System.out.println("============ hyper link: " + ptmEvidenceBean.getHyperlink()); } if (ptmEvidenceBeans.size() == 0) { System.out.println("============= No peptides found for " + identifiedAcBean.getAccession()); } System.out.println("\n"); } System.out.println("================= total size: " + gpmDbEntryBeans.size()); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // step5-linguistic-annotation/ System.err.println("Starting step 6 HIT Preparation"); File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (outputDir.exists()) { outputDir.delete();// w w w. j a va 2s . c om } outputDir.mkdir(); List<String> queries = new ArrayList<>(); // iterate over query containers int countClueWeb = 0; int countSentence = 0; for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); if (queries.contains(f.getName()) || queries.size() == 0) { // groups contain only non-empty documents Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>(); // split to groups according to number of sentences for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.originalXmi != null) { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class); int groupId = sentences.size() / 40; if (rankedResult.originalXmi == null) { System.err.println("Empty document: " + rankedResult.clueWebID); } else { if (!groups.containsKey(groupId)) { groups.put(groupId, new ArrayList<>()); } } //handle it groups.get(groupId).add(rankedResult); countClueWeb++; } } for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) { Integer groupId = entry.getKey(); List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue(); // make sure the results are sorted // DEBUG // for (QueryResultContainer.SingleRankedResult r : rankedResults) { // System.out.print(r.rank + "\t"); // } Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank)); // iterate over results for one query and group for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) { QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i); QueryResultContainer.SingleRankedResult r = rankedResults.get(i); int rank = r.rank; MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("template/template.html"); String queryId = queryResultContainer.qID; String query = queryResultContainer.query; // make the first letter uppercase query = query.substring(0, 1).toUpperCase() + query.substring(1); List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples; List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples; byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); List<generators.Sentence> sentences = new ArrayList<>(); List<Integer> paragraphs = new ArrayList<>(); paragraphs.add(0); for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) { for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) { String sentenceBegin = String.valueOf(s.getBegin()); generators.Sentence sentence = new generators.Sentence(s.getCoveredText(), sentenceBegin); sentences.add(sentence); countSentence++; } int SentenceID = paragraphs.get(paragraphs.size() - 1); if (sentences.size() > 120) while (SentenceID < sentences.size()) { if (!paragraphs.contains(SentenceID)) paragraphs.add(SentenceID); SentenceID = SentenceID + 120; } paragraphs.add(sentences.size()); } System.err.println("Output dir: " + outputDir); int startID = 0; int endID; for (int j = 0; j < paragraphs.size(); j++) { endID = paragraphs.get(j); int sentLength = endID - startID; if (sentLength > 120 || j == paragraphs.size() - 1) { if (sentLength > 120) { endID = paragraphs.get(j - 1); j--; } sentLength = endID - startID; if (sentLength <= 40) groupId = 40; else if (sentLength <= 80 && sentLength > 40) groupId = 80; else if (sentLength > 80) groupId = 120; File folder = new File(outputDir + "/" + groupId); if (!folder.exists()) { System.err.println("creating directory: " + outputDir + "/" + groupId); boolean result = false; try { folder.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + ".html"; System.err.println("Printing a file: " + newHtmlFile); File newHTML = new File(newHtmlFile); int t = 0; while (newHTML.exists()) { newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html"); t++; } mustache.execute(new PrintWriter(new FileWriter(newHTML)), new generators(query, relevantInformationExamples, irrelevantInformationExamples, sentences.subList(startID, endID), queryId, rank)) .flush(); startID = endID; } } } } } } System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences"); }
From source file:edu.monash.merc.system.parser.xml.HPAWSXmlParser.java
public static void main(String[] art) throws Exception { HPAWSXmlParser parser = new HPAWSXmlParser(); String hpaFileName = "./testData/hpa_chromosome_7.xml"; hpaFileName = "/opt/tpb/db_download/small_hpa.xml"; long startTime = System.currentTimeMillis(); List<HPAEntryBean> hpaEntryBeans = parser.parseHPAXml(hpaFileName, WSXmlInputFactory.getInputFactoryConfiguredForXmlConformance()); long endTime = System.currentTimeMillis(); int i = 0;/*from w w w . j av a 2 s .c o m*/ for (HPAEntryBean hpaEntryBean : hpaEntryBeans) { GeneBean geneBean = hpaEntryBean.getGeneBean(); String version = hpaEntryBean.getHpaVersion(); String engsAc = geneBean.getEnsgAccession(); System.out.println("=========== version: " + version + " - gene name: " + geneBean.getDisplayName() + " accession : " + geneBean.getEnsgAccession()); DBSourceBean primaryDbSource = hpaEntryBean.getPrimaryDbSourceBean(); System.out.println("=========== dbsource name: " + primaryDbSource.getDbName()); List<DbSourceAcEntryBean> dbSourceAcEntryBeans = hpaEntryBean.getDbSourceAcEntryBeans(); for (DbSourceAcEntryBean dbSourceAcEntryBean : dbSourceAcEntryBeans) { DBSourceBean dbSourceBean = dbSourceAcEntryBean.getDbSourceBean(); AccessionBean accessionBean = dbSourceAcEntryBean.getAccessionBean(); System.out.println( "========= ac : " + accessionBean.getAccession() + " db: " + dbSourceBean.getDbName()); } List<PEEvidenceBean> antiEvidenceBeans = hpaEntryBean.getPeAntiIHCNormEvidencesBeans(); if (antiEvidenceBeans != null) { System.out.println("====== total evidences size : " + antiEvidenceBeans.size()); for (PEEvidenceBean peEvidenceBean : antiEvidenceBeans) { System.out.println("========= anti evidence: color - level: " + peEvidenceBean.getColorLevel() + " evidence : " + peEvidenceBean.getEvidenceValue() + " - url : " + peEvidenceBean.getHyperlink()); } } else { System.out.println("There is no evidence for this gene."); } System.out.println(""); } System.out.println("===== total entry size : " + hpaEntryBeans.size()); System.out.println("===== total processing time : " + (endTime - startTime) / 1000 + " seconds."); }
From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java
public static void main(String[] args) { try {// w w w. j a va 2 s . c o m //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 //this demo cashbox does not implement error handling //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible //if an error occurs, only the stacktraces are logged //obviously this needs to be adapted in a productive cashbox //---------------------------------------------------------------------------------------------------- //basic inits //add bouncycastle provider Security.addProvider(new BouncyCastleProvider()); //---------------------------------------------------------------------------------------------------- //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256 if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) { System.out.println( "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files."); System.exit(0); } //---------------------------------------------------------------------------------------------------- //parse cmd line options 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 working directory"); //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)"); options.addOption("v", "verbose", false, "dump demo receipts to cmd line"); options.addOption("c", "closed system", false, "simulate closed system"); ///parse CMD line options CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); //setup inputs from cmd line //verbose VERBOSE = cmd.hasOption("v"); CLOSED_SYSTEM = cmd.hasOption("c"); //output directory 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(); //---------------------------------------------------------------------------------------------------- //external simulation runs... not implemented yet, currently only the internal test suites can be executed //String simulationFileOrDirectoryPath = cmd.getOptionValue("i"); //handling of arbitrary input simulation files will be possible in 0.7 //if (simulationFileOrDirectoryPath == null) { //} else { // File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath); // cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory); //} List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns(); //setup simulation and execute int index = 1; for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) { System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size()); System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel()); index++; File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY, cashboxSimulation.getSimulationRunLabel()); testSetDirectory.mkdirs(); CashBoxParameters cashBoxParameters = new CashBoxParameters(); cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId()); cashBoxParameters.setTurnOverCounterAESKey( CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey())); cashBoxParameters.setDepModul(new SimpleMemoryDEPModule()); cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule()); cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID()); //create pre-defined number of signature devices for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) { JWSModule jwsModule = new ManualJWSModule(); SignatureModule signatureModule; if (!CLOSED_SYSTEM) { signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule( RKSuite.R1_AT100, null); } else { signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule( cashboxSimulation.getCompanyID() + "-" + "K" + i); } jwsModule.setOpenSystemSignatureModule(signatureModule); cashBoxParameters.getJwsSignatureModules().add(jwsModule); } //init cashbox DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters); //exceute simulation run demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList()); //---------------------------------------------------------------------------------------------------- //export DEP DEPExportFormat depExportFormat = demoCashBox.exportDEP(); //get JSON rep and dump export format to file/std output File depExportFile = new File(testSetDirectory, "dep-export.json"); dumpJSONRepOfObject(depExportFormat, depExportFile, true, "------------DEP-EXPORT-FORMAT------------"); //---------------------------------------------------------------------------------------------------- //store signature certificates and AES key (so that they can be used for verification purposes) CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer(); HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>(); cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap); //store AES key as BASE64 String //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey()); List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules(); for (JWSModule jwsSignatureModule : jwsSignatureModules) { CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer(); certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID()); certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(), certificateOrPublicKeyContainer); X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule() .getSigningCertificate(); if (certificate == null) { //must be public key based... (closed system) PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey(); certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey( CashBoxUtils.base64Encode(publicKey.getEncoded(), false)); certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY); } else { certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey( CashBoxUtils.base64Encode(certificate.getEncoded(), false)); certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE); } } File cryptographicMaterialContainerFile = new File(testSetDirectory, "cryptographicMaterialContainer.json"); dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true, "------------CRYPTOGRAPHIC MATERIAL------------"); //---------------------------------------------------------------------------------------------------- //export QR codes to file //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(testSetDirectory, "qr-code-rep.json"); List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts(); List<String> qrCodeRepList = new ArrayList<>(); for (ReceiptPackage receiptPackage : receiptPackages) { qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation( receiptPackage.getJwsCompactRepresentation())); } dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true, "------------QR-CODE-REP------------"); //---------------------------------------------------------------------------------------------------- //export OCR codes to file //dump machine readable code of receipts (this "code" is used for the OCR-codes) //REF TO SPECIFICATION: Detailspezifikation/Abs 14 //dump to File File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json"); List<String> ocrCodeRepList = new ArrayList<>(); for (ReceiptPackage receiptPackage : receiptPackages) { ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation( receiptPackage.getJwsCompactRepresentation())); } dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true, "------------OCR-CODE-REP------------"); //---------------------------------------------------------------------------------------------------- //create PDF receipts and print to directory //REF TO SPECIFICATION: Detailspezifikation/Abs 12 File qrCodeDumpDirectory = new File(testSetDirectory, "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 File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf"); ocrCodeDumpDirectory.mkdirs(); List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages, ReceiptPrintType.OCR); CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory); //---------------------------------------------------------------------------------------------------- //dump executed testsuite File testSuiteDumpFile = new File(testSetDirectory, cashboxSimulation.getSimulationRunLabel() + ".json"); dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true, "------------CASHBOX Simulation------------"); } } catch (CertificateEncodingException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java
public static void main(String[] args) { if (args.length != 4) { System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n" + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n" + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n"); } else {//from w w w . j a va2s.c o m BufferedWriter outBuff = null; try { File inFile = new File(args[0]); File fastaFile = new File(args[1]); File outFile = new File(args[2]); File blastFile = new File(args[3]); //Primero cargo todos los datos del archivo xml del blast BufferedReader buffReader = new BufferedReader(new FileReader(blastFile)); StringBuilder stBuilder = new StringBuilder(); String line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); System.out.println("Creating blastoutput..."); BlastOutput blastOutput = new BlastOutput(stBuilder.toString()); System.out.println("BlastOutput created! :)"); stBuilder.delete(0, stBuilder.length()); HashMap<String, String> blastProteinsMap = new HashMap<String, String>(); ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations(); for (Iteration iteration : iterations) { blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString()); } //freeing some memory blastOutput = null; //------------------------------------------------------------------------ //Initializing writer for output file outBuff = new BufferedWriter(new FileWriter(outFile)); //reading gene annotation xml file..... buffReader = new BufferedReader(new FileReader(inFile)); stBuilder = new StringBuilder(); line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); XMLElement genesXML = new XMLElement(stBuilder.toString()); //freeing some memory I don't need anymore stBuilder.delete(0, stBuilder.length()); //reading file with the reference proteins set ArrayList<String> proteinsReferenceSet = new ArrayList<String>(); buffReader = new BufferedReader(new FileReader(fastaFile)); while ((line = buffReader.readLine()) != null) { if (line.charAt(0) == '>') { proteinsReferenceSet.add(line.split("\\|")[1]); } } buffReader.close(); Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME); List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME); System.out.println("There are " + contigs.size() + " contigs to be checked... "); outBuff.write("There are " + contigs.size() + " contigs to be checked... \n"); outBuff.write("Proteins reference set: \n"); for (String st : proteinsReferenceSet) { outBuff.write(st + ","); } outBuff.write("\n"); for (Element elem : contigs) { ContigXML contig = new ContigXML(elem); //escribo el id del contig en el que estoy outBuff.write("Checking contig: " + contig.getId() + "\n"); outBuff.flush(); List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME); System.out.println("geneList.size() = " + geneList.size()); int numeroDeGenesParaAnalizar = geneList.size() / FACTOR; if (numeroDeGenesParaAnalizar == 0) { numeroDeGenesParaAnalizar++; } ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>(); outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: " + numeroDeGenesParaAnalizar + "\n"); for (int j = 0; j < numeroDeGenesParaAnalizar; j++) { int geneIndex; boolean geneIsDismissed = false; do { geneIsDismissed = false; geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size())); PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) { geneIsDismissed = true; } } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed); indicesUtilizados.add(geneIndex); System.out.println("geneIndex = " + geneIndex); //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: " + gene.getAnnotationUniprotId() + "\n"); outBuff.write("eValue: " + gene.getEvalue() + "\n"); //--------------PETICION POST HTTP BLAST---------------------- PostMethod post = new PostMethod(BLAST_URL); post.addParameter("program", "blastx"); post.addParameter("sequence", gene.getSequence()); post.addParameter("database", "uniprotkb"); post.addParameter("email", "ppareja@era7.com"); post.addParameter("exp", "1e-10"); post.addParameter("stype", "dna"); // execute the POST HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("status post = " + status); InputStream inStream = post.getResponseBodyAsStream(); String fileName = "jobid.txt"; FileOutputStream outStream = new FileOutputStream(new File(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); String jobId = buffReader.readLine(); buffReader.close(); System.out.println("jobId = " + jobId); //--------------HTTP CHECK JOB STATUS REQUEST---------------------- GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId); String jobStatus = ""; do { try { Thread.sleep(1000);//sleep for 1000 ms } catch (InterruptedException ie) { //If this thread was intrrupted by nother thread } status = client.executeMethod(get); //System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobStatus.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); jobStatus = buffReader.readLine(); //System.out.println("jobStatus = " + jobStatus); buffReader.close(); } while (!jobStatus.equals(FINISHED_JOB_STATUS)); //Once I'm here the blast should've already finished //--------------JOB RESULTS HTTP REQUEST---------------------- get = new GetMethod(JOB_RESULT_URL + jobId + "/out"); status = client.executeMethod(get); System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobResults.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //--------parsing the blast results file----- TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>(); buffReader = new BufferedReader(new FileReader(new File(fileName))); while ((line = buffReader.readLine()) != null) { if (line.length() > 3) { String prefix = line.substring(0, 3); if (prefix.equals("TR:") || prefix.equals("SP:")) { String[] columns = line.split(" "); String id = columns[1]; //System.out.println("id = " + id); String e = ""; String[] arraySt = line.split("\\.\\.\\."); if (arraySt.length > 1) { arraySt = arraySt[1].trim().split(" "); int contador = 0; for (int k = 0; k < arraySt.length && contador <= 2; k++) { String string = arraySt[k]; if (!string.equals("")) { contador++; if (contador == 2) { e = string; } } } } else { //Number before e- String[] arr = arraySt[0].split("e-")[0].split(" "); String numeroAntesE = arr[arr.length - 1]; String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0]; e = numeroAntesE + "e-" + numeroDespuesE; } double eValue = Double.parseDouble(e); //System.out.println("eValue = " + eValue); GeneEValuePair g = new GeneEValuePair(id, eValue); featuresBlast.add(g); } } } GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(), gene.getEvalue()); System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id); System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue); boolean blastContainsGene = false; for (GeneEValuePair geneEValuePair : featuresBlast) { if (geneEValuePair.id.equals(currentGeneEValuePair.id)) { blastContainsGene = true; //le pongo la e que tiene en el wu-blast para poder comparar currentGeneEValuePair.eValue = geneEValuePair.eValue; break; } } if (blastContainsGene) { outBuff.write("The protein was found in the WU-BLAST result.. \n"); //Una vez que se que esta en el blast tengo que ver que sea la mejor GeneEValuePair first = featuresBlast.first(); outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id + " , " + first.eValue + "\n"); if (first.id.equals(currentGeneEValuePair.id)) { outBuff.write("Proteins with best eValue match up \n"); } else { if (first.eValue == currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has the same eValue \n"); } else if (first.eValue > currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has a worse eValue :) \n"); } else { outBuff.write( "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n"); //System.exit(-1); if (proteinsReferenceSet.contains(first.id)) { //The protein is in the reference set and that shouldn't happen outBuff.write( "The protein was found on the reference set, checking if it belongs to the same contig...\n"); String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId()); if (iterationSt != null) { outBuff.write( "The protein was found in the BLAST used at the beginning of the annotation process.\n"); Iteration iteration = new Iteration(iterationSt); ArrayList<Hit> hits = iteration.getIterationHits(); boolean contigFound = false; Hit errorHit = null; for (Hit hit : hits) { if (hit.getHitDef().indexOf(contig.getId()) >= 0) { contigFound = true; errorHit = hit; break; } } if (contigFound) { outBuff.write( "ERROR: A hit from the same contig was find in the Blast file: \n" + errorHit.toString() + "\n"); } else { outBuff.write("There is no hit with the same contig! :)\n"); } } else { outBuff.write( "The protein is NOT in the BLAST used at the beginning of the annotation process.\n"); } } else { //The protein was not found on the reference set so everything's ok outBuff.write( "The protein was not found on the reference, everything's ok :)\n"); } } } } else { outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n"); //System.exit(-1); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { //closing outputfile outBuff.close(); } catch (IOException ex) { Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:com.github.brandtg.StlPlotter.java
public static void main(String[] args) throws Exception { List<Long> times = new ArrayList<>(); List<Number> series = new ArrayList<>(); try (InputStream is = new FileInputStream(args[1]); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line = reader.readLine(); // header while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); times.add(Long.valueOf(tokens[0])); series.add(Double.valueOf(tokens[1])); }//from www.j ava 2s . com } StlConfig config = new StlConfig(); config.setNumberOfObservations(Integer.valueOf(args[0])); config.setNumberOfDataPoints(times.size()); config.setNumberOfRobustnessIterations(1); config.setPeriodic(true); StlResult result = new StlDecomposition(config).decompose(times, series); plot(result); }
From source file:com.photon.phresco.service.tools.TechnologyDataGenerator.java
public static void main(String[] args) throws PhrescoException { File toolsHome = new File("D:/work/phresco/MasterNew/servicenew/phresco-service-runner/delivery/tools"); File binariesDir = new File("D:\\work\\phresco\\Phresco-binaries\\"); File inputRootDir = new File(toolsHome, "files"); File outputRootDir = new File(toolsHome, "repo"); TechnologyDataGenerator dataGen = new TechnologyDataGenerator(inputRootDir, outputRootDir, binariesDir); dataGen.generateAll();/* www . j a va2 s . co m*/ System.out.println(moduleMap.size()); Set<String> keySet = moduleMap.keySet(); List<ArtifactGroup> group = new ArrayList<ArtifactGroup>(); for (String string : keySet) { ArtifactGroup moduleGroup = moduleMap.get(string); group.add(moduleGroup); } System.out.println(group.size()); }
From source file:com.jwm123.loggly.reporter.AppLauncher.java
public static void main(String args[]) throws Exception { try {//from w w w .ja va 2 s. c o m CommandLine cl = parseCLI(args); try { config = new Configuration(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: Failed to read in persisted configuration."); } if (cl.hasOption("h")) { HelpFormatter help = new HelpFormatter(); String jarName = AppLauncher.class.getProtectionDomain().getCodeSource().getLocation().getFile(); if (jarName.contains("/")) { jarName = jarName.substring(jarName.lastIndexOf("/") + 1); } help.printHelp("java -jar " + jarName + " [options]", opts); } if (cl.hasOption("c")) { config.update(); } if (cl.hasOption("q")) { Client client = new Client(config); client.setQuery(cl.getOptionValue("q")); if (cl.hasOption("from")) { client.setFrom(cl.getOptionValue("from")); } if (cl.hasOption("to")) { client.setTo(cl.getOptionValue("to")); } List<Map<String, Object>> report = client.getReport(); if (report != null) { List<Map<String, String>> reportContent = new ArrayList<Map<String, String>>(); ReportGenerator generator = null; if (cl.hasOption("file")) { generator = new ReportGenerator(new File(cl.getOptionValue("file"))); } byte reportFile[] = null; if (cl.hasOption("g")) { System.out.println("Search results: " + report.size()); Set<Object> values = new TreeSet<Object>(); Map<Object, Integer> counts = new HashMap<Object, Integer>(); for (String groupBy : cl.getOptionValues("g")) { for (Map<String, Object> result : report) { if (mapContains(result, groupBy)) { Object value = mapGet(result, groupBy); values.add(value); if (counts.containsKey(value)) { counts.put(value, counts.get(value) + 1); } else { counts.put(value, 1); } } } System.out.println("For key: " + groupBy); for (Object value : values) { System.out.println(" " + value + ": " + counts.get(value)); } } if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); for (Object value : values) { reportAddition = new LinkedHashMap<String, String>(); reportAddition.put(value.toString(), "" + counts.get(value)); reportContent.add(reportAddition); } reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Total", "" + report.size()); reportContent.add(reportAddition); } } else { System.out.println("The Search [" + cl.getOptionValue("q") + "] yielded " + report.size() + " results."); if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Count", "" + report.size()); reportContent.add(reportAddition); } } if (cl.hasOption("file")) { reportFile = generator.build(reportContent); File reportFileObj = new File(cl.getOptionValue("file")); FileUtils.writeByteArrayToFile(reportFileObj, reportFile); if (cl.hasOption("e")) { ReportMailer mailer = new ReportMailer(config, cl.getOptionValues("e"), cl.getOptionValue("s"), reportFileObj.getName(), reportFile); mailer.send(); } } } } } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); System.exit(1); } }