List of usage examples for java.util ArrayList get
public E get(int index)
From source file:com.sun.faban.harness.util.CLI.java
/** * The first argument to the CLI is the action. It can be:<ul> * <li>pending</li>/* ww w . jav a2 s . c o m*/ * <li>status runId</li> * <li>submit benchmark profile configfile.xml</ul> * </ul> * * @param args The command line arguments. */ public static void main(String[] args) { if (args.length == 0) { printUsage(); System.exit(1); } ArrayList<String> argList = new ArrayList<String>(); // Do the getopt thing. char opt = (char) -1; String master = null; String user = null; String password = null; for (String arg : args) { if (arg.startsWith("-M")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'M'; continue; } master = optArg; } else if (arg.startsWith("-U")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'U'; continue; } user = optArg; } else if (arg.startsWith("-P")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'P'; continue; } password = optArg; } else if (opt != (char) -1) { switch (opt) { case 'M': master = arg; opt = (char) -1; break; case 'U': user = arg; opt = (char) -1; break; case 'P': password = arg; opt = (char) -1; break; } } else { argList.add(arg); opt = (char) -1; } } if (master == null) master = "http://localhost:9980/"; else if (!master.endsWith("/")) master += '/'; CLI cli = new CLI(); String action = argList.get(0); try { if ("pending".equals(action)) { cli.doGet(master + "pending"); } else if ("status".equals(action)) { if (argList.size() > 1) cli.doGet(master + "status/" + argList.get(1)); else printUsage(); } else if ("submit".equals(action)) { if (argList.size() > 3) { cli.doPostSubmit(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("kill".equals(action)) { if (argList.size() > 1) { cli.doPostKill(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("wait".equals(action)) { if (argList.size() > 1) { cli.pollStatus(master + "status/" + argList.get(1)); } else { printUsage(); System.exit(1); } } else if ("showlogs".equals(action)) { StringBuilder url = new StringBuilder(); if (argList.size() > 1) { url.append(master).append("logs/"); url.append(argList.get(1)); } else { printUsage(); } for (int i = 2; i < argList.size(); i++) { if ("-t".equals(argList.get(i))) url.append("/tail"); if ("-f".equals(argList.get(i))) url.append("/follow"); if ("-ft".equals(argList.get(i))) url.append("/tail/follow"); if ("-tf".equals(argList.get(i))) url.append("/tail/follow"); } cli.doGet(url.toString()); } else { printUsage(); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
From source file:dependencies.DependencyResolving.java
/** * @param args the command line arguments *///from ww w. ja va 2s .c om public static void main(String[] args) { // TODO code application logic here JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file try { //here we declare the file reader and define the path to the file dependencies.json Object obj = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json")); JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies" System.out.print("We need to install the following dependencies: "); Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies" while (iterator.hasNext()) { System.out.println(iterator.next()); } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json Object obj2 = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json")); JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json for (int i = 0; i < dependencies.size(); i++) { if (tools.containsKey(dependencies.get(i))) { System.out.println( "In order to install " + dependencies.get(i) + ", we need the following programs:"); JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies for (i = 0; i < temporaryArray.size(); i++) { System.out.println(temporaryArray.get(i)); } ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore for (i = 0; i < temporaryArray.size(); i++) { System.out.println("Installing " + temporaryArray.get(i)); } while (!temporaryArray.isEmpty()) { for (Object element : temporaryArray) { if (tools.containsKey(element)) { JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement if (secondaryArray.size() != 0) { System.out.println("In order to install " + element + ", we need "); } for (i = 0; i < secondaryArray.size(); i++) { System.out.println(secondaryArray.get(i)); } for (Object o : secondaryArray) { arraysOfJsonData.add(o); //here we create a file with the installed dependency File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + o); if (file.createNewFile()) { System.out.println(file.getName() + " is installed!"); } else { } } secondaryArray.clear(); } } temporaryArray.clear(); for (i = 0; i < arraysOfJsonData.size(); i++) { temporaryArray.add(arraysOfJsonData.get(i)); } arraysOfJsonData.clear(); } } } Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json for (String s : keys) { File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + s); if (file.createNewFile()) { System.out.println(file.getName() + " is installed."); } else { } } } catch (IOException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionSplitter.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", null, true, "Input file"); options.addOption("o", null, true, "Output file prefix"); options.addOption("p", null, true, "Comma separated probabilities e.g., 0.1,0.2,0.7."); options.addOption("n", null, true, "Comma separated part names, e.g., dev,test,train"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w . ja va 2s.c o m CommandLine cmd = parser.parse(options, args); InputStream input = null; if (cmd.hasOption("i")) { input = CompressUtils.createInputStream(cmd.getOptionValue("i")); } else { Usage("Specify Input file"); } ArrayList<Double> probs = new ArrayList<Double>(); String[] partNames = null; if (cmd.hasOption("p")) { String parts[] = cmd.getOptionValue("p").split(","); try { double sum = 0; for (String s : parts) { double p = Double.parseDouble(s); if (p <= 0 || p > 1) Usage("All probabilities must be in the range (0,1)"); sum += p; probs.add(p); } if (Math.abs(sum - 1.0) > Float.MIN_NORMAL) { Usage("The sum of probabilities should be equal to 1, but it's: " + sum); } } catch (NumberFormatException e) { Usage("Can't convert some of the probabilities to a floating-point number."); } } else { Usage("Specify part probabilities."); } if (cmd.hasOption("n")) { partNames = cmd.getOptionValue("n").split(","); if (partNames.length != probs.size()) Usage("The number of probabilities is not equal to the number of parts!"); } else { Usage("Specify part names"); } BufferedWriter[] outFiles = new BufferedWriter[partNames.length]; if (cmd.hasOption("o")) { String outPrefix = cmd.getOptionValue("o"); for (int partId = 0; partId < partNames.length; ++partId) { outFiles[partId] = new BufferedWriter(new OutputStreamWriter( CompressUtils.createOutputStream(outPrefix + "_" + partNames[partId] + ".gz"))); } } else { Usage("Specify Output file prefix"); } System.out.println("Using probabilities:"); for (int partId = 0; partId < partNames.length; ++partId) System.out.println(partNames[partId] + " : " + probs.get(partId)); System.out.println("================================================="); XmlIterator inpIter = new XmlIterator(input, YahooAnswersReader.DOCUMENT_TAG); String oneRec = inpIter.readNext(); int docNum = 1; for (; !oneRec.isEmpty(); ++docNum, oneRec = inpIter.readNext()) { double p = Math.random(); if (docNum % 1000 == 0) { System.out.println(String.format("Processed %d documents", docNum)); } BufferedWriter out = null; for (int partId = 0; partId < partNames.length; ++partId) { double pp = probs.get(partId); if (p <= pp || partId + 1 == partNames.length) { out = outFiles[partId]; break; } p -= pp; } oneRec = oneRec.trim() + System.getProperty("line.separator"); out.write(oneRec); } System.out.println(String.format("Processed %d documents", docNum - 1)); // It's important to close all the streams here! for (BufferedWriter f : outFiles) f.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("q", null, true, "Query"); options.addOption("n", null, true, "Max # of results"); options.addOption("o", null, true, "An optional TREC-style output file"); options.addOption("w", null, false, "Do a warm-up query call, before each query"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter trecOutFile = null; try {/*from w w w . j a v a 2 s . c o m*/ CommandLine cmd = parser.parse(options, args); String queryFile = null, solrURI = null; if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); if (cmd.hasOption("q")) { queryFile = cmd.getOptionValue("q"); } else { Usage("Specify Query file"); } int numRet = 100; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } if (cmd.hasOption("o")) { trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o")))); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConst.ID_FIELD); fieldList.add(UtilConst.SCORE_FIELD); double totalTime = 0; double retQty = 0; ArrayList<Double> queryTimes = new ArrayList<Double>(); boolean bDoWarmUp = cmd.hasOption("w"); if (bDoWarmUp) { System.out.println("Using a warmup step!"); } int queryQty = 0; for (String t : FileUtils.readLines(new File(queryFile))) { t = t.trim(); if (t.isEmpty()) continue; int ind = t.indexOf('|'); if (ind < 0) throw new Exception("Wrong format, line: '" + t + "'"); String qID = t.substring(0, ind); String q = t.substring(ind + 1); SolrDocumentList res = null; if (bDoWarmUp) { res = solr.runQuery(q, fieldList, numRet); } Long tm1 = System.currentTimeMillis(); res = solr.runQuery(q, fieldList, numRet); Long tm2 = System.currentTimeMillis(); retQty += res.getNumFound(); System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms"); double delta = (tm2 - tm1); totalTime += delta; queryTimes.add(delta); ++queryQty; if (trecOutFile != null) { ArrayList<SolrRes> resArr = new ArrayList<SolrRes>(); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConst.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD); resArr.add(new SolrRes(id, "", score)); } SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]); Arrays.sort(results); SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length); } } double devTime = 0, meanTime = totalTime / queryQty; for (int i = 0; i < queryQty; ++i) { double d = queryTimes.get(i) - meanTime; devTime += d * d; } devTime = Math.sqrt(devTime / (queryQty - 1)); System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime)); System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty)); solr.close(); trecOutFile.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:boa.compiler.BoaCompiler.java
public static void main(final String[] args) throws IOException { CommandLine cl = processCommandLineOptions(args); if (cl == null) return;// www . ja va 2s . c o m final ArrayList<File> inputFiles = BoaCompiler.inputFiles; // get the name of the generated class final String className = getGeneratedClass(cl); // get the filename of the jar we will be writing final String jarName; if (cl.hasOption('o')) jarName = cl.getOptionValue('o'); else jarName = className + ".jar"; // make the output directory File outputRoot = null; if (cl.hasOption("cd")) { outputRoot = new File(cl.getOptionValue("cd")); } else { outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString()); } final File outputSrcDir = new File(outputRoot, "boa"); if (!outputSrcDir.mkdirs()) throw new IOException("unable to mkdir " + outputSrcDir); // find custom libs to load final List<URL> libs = new ArrayList<URL>(); if (cl.hasOption('l')) for (final String lib : cl.getOptionValues('l')) libs.add(new File(lib).toURI().toURL()); final File outputFile = new File(outputSrcDir, className + ".java"); final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile)); try { final List<String> jobnames = new ArrayList<String>(); final List<String> jobs = new ArrayList<String>(); boolean isSimple = true; final List<Program> visitorPrograms = new ArrayList<Program>(); SymbolTable.initialize(libs); final int maxVisitors; if (cl.hasOption('v')) maxVisitors = Integer.parseInt(cl.getOptionValue('v')); else maxVisitors = Integer.MAX_VALUE; for (int i = 0; i < inputFiles.size(); i++) { final File f = inputFiles.get(i); try { final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath())); lexer.removeErrorListeners(); lexer.addErrorListener(new LexerErrorListener()); final CommonTokenStream tokens = new CommonTokenStream(lexer); final BoaParser parser = new BoaParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException(e); } }); final BoaErrorListener parserErrorListener = new ParserErrorListener(); final Start p = parse(tokens, parser, parserErrorListener); if (cl.hasOption("ast")) new ASTPrintingVisitor().start(p); final String jobName = "" + i; try { if (!parserErrorListener.hasError) { new TypeCheckingVisitor().start(p, new SymbolTable()); final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor(); simpleVisitor.start(p); LOG.info(f.getName() + ": task complexity: " + (!simpleVisitor.isComplex() ? "simple" : "complex")); isSimple &= !simpleVisitor.isComplex(); new ShadowTypeEraser().start(p); new InheritedAttributeTransformer().start(p); new LocalAggregationTransformer().start(p); // if a job has no visitor, let it have its own method // also let jobs have own methods if visitor merging is disabled if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) { new VisitorOptimizingTransformer().start(p); if (cl.hasOption("pp")) new PrettyPrintVisitor().start(p); if (cl.hasOption("ast2")) new ASTPrintingVisitor().start(p); final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName); cg.start(p); jobs.add(cg.getCode()); jobnames.add(jobName); } // if a job has visitors, fuse them all together into a single program else { p.getProgram().jobName = jobName; visitorPrograms.add(p.getProgram()); } } } catch (final TypeCheckException e) { parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn, e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e); } } catch (final Exception e) { System.err.print(f.getName() + ": compilation failed: "); e.printStackTrace(); } } if (!visitorPrograms.isEmpty()) try { for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms, maxVisitors)) { new VisitorOptimizingTransformer().start(p); if (cl.hasOption("pp")) new PrettyPrintVisitor().start(p); if (cl.hasOption("ast2")) new ASTPrintingVisitor().start(p); final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName); cg.start(p); jobs.add(cg.getCode()); jobnames.add(p.jobName); } } catch (final Exception e) { System.err.println("error fusing visitors - falling back: " + e); e.printStackTrace(); for (final Program p : visitorPrograms) { new VisitorOptimizingTransformer().start(p); if (cl.hasOption("pp")) new PrettyPrintVisitor().start(p); if (cl.hasOption("ast2")) new ASTPrintingVisitor().start(p); final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName); cg.start(p); jobs.add(cg.getCode()); jobnames.add(p.jobName); } } if (jobs.size() == 0) throw new RuntimeException("no files compiled without error"); final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program"); st.add("name", className); st.add("numreducers", inputFiles.size()); st.add("jobs", jobs); st.add("jobnames", jobnames); st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings); st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings); st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024); if (DefaultProperties.localDataPath != null) { st.add("isLocal", true); } o.write(st.render().getBytes()); } finally { o.close(); } compileGeneratedSrc(cl, jarName, outputRoot, outputFile); }
From source file:gedi.lfc.quick.ShiroguchiCounter.java
public static void main(String[] args) throws IOException { String path = "/home/users/erhard/biostor/seq/ngade/shiroguchi_randombarcodes/data/"; MemoryIntervalTreeStorage<int[]> reads = new MemoryIntervalTreeStorage<int[]>(int[].class); String[] files = { "Shiroguchi_A_collapsed.bed", "Shiroguchi_B_collapsed.bed", "Shiroguchi_A_uncollapsed.bed", "Shiroguchi_B_uncollapsed.bed" }; for (int i = 0; i < 4; i++) { Iterator<String> it = new LineOrientedFile(path + files[i]).lineIterator(); while (it.hasNext()) { String[] f = StringUtils.split(it.next(), '\t'); Chromosome chr = Chromosome.obtain(f[0]); ArrayGenomicRegion region = new ArrayGenomicRegion(Integer.parseInt(f[1]), Integer.parseInt(f[2])); int c = Integer.parseInt(StringUtils.splitField(f[3], '|', 0)); int[] counts = reads.getData(chr, region); if (counts == null) reads.add(chr, region, counts = new int[4]); counts[i] += c;//w w w . ja v a 2 s. co m } } HashMap<String, String> map = new HashMap<String, String>(); new LineOrientedFile(path + "U00096.2.genes.csv").lineIterator().forEachRemaining(s -> { String[] f = StringUtils.split(s, '\t'); map.put(f[0], f[7]); }); LineOrientedFile fragments = new LineOrientedFile("fragments.csv"); fragments.startWriting(); fragments.writef("Gene\tonlyA\tonlyB\tBoth\tLength\n"); LineOrientedFile bias = new LineOrientedFile("bias.csv"); bias.startWriting(); bias.writef("OriginalA\tBiasA\tOriginalB\tBiasB\n"); IntArrayList biasFactors = new IntArrayList(); ArrayList<GeneData> geneData = new ArrayList<GeneData>(); MemoryIntervalTreeStorage<Transcript> genes = new BiomartExonFileReader(path + "U00096.2.exons.csv", false) .readIntoMemoryTakeFirst(); for (ImmutableReferenceGenomicRegion<Transcript> g : genes.getReferenceGenomicRegions()) { ArrayList<ImmutableReferenceGenomicRegion<int[]>> frag = reads .getReferenceRegionsIntersecting(g.getReference().toStrandIndependent(), g.getRegion()); GeneData gd = new GeneData(); int l = g.getRegion().getTotalLength(); for (ImmutableReferenceGenomicRegion<int[]> r : frag) { if (r.getData()[0] == 0) gd.onlyB++; if (r.getData()[1] == 0) gd.onlyA++; if (r.getData()[0] == 0 && r.getData()[1] == 0) throw new RuntimeException(); bias.writef("%d\t%.0f\t%d\t%.0f\n", r.getData()[0], r.getData()[2] / (double) r.getData()[0], r.getData()[1], r.getData()[3] / (double) r.getData()[1]); if (r.getData()[0] > 0) { biasFactors.add(r.getData()[2] / r.getData()[0]); } if (r.getData()[1] > 0) { biasFactors.add(r.getData()[3] / r.getData()[1]); } } gd.both = frag.size() - gd.onlyA - gd.onlyB; fragments.writef("%s\t%d\t%d\t%d\t%d\n", map.get(g.getData().getTranscriptId()), gd.onlyA, gd.onlyB, gd.both, l); if (gd.onlyA + gd.onlyB + gd.both > 0) geneData.add(gd); } fragments.finishWriting(); bias.finishWriting(); double fc = 1.4; int rep = 5; int nDiff = 1000; int n = 10000; int N = 6000; double noise = 0.05; LineOrientedFile countMatrix = new LineOrientedFile("countMatrix.csv"); countMatrix.startWriting(); LineOrientedFile downCountMatrix = new LineOrientedFile("countMatrix_downsampled.csv"); downCountMatrix.startWriting(); RandomNumbers rnd = new RandomNumbers(); for (int i = 0; i < n; i++) { GeneData gd = geneData.get(rnd.getUnif(0, geneData.size())); // int N = gd.both==0?Integer.MAX_VALUE/2:(int) (gd.onlyA+gd.onlyB+gd.both+gd.onlyA*gd.onlyB/gd.both); double p1 = (gd.onlyA + gd.both) / (double) N; double p2 = i < nDiff ? p1 / fc : p1; ArrayList<ReadData> list = new ArrayList<ReadData>(); for (int r = 0; r < rep * 2; r++) { int k = rnd.getBinom(N, r < rep ? p1 : p2) + 1; int hit = N == -1 ? 0 : rnd.getBinom(k, list.size() / (double) N); rnd.shuffle(list); for (int x = 0; x < hit; x++) list.get(x).reads[r] = (int) rnd.getNormal(list.get(x).bias, list.get(x).bias * noise); for (int x = 0; x < k - hit; x++) list.add(new ReadData(biasFactors.getInt(rnd.getUnif(0, biasFactors.size())), rep * 2, r)); } int[] c = new int[rep * 2]; for (ReadData d : list) { for (int r = 0; r < c.length; r++) { c[r] += d.reads[r]; } } double[] down = new double[rep * 2]; for (ReadData d : list) { double max = ArrayUtils.max(d.reads); for (int r = 0; r < down.length; r++) { down[r] += d.reads[r] / max; } } countMatrix.writeLine(StringUtils.concat("\t", c)); downCountMatrix.writeLine(StringUtils.concat("\t", down)); } countMatrix.finishWriting(); downCountMatrix.finishWriting(); }
From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java
/** * @param args/*w w w. ja v a 2 s . co m*/ */ public static void main(String[] args) { // process command-line options Options options = new Options(); options.addOption("n", "noaddr", false, "do not do any address matching (for testing)"); options.addOption("i", "info", false, "create and populate address information table"); options.addOption("h", "help", false, "this message"); // database connection options.addOption("s", "server", true, "database server to connect to"); options.addOption("d", "database", true, "OSM database name"); options.addOption("u", "user", true, "OSM database user name"); options.addOption("p", "pass", true, "OSM database password"); // logging options options.addOption("l", "logdir", true, "log file directory (default './logs')"); options.addOption("e", "loglevel", true, "log level (default 'FINEST')"); // automatically generate the help statement HelpFormatter help_formatter = new HelpFormatter(); // database URI for connection String dburi = null; // Information message for help screen String info_msg = "IzbirkomExtractor [options] <html_directory>"; try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h') || cmd.getArgs().length != 1) { help_formatter.printHelp(info_msg, options); System.exit(1); } /* prohibit n and i together */ if (cmd.hasOption('n') && cmd.hasOption('i')) { System.err.println("Options 'n' and 'i' cannot be used together."); System.exit(1); } /* require database arguments without -n */ if (cmd.hasOption('n') && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) { System.err.println("Options 'n' and does not need any databse parameters."); System.exit(1); } /* require all 4 database options to be used together */ if (!cmd.hasOption('n') && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) { System.err.println( "For database access all of the following arguments have to be specified: server, database, user, pass"); System.exit(1); } /* useful variables */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm"); String dateString = formatter.format(new Date()); /* setup logging */ File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs"); FileUtils.forceMkdir(logdir); File log_file_name = new File( logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log"); FileHandler log_file = new FileHandler(log_file_name.getPath()); /* create "latest" link to currently created log file */ Path latest_log_link = Paths.get(logdir + "/latest"); Files.deleteIfExists(latest_log_link); Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName())); log_file.setFormatter(new SimpleFormatter()); LogManager.getLogManager().reset(); // prevents logging to console logger.addHandler(log_file); logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST); // open directory with HTML files and create file list File dir = new File(cmd.getArgs()[0]); if (!dir.isDirectory()) { System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting"); System.exit(1); } PathMatcher pmatcher = FileSystems.getDefault() .getPathMatcher("glob:? * ?*.html"); ArrayList<File> html_files = new ArrayList<>(); for (Path file : Files.newDirectoryStream(dir.toPath())) if (pmatcher.matches(file.getFileName())) html_files.add(file.toFile()); if (html_files.size() == 0) { System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting"); System.exit(1); } // create csvResultSink FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv"); OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8"); ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#')); // Connect to DB and osmAddressMatcher AddressMatcher osmAddressMatcher; DBSink dbSink = null; DBInfoSink dbInfoSink = null; if (cmd.hasOption('n')) { osmAddressMatcher = new DummyAddressMatcher(); } else { dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d'); Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'), cmd.getOptionValue('p')); osmAddressMatcher = new OsmAddressMatcher(con); dbSink = new DBSink(con); if (cmd.hasOption('i')) dbInfoSink = new DBInfoSink(con); } /* create resultsinks */ SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor(); sm.addResultSink(csvResultSink); if (dbSink != null) { sm.addResultSink(dbSink); if (dbInfoSink != null) sm.addResultSink(dbInfoSink); } // create tableExtractor TableExtractor te = new TableExtractor(osmAddressMatcher, sm); // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters // iterate through files logger.info("Start processing " + html_files.size() + " files in " + dir); for (int i = 0; i < html_files.size(); i++) { System.err.println("Parsing #" + i + ": " + html_files.get(i)); te.processHTMLfile(html_files.get(i)); } System.err.println("Processed " + html_files.size() + " HTML files"); logger.info("Finished processing " + html_files.size() + " files in " + dir); } catch (ParseException e1) { System.err.println("Failed to parse CLI: " + e1.getMessage()); help_formatter.printHelp(info_msg, options); System.exit(1); } catch (IOException e) { System.err.println("I/O Exception: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.println("Database '" + dburi + "': " + e.getMessage()); System.exit(1); } catch (ResultSinkException e) { System.err.println("Failed to initialize ResultSink: " + e.getMessage()); System.exit(1); } catch (TableExtractorException e) { System.err.println("Failed to initialize Table Extractor: " + e.getMessage()); System.exit(1); } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) { System.err.println("Something really odd happened: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:edu.upenn.cis.FastAlign.java
/** * Prints alignments for options specified by command line arguments. * @param argv parameters to be used by FastAlign. *//*from w w w . j a v a 2s . c o m*/ public static void main(String[] argv) { FastAlign align = FastAlign.initCommandLine(argv); if (align == null) { System.err.println("Usage: java " + FastAlign.class.getCanonicalName() + " -i file.fr-en\n" + " Standard options ([USE] = strongly recommended):\n" + " -i: [REQ] Input parallel corpus\n" + " -v: [USE] Use Dirichlet prior on lexical translation distributions\n" + " -d: [USE] Favor alignment points close to the monotonic diagonoal\n" + " -o: [USE] Optimize how close to the diagonal alignment points should be\n" + " -r: Run alignment in reverse (condition on target and predict source)\n" + " -c: Output conditional probability table\n" + " -e: Start with existing conditional probability table\n" + " Advanced options:\n" + " -I: number of iterations in EM training (default = 5)\n" + " -p: p_null parameter (default = 0.08)\n" + " -N: No null word\n" + " -a: alpha parameter for optional Dirichlet prior (default = 0.01)\n" + " -T: starting lambda for diagonal distance parameter (default = 4)\n"); System.exit(1); } boolean use_null = !align.no_null_word; if (align.variational_bayes && align.alpha <= 0.0) { System.err.println("--alpha must be > 0\n"); System.exit(1); } double prob_align_not_null = 1.0 - align.prob_align_null; final int kNULL = align.d.Convert("<eps>"); TTable s2t = new TTable(); if (!align.existing_probability_filename.isEmpty()) { boolean success = s2t.ImportFromFile(align.existing_probability_filename, '\t', align.d); if (!success) { System.err.println("Can't read table " + align.existing_probability_filename); System.exit(1); } } Map<Pair, Integer> size_counts = new HashMap<Pair, Integer>(); double tot_len_ratio = 0; double mean_srclen_multiplier = 0; List<Double> probs = new ArrayList<Double>(); ; // E-M Iterations Loop TODO move this into a method? for (int iter = 0; iter < align.iterations || (iter == 0 && align.iterations == 0); ++iter) { final boolean final_iteration = (iter >= (align.iterations - 1)); System.err.println("ITERATION " + (iter + 1) + (final_iteration ? " (FINAL)" : "")); Scanner in = null; try { in = new Scanner(new File(align.input)); if (!in.hasNextLine()) { System.err.println("Can't read " + align.input); System.exit(1); } } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("Can't read " + align.input); System.exit(1); } double likelihood = 0; double denom = 0.0; int lc = 0; boolean flag = false; String line; // String ssrc, strg; ArrayList<Integer> src = new ArrayList<Integer>(); ArrayList<Integer> trg = new ArrayList<Integer>(); double c0 = 0; double emp_feat = 0; double toks = 0; // Iterate over each line of the input file while (in.hasNextLine()) { line = in.nextLine(); ++lc; if (lc % 1000 == 0) { System.err.print('.'); flag = true; } if (lc % 50000 == 0) { System.err.println(" [" + lc + "]\n"); System.err.flush(); flag = false; } src.clear(); trg.clear(); // TODO this is redundant; src and tgt cleared in ParseLine // Integerize and split source and target lines. align.ParseLine(line, src, trg); if (align.is_reverse) { ArrayList<Integer> tmp = src; src = trg; trg = tmp; } // TODO Empty lines break the parser. Should this be true? if (src.size() == 0 || trg.size() == 0) { System.err.println("Error in line " + lc + "\n" + line); System.exit(1); } if (iter == 0) { tot_len_ratio += ((double) trg.size()) / ((double) src.size()); } denom += trg.size(); probs.clear(); // Add to pair length counts only if first iteration. if (iter == 0) { Pair pair = new Pair(trg.size(), src.size()); Integer value = size_counts.get(pair); if (value == null) value = 0; size_counts.put(pair, value + 1); } boolean first_al = true; // used when printing alignments toks += trg.size(); // Iterate through the English tokens for (int j = 0; j < trg.size(); ++j) { final int f_j = trg.get(j); double sum = 0; double prob_a_i = 1.0 / (src.size() + (use_null ? 1 : 0)); // uniform (model 1) if (use_null) { if (align.favor_diagonal) { prob_a_i = align.prob_align_null; } probs.add(0, s2t.prob(kNULL, f_j) * prob_a_i); sum += probs.get(0); } double az = 0; if (align.favor_diagonal) az = DiagonalAlignment.computeZ(j + 1, trg.size(), src.size(), align.diagonal_tension) / prob_align_not_null; for (int i = 1; i <= src.size(); ++i) { if (align.favor_diagonal) prob_a_i = DiagonalAlignment.unnormalizedProb(j + 1, i, trg.size(), src.size(), align.diagonal_tension) / az; probs.add(i, s2t.prob(src.get(i - 1), f_j) * prob_a_i); sum += probs.get(i); } if (final_iteration) { double max_p = -1; int max_index = -1; if (use_null) { max_index = 0; max_p = probs.get(0); } for (int i = 1; i <= src.size(); ++i) { if (probs.get(i) > max_p) { max_index = i; max_p = probs.get(i); } } if (max_index > 0) { if (first_al) first_al = false; else System.out.print(' '); if (align.is_reverse) System.out.print("" + j + '-' + (max_index - 1)); else System.out.print("" + (max_index - 1) + '-' + j); } } else { if (use_null) { double count = probs.get(0) / sum; c0 += count; s2t.Increment(kNULL, f_j, count); } for (int i = 1; i <= src.size(); ++i) { final double p = probs.get(i) / sum; s2t.Increment(src.get(i - 1), f_j, p); emp_feat += DiagonalAlignment.feature(j, i, trg.size(), src.size()) * p; } } likelihood += Math.log(sum); } if (final_iteration) System.out.println(); } // log(e) = 1.0 double base2_likelihood = likelihood / Math.log(2); if (flag) { System.err.println(); } if (iter == 0) { mean_srclen_multiplier = tot_len_ratio / lc; System.err.println("expected target length = source length * " + mean_srclen_multiplier); } emp_feat /= toks; System.err.println(" log_e likelihood: " + likelihood); System.err.println(" log_2 likelihood: " + base2_likelihood); System.err.println(" cross entropy: " + (-base2_likelihood / denom)); System.err.println(" perplexity: " + Math.pow(2.0, -base2_likelihood / denom)); System.err.println(" posterior p0: " + c0 / toks); System.err.println(" posterior al-feat: " + emp_feat); //System.err.println(" model tension: " + mod_feat / toks ); System.err.println(" size counts: " + size_counts.size()); if (!final_iteration) { if (align.favor_diagonal && align.optimize_tension && iter > 0) { for (int ii = 0; ii < 8; ++ii) { double mod_feat = 0; Iterator<Map.Entry<Pair, Integer>> it = size_counts.entrySet().iterator(); for (; it.hasNext();) { Map.Entry<Pair, Integer> entry = it.next(); final Pair p = entry.getKey(); for (int j = 1; j <= p.first; ++j) mod_feat += entry.getValue() * DiagonalAlignment.computeDLogZ(j, p.first, p.second, align.diagonal_tension); } mod_feat /= toks; System.err.println(" " + ii + 1 + " model al-feat: " + mod_feat + " (tension=" + align.diagonal_tension + ")"); align.diagonal_tension += (emp_feat - mod_feat) * 20.0; if (align.diagonal_tension <= 0.1) align.diagonal_tension = 0.1; if (align.diagonal_tension > 14) align.diagonal_tension = 14; } System.err.println(" final tension: " + align.diagonal_tension); } if (align.variational_bayes) s2t.NormalizeVB(align.alpha); else s2t.Normalize(); //prob_align_null *= 0.8; // XXX //prob_align_null += (c0 / toks) * 0.2; prob_align_not_null = 1.0 - align.prob_align_null; } } if (!align.conditional_probability_filename.isEmpty()) { System.err.println("conditional probabilities: " + align.conditional_probability_filename); s2t.ExportToFile(align.conditional_probability_filename, align.d); } System.exit(0); }
From source file:edu.oregonstate.eecs.mcplan.ml.ConstrainedKMeans.java
/** * @param args// ww w . j a v a 2s. c o m */ public static void main(final String[] args) { final RandomGenerator rng = new MersenneTwister(42); final int K = 2; final int d = 2; final ArrayList<RealVector> X = new ArrayList<RealVector>(); final double u = 2.0; final double ell = 8.0; final double gamma = 10.0; for (final int s : new int[] { 0, 5, 10 }) { for (int x = -1; x <= 1; ++x) { for (int y = -1; y <= 1; ++y) { X.add(new ArrayRealVector(new double[] { x + s, y })); } } } final TIntObjectMap<Pair<int[], double[]>> M = new TIntObjectHashMap<Pair<int[], double[]>>(); M.put(16, Pair.makePair(new int[] { 20 }, new double[] { 1.0 })); M.put(0, Pair.makePair(new int[] { 8 }, new double[] { 1.0 })); final TIntObjectMap<Pair<int[], double[]>> C = new TIntObjectHashMap<Pair<int[], double[]>>(); C.put(13, Pair.makePair(new int[] { 20 }, new double[] { 1.0 })); C.put(10, Pair.makePair(new int[] { 16 }, new double[] { 1.0 })); final ArrayList<double[]> S = new ArrayList<double[]>(); M.forEachKey(new TIntProcedure() { @Override public boolean execute(final int i) { final Pair<int[], double[]> p = M.get(i); if (p != null) { for (final int j : p.first) { S.add(new double[] { i, j }); } } return true; } }); final ArrayList<double[]> D = new ArrayList<double[]>(); C.forEachKey(new TIntProcedure() { @Override public boolean execute(final int i) { final Pair<int[], double[]> p = C.get(i); if (p != null) { for (final int j : p.first) { D.add(new double[] { i, j }); } } return true; } }); final ConstrainedKMeans kmeans = new ConstrainedKMeans(K, d, X, M, C, rng) { RealMatrix A_ = MatrixUtils.createRealIdentityMatrix(d); double Dmax_ = 1.0; @Override public double distance(final RealVector x1, final RealVector x2) { final RealVector diff = x1.subtract(x2); return Math.sqrt(HilbertSpace.inner_prod(diff, A_, diff)); } @Override public double distanceMax() { return Dmax_; } @Override protected void initializeDistanceFunction() { double max_distance = 0.0; for (int i = 0; i < X.size(); ++i) { for (int j = i + 1; j < X.size(); ++j) { final double d = distance(X.get(i), X.get(j)); if (d > max_distance) { max_distance = d; } } } Dmax_ = max_distance; } @Override protected boolean updateDistanceFunction() { final InformationTheoreticMetricLearner itml = new InformationTheoreticMetricLearner(S, D, u, ell, A_, gamma, rng_); itml.run(); final double delta = A_.subtract(itml.A()).getFrobeniusNorm(); A_ = itml.A(); initializeDistanceFunction(); return delta > convergence_tolerance_; } }; kmeans.run(); for (int i = 0; i < kmeans.mu().length; ++i) { System.out.println("Mu " + i + ": " + kmeans.mu()[i]); for (int j = 0; j < kmeans.assignments().length; ++j) { if (kmeans.assignments()[j] == i) { System.out.println("\tPoint " + X.get(j)); } } } }
From source file:de.prozesskraft.pkraft.Createdoc.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { Createdoc tmp = new Createdoc(); /*---------------------------- get options from ini-file//from ww w . j a va 2 s.co m ----------------------------*/ File installDir = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Createdoc.class) + "/.."); File inifile = new java.io.File(installDir.getAbsolutePath() + "/etc/pkraft-createdoc.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option odefinition = OptionBuilder.withArgName("definition").hasArg() .withDescription("[mandatory] process definition file") // .isRequired() .create("definition"); Option oformat = OptionBuilder.withArgName("format").hasArg() .withDescription("[mandatory, default=pdf] output format (pdf|pptx) ").create("format"); Option ooutput = OptionBuilder.withArgName("output").hasArg().withDescription( "[mandatory, default=out.<format>] output file with full documentation of process definition") // .isRequired() .create("output"); //// Option property = OptionBuilder.withArgName( "property=value" ) //// .hasArgs(2) //// .withValueSeparator() //// .withDescription( "use value for given property" ) //// .create("D"); // // /*---------------------------- // create options object // ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(odefinition); options.addOption(oformat); options.addOption(ooutput); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments line = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("createdoc", options); System.exit(0); } if (line.hasOption("v")) { System.out.println("web: www.prozesskraft.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- die variablen festlegen ----------------------------*/ int error = 0; String definition = null; String format = null; String output = null; // festlegen von definition if (line.hasOption("definition")) { definition = line.getOptionValue("definition"); if (!(new java.io.File(definition).exists())) { System.err.println("file does not exist " + definition); } } else { System.err.println("parameter -definition is mandatory"); error++; } // festlegen von format if (line.hasOption("format")) { if (line.getOptionValue("format").matches("pdf|pptx")) { format = line.getOptionValue("format"); } else { System.err.println("for -format use only pdf|pptx"); error++; } } else { format = "pdf"; } // festlegen von output if (line.hasOption("output")) { output = line.getOptionValue("output"); } else { output = "out." + format; } // feststellen ob output bereits existiert if (new java.io.File(output).exists()) { System.err.println("output already exists: " + output); error++; } // aussteigen, falls fehler aufgetaucht sind if (error > 0) { System.err.println("error(s) occured. try -help for help."); System.exit(1); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process process = new Process(); Reporter report; process.setInfilexml(definition); System.out.println("info: reading process definition " + definition); try { process.readXml(); process.setStepRanks(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } //festlegen des temporaeren verzeichnisses fuer die Daten und Pfade erzeugen long jetztMillis = System.currentTimeMillis(); String randomPathJasperFilled = "/tmp/" + jetztMillis + "_jasperFilled"; String randomPathPng = "/tmp/" + jetztMillis + "_png"; String randomPathPdf = "/tmp/" + jetztMillis + "_pdf"; String randomPathPptx = "/tmp/" + jetztMillis + "_pptx"; new File(randomPathJasperFilled).mkdirs(); new File(randomPathPng).mkdirs(); new File(randomPathPdf).mkdirs(); new File(randomPathPptx).mkdirs(); ////////////////////////////////////////// // erstellen der Bilder // konfigurieren der processing ansicht // PmodelViewPage page = new PmodelViewPage(process); PmodelViewPage page = new PmodelViewPage(); page.einstellungen.getProcess().setStepRanks(); page.einstellungen.setSize(100); page.einstellungen.setZoom(100); // page.einstellungen.setZoom(8 * 100/process.getMaxLevel()); page.einstellungen.setTextsize(0); page.einstellungen.setRanksize(7); page.einstellungen.setWidth(2500); page.einstellungen.setHeight(750); page.einstellungen.setGravx(10); page.einstellungen.setGravy(0); page.einstellungen.setRootpositionratiox((float) 0.05); page.einstellungen.setRootpositionratioy((float) 0.5); page.einstellungen.setProcess(process); createContents(page); // mit open kann die page angezeigt werden if (!(produktiv)) { open(); } // // warten // System.out.println("stabilisierung ansicht: 5 sekunden warten gravitation = "+page.einstellungen.getGravx()); // long jetzt5 = System.currentTimeMillis(); // while (System.currentTimeMillis() < jetzt5 + 5000) // { // // } // // page.einstellungen.setGravx(10); // // warten int wartezeitSeconds = 1; if (produktiv) { wartezeitSeconds = page.einstellungen.getProcess().getStep().size() * 2; } System.out.println("stabilisierung ansicht: " + wartezeitSeconds + " sekunden warten gravitation = " + page.einstellungen.getGravx()); long jetzt6 = System.currentTimeMillis(); while (System.currentTimeMillis() < jetzt6 + (wartezeitSeconds * 1000)) { } page.einstellungen.setFix(true); // VORBEREITUNG) bild speichern processTopologyImagePath = randomPathPng + "/processTopology.png"; page.savePic(processTopologyImagePath); // zuerst 1 sekunde warten, dann autocrop long jetzt = System.currentTimeMillis(); while (System.currentTimeMillis() < jetzt + 1000) { } new AutoCropBorder(processTopologyImagePath); // VORBEREITUNG) fuer jeden step ein bild speichern for (Step actualStep : process.getStep()) { // root ueberspringen // if (actualStep.isRoot()); String stepImagePath = randomPathPng + "/step_" + actualStep.getName() + "_Topology.png"; // Farbe des Steps auf finished (gruen) aendern page.einstellungen.getProcess().getRootStep().setStatusOverwrite("waiting"); actualStep.setStatusOverwrite("finished"); // etwas warten, bis die farbe bezeichnet wurde long jetzt4 = System.currentTimeMillis(); while (System.currentTimeMillis() < jetzt4 + 500) { } page.savePic(stepImagePath); // zuerst 1 sekunde warten, dann autocrop long jetzt3 = System.currentTimeMillis(); while (System.currentTimeMillis() < jetzt3 + 1000) { } new AutoCropBorder(stepImagePath); stepTopologyImagePath.put(actualStep.getName(), stepImagePath); // farbe wieder auf grau aendern actualStep.setStatusOverwrite(null); System.out.println("erstelle bild fuer step: " + actualStep.getName()); long jetzt2 = System.currentTimeMillis(); while (System.currentTimeMillis() < jetzt2 + 1000) { } } page.destroy(); ////////////////////////////////////////// report = new Reporter(); // P03) erstellen des p03 System.out.println("info: generating p03."); String pdfPathP03 = null; String pptxPathP03 = null; String jasperPathP03 = null; String jasperFilledPathP03 = null; // P03) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p03") != null) { pdfPathP03 = randomPathPdf + "/p03.pdf"; pptxPathP03 = randomPathPptx + "/p03.pptx"; jasperPathP03 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p03"); jasperFilledPathP03 = (randomPathJasperFilled + "/p03.jasperFilled"); pdfRankFiles.put("0.0.03", pdfPathP03); pptxRankFiles.put("0.0.03", pptxPathP03); } else { System.err.println("no entry 'p03' found in ini file"); System.exit(1); } DateFormat dateFormat = new SimpleDateFormat("dd. MM. yyyy"); Date date = new Date(); report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processDatum", dateFormat.format(date)); report.setParameter("processArchitectLogoImagePath", installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "logo")); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); try { report.fillReportFileToFile(jasperPathP03, jasperFilledPathP03); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP03, pdfPathP03); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP03, pptxPathP03); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; //System.exit(0); ////////////////////////////////////////// report = new Reporter(); // P05) erstellen des p05 System.out.println("info: generating p05."); String pdfPathP05 = null; String pptxPathP05 = null; String jasperPathP05 = null; String jasperFilledPathP05 = null; // P05) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p05") != null) { pdfPathP05 = randomPathPdf + "/p05.pdf"; pptxPathP05 = randomPathPptx + "/p05.pptx"; jasperPathP05 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p05"); jasperFilledPathP05 = (randomPathJasperFilled + "/p05.jasperFilled"); pdfRankFiles.put("0.0.05", pdfPathP05); pptxRankFiles.put("0.0.05", pptxPathP05); } else { System.err.println("no entry 'p05' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); try { report.fillReportFileToFile(jasperPathP05, jasperFilledPathP05); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP05, pdfPathP05); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP05, pptxPathP05); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; //System.exit(0); ////////////////////////////////////////// report = new Reporter(); // P08) erstellen des p08 System.out.println("info: generating p08."); String pdfPathP08 = null; String pptxPathP08 = null; String jasperPathP08 = null; String jasperFilledPathP08 = null; // P08) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p08") != null) { pdfPathP08 = randomPathPdf + "/p08.pdf"; pptxPathP08 = randomPathPptx + "/p08.pptx"; jasperPathP08 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p08"); jasperFilledPathP08 = (randomPathJasperFilled + "/p08.jasperFilled"); pdfRankFiles.put("0.0.08", pdfPathP08); pptxRankFiles.put("0.0.08", pptxPathP08); } else { System.err.println("no entry 'p08' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); report.setParameter("processDescription", process.getDescription()); try { report.fillReportFileToFile(jasperPathP08, jasperFilledPathP08); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP08, pdfPathP08); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP08, pptxPathP08); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; //System.exit(0); ////////////////////////////////////////// report = new Reporter(); // P10) erstellen des p10 System.out.println("info: generating p10."); String pdfPathP10 = null; String pptxPathP10 = null; String jasperPathP10 = null; String jasperFilledPathP10 = null; // P10) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p10") != null) { pdfPathP10 = randomPathPdf + "/p10.pdf"; pptxPathP10 = randomPathPptx + "/p10.pptx"; jasperPathP10 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p10"); jasperFilledPathP10 = (randomPathJasperFilled + "/p10.jasperFilled"); pdfRankFiles.put("0.0.10", pdfPathP10); pptxRankFiles.put("0.0.10", pptxPathP10); } else { System.err.println("no entry 'p10' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); // rootstep holen Step rootStep = process.getStep(process.getRootstepname()); // ueber alle commit iterieren for (Commit actualCommit : rootStep.getCommit()) { // ueber alle files iterieren for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'origin' row.put("origin", "user/cb2"); // Spalte 'objectType' row.put("objectType", "file"); // Spalte 'minOccur' row.put("minOccur", "" + actualFile.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualFile.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualFile.getKey()); // die steps herausfinden, die dieses file benoetigen ArrayList<Step> allStepsThatNeedThisFileFromRoot = process.getStepWhichNeedFromRoot("file", actualFile.getKey()); String stepnameListe = ""; for (Step actStep : allStepsThatNeedThisFileFromRoot) { stepnameListe += "\n=> " + actStep.getName(); } // Spalte 'objectDescription' row.put("objectDescription", actualFile.getDescription() + stepnameListe); // Datensatz dem report hinzufuegen report.addField(row); } // ueber alle variablen iterieren for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'origin' row.put("origin", "user/cb2"); // Spalte 'objectType' row.put("objectType", "variable"); // Spalte 'minOccur' row.put("minOccur", "" + actualVariable.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualVariable.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualVariable.getKey()); // die steps herausfinden, die dieses file benoetigen ArrayList<Step> allStepsThatNeedThisObjectFromRoot = process.getStepWhichNeedFromRoot("variable", actualVariable.getKey()); String stepnameListe = ""; for (Step actStep : allStepsThatNeedThisObjectFromRoot) { stepnameListe += "\n=> " + actStep.getName(); } // Spalte 'objectDescription' row.put("objectDescription", actualVariable.getDescription() + stepnameListe); // Datensatz dem report hinzufuegen report.addField(row); } } try { report.fillReportFileToFile(jasperPathP10, jasperFilledPathP10); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP10, pdfPathP10); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP10, pptxPathP10); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; ////////////////////////////////////////// report = new Reporter(); // P20) erstellen des p20 System.out.println("info: generating p20."); String pdfPathP20 = null; String pptxPathP20 = null; String jasperPathP20 = null; String jasperFilledPathP20 = null; // P20) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p20") != null) { pdfPathP20 = randomPathPdf + "/p20.pdf"; pptxPathP20 = randomPathPptx + "/p20.pptx"; jasperPathP20 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p20"); jasperFilledPathP20 = (randomPathJasperFilled + "/p20.jasperFilled"); pdfRankFiles.put("0.0.20", pdfPathP20); pptxRankFiles.put("0.0.20", pptxPathP20); } else { System.err.println("no entry 'p20' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); // ueber alle steps iterieren (ausser root) for (Step actualStep : (ArrayList<Step>) process.getStep()) { // ueberspringen wenn es sich um root handelt if (!(actualStep.getName().equals(process.getRootstepname()))) { // ueber alle commit iterieren for (Commit actualCommit : actualStep.getCommit()) { // nur die, die toroot=true ( und spaeter auch tosdm=true) if (actualCommit.isTorootPresent()) { // ueber alle files iterieren for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'destination' row.put("destination", "user/cb2"); // Spalte 'objectType' row.put("objectType", "file"); // Spalte 'minOccur' row.put("minOccur", "" + actualFile.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualFile.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualFile.getKey()); // Spalte 'objectDescription' row.put("objectDescription", actualFile.getDescription() + "\n<= " + actualStep.getName()); // Datensatz dem report hinzufuegen report.addField(row); } // ueber alle variablen iterieren for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'objectType' row.put("destination", "user/cb2"); // Spalte 'objectType' row.put("objectType", "variable"); // Spalte 'minOccur' row.put("minOccur", "" + actualVariable.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualVariable.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualVariable.getKey()); // Spalte 'objectDescription' row.put("objectDescription", actualVariable.getDescription() + "\n<= " + actualStep.getName()); // Datensatz dem report hinzufuegen report.addField(row); } } } } } try { report.fillReportFileToFile(jasperPathP20, jasperFilledPathP20); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP20, pdfPathP20); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP20, pptxPathP20); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; ////////////////////////////////////////// report = new Reporter(); // P30) erstellen des p30 System.out.println("info: generating p30."); String pdfPathP30 = null; String pptxPathP30 = null; String jasperPathP30 = null; String jasperFilledPathP30 = null; // P30) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p30") != null) { pdfPathP30 = randomPathPdf + "/p30.pdf"; pptxPathP30 = randomPathPptx + "/p30.pptx"; jasperPathP30 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p30"); jasperFilledPathP30 = (randomPathJasperFilled + "/p30.jasperFilled"); pdfRankFiles.put("0.0.30", pdfPathP30); pptxRankFiles.put("0.0.30", pptxPathP30); } else { System.err.println("no entry 'p30' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); // P1) bild an report melden report.setParameter("processTopologyImagePath", processTopologyImagePath); try { report.fillReportFileToFile(jasperPathP30, jasperFilledPathP30); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP30, pdfPathP30); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP30, pptxPathP30); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; // System.exit(0); ////////////////////////////////////////// report = new Reporter(); // P40) erstellen des p40 System.out.println("info: generating p40."); String pdfPathP40 = null; String pptxPathP40 = null; String jasperPathP40 = null; String jasperFilledPathP40 = null; // P40) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p40") != null) { pdfPathP40 = randomPathPdf + "/p40.pdf"; pptxPathP40 = randomPathPptx + "/p40.pptx"; jasperPathP40 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p40"); jasperFilledPathP40 = (randomPathJasperFilled + "/p40.jasperFilled"); pdfRankFiles.put("0.0.40", pdfPathP40); pptxRankFiles.put("0.0.40", pptxPathP40); } else { System.err.println("no entry 'p40' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); // P40) bild an report melden report.setParameter("processTopologyImagePath", processTopologyImagePath); // Tabelle erzeugen ArrayList<Step> steps = process.getStep(); for (int x = 0; x < steps.size(); x++) { HashMap<String, Object> row = new HashMap<String, Object>(); Step actualStep = steps.get(x); // erste Spalte ist 'rank' // um die korrekte sortierung zu erhalten soll der rank-string auf jeweils 2 Stellen erweitert werden String[] rankArray = actualStep.getRank().split("\\."); Integer[] rankArrayInt = new Integer[rankArray.length]; for (int y = 0; y < rankArray.length; y++) { rankArrayInt[y] = Integer.parseInt(rankArray[y]); } String rankFormated = String.format("%02d.%02d", rankArrayInt); row.put("stepRank", rankFormated); // zweite Spalte ist 'stepname' row.put("stepName", actualStep.getName()); // System.out.println("stepName: "+actualStep.getName()); // dritte Spalte ist 'Beschreibung' row.put("stepDescription", actualStep.getDescription()); // System.out.println("stepRank: "+actualStep.getDescription()); // wenn nicht der root-step, dann row eintragen if (!(actualStep.getName().equals(process.getRootstepname()))) { report.addField(row); } } try { report.fillReportFileToFile(jasperPathP40, jasperFilledPathP40); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP40, pdfPathP40); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP40, pptxPathP40); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; ////////////////////////////////////////// // fuer jeden Step einen eigenen Input Report erzeugen for (Step actualStep : process.getStep()) { // root-step ueberspringen if (actualStep.getName().equals(process.getRootstepname())) { System.out.println("skipping step root"); } // alle anderen auswerten else { report = new Reporter(); // P51x) erstellen des p51 System.out.println( "info: generating p51 for step " + actualStep.getRank() + " => " + actualStep.getName()); String stepRank = actualStep.getRank(); String pdfPathP51 = null; String pptxPathP51 = null; String jasperPathP51 = null; String jasperFilledPathP51 = null; // P51x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p51") != null) { pdfPathP51 = randomPathPdf + "/p5." + stepRank + ".1.pdf"; pptxPathP51 = randomPathPptx + "/p5." + stepRank + ".1.pptx"; jasperPathP51 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p51"); jasperFilledPathP51 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled"; String[] rankArray = stepRank.split("\\."); Integer[] rankArrayInt = new Integer[rankArray.length]; for (int x = 0; x < rankArray.length; x++) { rankArrayInt[x] = Integer.parseInt(rankArray[x]); } String rankFormated = String.format("%03d.%03d", rankArrayInt); pdfRankFiles.put(rankFormated + ".1", pdfPathP51); pptxRankFiles.put(rankFormated + ".1", pptxPathP51); } else { System.err.println("no entry 'p51' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); report.setParameter("stepName", actualStep.getName()); report.setParameter("stepRank", stepRank); report.setParameter("stepDescription", actualStep.getDescription()); String aufruf = ""; if (actualStep.getWork() != null) { // zusammensetzen des scriptaufrufs String interpreter = ""; if (actualStep.getWork().getInterpreter() != null) { interpreter = actualStep.getWork().getInterpreter(); } aufruf = interpreter + " " + actualStep.getWork().getCommand(); for (Callitem actualCallitem : actualStep.getWork().getCallitem()) { aufruf += " " + actualCallitem.getPar(); if (!(actualCallitem.getDel() == null)) { aufruf += actualCallitem.getDel(); } if (!(actualCallitem.getVal() == null)) { aufruf += actualCallitem.getVal(); } } } else if (actualStep.getSubprocess() != null) { aufruf = ini.get("apps", "pkraft-startinstance"); aufruf += " --pdomain " + actualStep.getSubprocess().getDomain(); aufruf += " --pname " + actualStep.getSubprocess().getName(); aufruf += " --pversion " + actualStep.getSubprocess().getVersion(); for (Commit actCommit : actualStep.getSubprocess().getStep().getCommit()) { for (de.prozesskraft.pkraft.File actFile : actCommit.getFile()) { aufruf += " --commitfile " + actFile.getGlob(); } for (Variable actVariable : actCommit.getVariable()) { aufruf += " --commitvariable " + actVariable.getKey() + "=" + actVariable.getValue(); } } } report.setParameter("stepWorkCall", aufruf); // P51x) bild an report melden report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName())); // ueber alle lists iterieren for (List actualList : actualStep.getList()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'Woher?' row.put("origin", "-"); // Spalte 'typ' row.put("objectType", "wert"); // Spalte 'minOccur' row.put("minOccur", "-"); // Spalte 'maxOccur' row.put("maxOccur", "-"); // Spalte 'Label' row.put("objectKey", actualList.getName()); // Spalte 'Label' String listString = actualList.getItem().toString(); row.put("objectDescription", listString.substring(1, listString.length() - 1)); report.addField(row); } // ueber alle inits iterieren for (Init actualInit : actualStep.getInit()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'Woher?' if (actualInit.getFromstep().equals(process.getRootstepname())) { row.put("origin", "user/cb2"); } else { row.put("origin", actualInit.getFromstep()); } // Spalte 'typ' row.put("objectType", actualInit.getFromobjecttype()); // Spalte 'minOccur' row.put("minOccur", "" + actualInit.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualInit.getMaxoccur()); // Spalte 'Label' row.put("objectKey", actualInit.getListname()); // Spalte 'Label' row.put("objectDescription", "-"); report.addField(row); } try { report.fillReportFileToFile(jasperPathP51, jasperFilledPathP51); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP51, pdfPathP51); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP51, pptxPathP51); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; } } ////////////////////////////////////////// // fuer jeden Step einen eigenen Output Report erzeugen for (Step actualStep : process.getStep()) { // root-step ueberspringen if (actualStep.getName().equals(process.getRootstepname())) { System.out.println("skipping step root"); } // alle anderen auswerten else { report = new Reporter(); // P52x) erstellen des p52 System.out.println( "info: generating p52 for step " + actualStep.getRank() + " => " + actualStep.getName()); String stepRank = actualStep.getRank(); String pdfPathP52 = null; String pptxPathP52 = null; String jasperPathP52 = null; String jasperFilledPathP52 = null; // P52x) feststellen, welches jasperreports-template fuer den angeforderten typ verwendet werden soll if (ini.get("pkraft-createdoc", "p52") != null) { pdfPathP52 = randomPathPdf + "/p5." + stepRank + ".2.pdf"; pptxPathP52 = randomPathPptx + "/p5." + stepRank + ".2.pptx"; jasperPathP52 = installDir.getAbsolutePath() + "/" + ini.get("pkraft-createdoc", "p52"); jasperFilledPathP52 = randomPathJasperFilled + "/p5." + stepRank + ".1.jasperFilled"; String[] rankArray = stepRank.split("\\."); Integer[] rankArrayInt = new Integer[rankArray.length]; for (int x = 0; x < rankArray.length; x++) { rankArrayInt[x] = Integer.parseInt(rankArray[x]); } String rankFormated = String.format("%03d.%03d", rankArrayInt); pdfRankFiles.put(rankFormated + ".2", pdfPathP52); pptxRankFiles.put(rankFormated + ".2", pptxPathP52); } else { System.err.println("no entry 'p52' found in ini file"); System.exit(1); } report.setParameter("processName", process.getName()); report.setParameter("processVersion", process.getVersion()); report.setParameter("processArchitectCompany", process.getArchitectCompany()); report.setParameter("processArchitectName", process.getArchitectName()); report.setParameter("processArchitectMail", process.getArchitectMail()); report.setParameter("processCustomerCompany", process.getCustomerCompany()); report.setParameter("processCustomerName", process.getCustomerName()); report.setParameter("processCustomerMail", process.getCustomerMail()); report.setParameter("stepName", actualStep.getName()); report.setParameter("stepRank", stepRank); // logfile ermitteln String logfile = "-"; if (actualStep.getWork() != null) { if (actualStep.getWork().getLogfile() == null || actualStep.getWork().getLogfile().equals("")) { report.setParameter("stepWorkLogfile", actualStep.getWork().getLogfile()); } } else if (actualStep.getSubprocess() != null) { logfile = ".log"; } report.setParameter("stepWorkLogfile", logfile); // zusammensetzen der return/exitcode informationen String exitInfo = "exit 0 = kein fehler aufgetreten"; exitInfo += "\nexit >0 = ein fehler ist aufgetreten."; if (actualStep.getWork() != null) { for (Exit actualExit : actualStep.getWork().getExit()) { exitInfo += "\nexit " + actualExit.getValue() + " = " + actualExit.getMsg(); } } report.setParameter("stepWorkExit", exitInfo); // P52x) bild an report melden report.setParameter("stepTopologyImagePath", stepTopologyImagePath.get(actualStep.getName())); // ueber alle inits iterieren for (Commit actualCommit : actualStep.getCommit()) { // ueber alle files iterieren for (de.prozesskraft.pkraft.File actualFile : actualCommit.getFile()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'destination' if (actualCommit.isTorootPresent()) { row.put("destination", "user/cb2"); } else { row.put("destination", "prozessintern"); } // Spalte 'objectType' row.put("objectType", "file"); // Spalte 'minOccur' row.put("minOccur", "" + actualFile.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualFile.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualFile.getKey()); // Spalte 'objectDescription' row.put("objectDescription", actualFile.getDescription()); // Datensatz dem report hinzufuegen report.addField(row); } // ueber alle variablen iterieren for (de.prozesskraft.pkraft.Variable actualVariable : actualCommit.getVariable()) { HashMap<String, Object> row = new HashMap<String, Object>(); // Spalte 'destination' if (actualCommit.isTorootPresent()) { row.put("destination", "user/cb2"); } else { row.put("destination", "prozessintern"); } // Spalte 'objectType' row.put("objectType", "variable"); // Spalte 'minOccur' row.put("minOccur", "" + actualVariable.getMinoccur()); // Spalte 'maxOccur' row.put("maxOccur", "" + actualVariable.getMaxoccur()); // Spalte 'objectKey' row.put("objectKey", actualVariable.getKey()); // Spalte 'objectDescription' row.put("objectDescription", actualVariable.getDescription()); // Datensatz dem report hinzufuegen report.addField(row); } } try { report.fillReportFileToFile(jasperPathP52, jasperFilledPathP52); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pdf try { report.convertFileToPdf(jasperFilledPathP52, pdfPathP52); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } // export to pptx try { report.convertFileToPptx(jasperFilledPathP52, pptxPathP52); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } report = null; } } // warten bis alles auf platte geschrieben ist try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } // merge and output if (format.equals("pdf")) { mergePdf(pdfRankFiles, output); } else if (format.equals("pptx")) { mergePptx(pptxRankFiles, output); } System.out.println("info: generating process documentation ready."); System.exit(0); }