List of usage examples for java.util ArrayList add
public boolean add(E e)
From source file:jsdp.app.inventory.univariate.CapacitatedStochasticLotSizing.java
public static void main(String args[]) { boolean simulate = true; /******************************************************************* * Problem parameters/* w w w. ja va2 s .c o m*/ */ double fixedOrderingCost = 40; double proportionalOrderingCost = 0; double holdingCost = 1; double penaltyCost = 2; double maxOrderQuantity = 50; double[] meanDemand = { 20, 50, 20, 10, 20, 50 }; double coefficientOfVariation = 0.2; double truncationQuantile = 0.99; // Random variables Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length) .mapToObj(i -> new NormalDist(meanDemand[i], meanDemand[i] * coefficientOfVariation)) //.mapToObj(i -> new PoissonDist(meanDemand[i])) .toArray(Distribution[]::new); double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length) .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray(); double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length) .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray(); double initialInventory = 0; /******************************************************************* * Model definition */ // State space double stepSize = 1; //Stepsize must be 1 for discrete distributions double minState = -250; double maxState = 250; StateImpl.setStateBoundaries(stepSize, minState, maxState); // Actions Function<State, ArrayList<Action>> buildActionList = s -> { StateImpl state = (StateImpl) s; ArrayList<Action> feasibleActions = new ArrayList<Action>(); for (double i = state.getInitialState(); i <= StateImpl.getMaxState() && i <= state.getInitialState() + maxOrderQuantity; i += StateImpl.getStepSize()) { feasibleActions.add(new ActionImpl(state, i - state.getInitialState())); } return feasibleActions; }; Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0); // Immediate Value Function ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action, finalState) -> { ActionImpl a = (ActionImpl) action; StateImpl fs = (StateImpl) finalState; double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost) : 0; double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0) + penaltyCost * Math.max(-fs.getInitialState(), 0); return orderingCost + holdingAndPenaltyCost; }; // Random Outcome Function RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> { double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction() - ((StateImpl) finalState).getInitialState(); return realizedDemand; }; /******************************************************************* * Solve */ // Sampling scheme SamplingScheme samplingScheme = SamplingScheme.NONE; int maxSampleSize = 200; double reductionFactorPerStage = 1; // Value Function Processing Method: backward recursion double discountFactor = 1.0; BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions, supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList, idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage, HashType.HASHTABLE); System.out.println("--------------Backward recursion--------------"); recursion.runBackwardRecursionMonitoring(); System.out.println(); double ETC = recursion.getExpectedCost(initialInventory); StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory); double action = recursion.getOptimalAction(initialState).getAction(); long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU(); System.out.println( "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC); System.out.println("Optimal initial action: " + action); System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime()); System.out .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)"); System.out.println(); /******************************************************************* * Charting */ System.out.println("--------------Charting--------------"); int targetPeriod = 0; //If targetPeriod > 0 then no sampling! plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions, supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList, idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage, HashType.HASHTABLE); plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost System.out.println(); /******************************************************************* * Simulation */ System.out.println("--------------Simulation--------------"); double confidence = 0.95; //Simulation confidence level double errorTolerance = 0.0001; //Simulation error threshold if (simulate && samplingScheme == SamplingScheme.NONE) simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost, initialInventory, recursion, confidence, errorTolerance); else { if (!simulate) System.out.println("Simulation disabled."); if (samplingScheme != SamplingScheme.NONE) System.out.println( "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE."); } }
From source file:apps.Source2XML.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"); options.addOption("reparse_xml", null, false, "reparse each XML entry to ensure the parser doesn't fail"); Joiner commaJoin = Joiner.on(','); options.addOption("source_type", null, true, "document source type: " + commaJoin.join(SourceFactory.getDocSourceList())); Joiner spaceJoin = Joiner.on(' '); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter outputFile = null; int docNum = 0; if (USE_LEMMATIZER && USE_STEMMER) { System.err.println("Bug/inconsistent code: cann't use the stemmer and lemmatizer at the same time!"); System.exit(1);//ww w . java2 s . c o m } //Stemmer stemmer = new Stemmer(); KrovetzStemmer stemmer = new KrovetzStemmer(); System.out.println("Using Stanford NLP? " + USE_STANFORD); System.out.println("Using Stanford lemmatizer? " + USE_LEMMATIZER); System.out.println("Using stemmer? " + USE_STEMMER + (USE_STEMMER ? " (class: " + stemmer.getClass().getCanonicalName() + ")" : "")); try { CommandLine cmd = parser.parse(options, args); String inputFileName = null, outputFileName = null; if (cmd.hasOption("i")) { inputFileName = cmd.getOptionValue("i"); } else { Usage("Specify 'input file'", options); } if (cmd.hasOption("o")) { outputFileName = cmd.getOptionValue("o"); } else { Usage("Specify 'output file'", options); } outputFile = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outputFileName))); String sourceName = cmd.getOptionValue("source_type"); if (sourceName == null) Usage("Specify document source type", options); boolean reparseXML = options.hasOption("reparse_xml"); DocumentSource inpDocSource = SourceFactory.createDocumentSource(sourceName, inputFileName); DocumentEntry inpDoc = null; TextCleaner textCleaner = new TextCleaner( new DictNoComments(new File("data/stopwords.txt"), true /* lower case */), USE_STANFORD, USE_LEMMATIZER); Map<String, String> outputMap = new HashMap<String, String>(); outputMap.put(UtilConst.XML_FIELD_DOCNO, null); outputMap.put(UtilConst.XML_FIELD_TEXT, null); XmlHelper xmlHlp = new XmlHelper(); if (reparseXML) System.out.println("Will reparse every XML entry to verify correctness!"); while ((inpDoc = inpDocSource.next()) != null) { ++docNum; ArrayList<String> toks = textCleaner.cleanUp(inpDoc.mDocText); ArrayList<String> goodToks = new ArrayList<String>(); for (String s : toks) if (s.length() <= MAX_WORD_LEN && // Exclude long and short words s.length() >= MIN_WORD_LEN && isGoodWord(s)) goodToks.add(USE_STEMMER ? stemmer.stem(s) : s); String partlyCleanedText = spaceJoin.join(goodToks); String cleanText = XmlHelper.removeInvaildXMLChars(partlyCleanedText); // isGoodWord combiend with Stanford tokenizer should be quite restrictive already //cleanText = replaceSomePunct(cleanText); outputMap.replace(UtilConst.XML_FIELD_DOCNO, inpDoc.mDocId); outputMap.replace(UtilConst.XML_FIELD_TEXT, cleanText); String xml = xmlHlp.genXMLIndexEntry(outputMap); if (reparseXML) { try { XmlHelper.parseDocWithoutXMLDecl(xml); } catch (Exception e) { System.err.println("Error re-parsing xml for document ID: " + inpDoc.mDocId); System.exit(1); } } /* { System.out.println(inpDoc.mDocId); System.out.println("====================="); System.out.println(partlyCleanedText); System.out.println("====================="); System.out.println(cleanText); } */ try { outputFile.write(xml); outputFile.write(NL); } catch (Exception e) { e.printStackTrace(); System.err.println("Error processing/saving a document!"); } if (docNum % 1000 == 0) System.out.println(String.format("Processed %d documents", docNum)); } } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments" + e, options); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } finally { System.out.println(String.format("Processed %d documents", docNum)); try { if (null != outputFile) { outputFile.close(); System.out.println("Output file is closed! all seems to be fine..."); } } catch (IOException e) { System.err.println("IO exception: " + e); e.printStackTrace(); } } }
From source file:unalcol.termites.boxplots.BestAgentsPercentageInfoCollected.java
/** * For testing from the command line.//from w ww.j av a 2 s .c om * * @param args ignored. */ public static void main(final String[] args) { // double pf = Double.valueOf(args[0]); // System.out.println("pf:" + args[0]); /** * For saso paper */ /* double pf = 0; ArrayList<Double> pf0 = new ArrayList<>(); ArrayList<Double> pfg1 = new ArrayList<>(); ArrayList<Double> pfg2 = new ArrayList<>(); ArrayList<Double> pfg3 = new ArrayList<>(); pf0.add(0.0); pfg1.add(1.0E-4); pfg1.add(3.0E-4); pfg2.add(5.0E-4); pfg2.add(7.0E-4); pfg3.add(9.0E-4); // pfg3.add(1.0E-3); //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out)); final InformationCollected2 demo = new InformationCollected2("Information Collected", pf0); final InformationCollected2 demo1 = new InformationCollected2("Information Collected", pfg1); final InformationCollected2 demo2 = new InformationCollected2("Information Collected", pfg2); final InformationCollected2 demo3 = new InformationCollected2("Information Collected", pfg3); //demo.pack(); //RefineryUtilities.centerFrameOnScreen(demo); //demo.setVisible(true); */ if (args.length > 0) { experimentsDir = args[0]; } if (args.length > 1) { mazeMode = args[1]; } aMode = new String[args.length - 2]; for (int i = 2; i < args.length; i++) { aMode[i - 2] = args[i]; } ArrayList<Double> failureProbs = getFailureProbs(); for (Double pf : failureProbs) { ArrayList<Double> pfi = new ArrayList<>(); pfi.add(pf); final BestAgentsPercentageInfoCollected demo = new BestAgentsPercentageInfoCollected( "Information Collected", pfi); } /* Main with all Pictures by pf */ /*ArrayList<Double> pf0 = new ArrayList<>(); ArrayList<Double> pf1 = new ArrayList<>(); ArrayList<Double> pf3 = new ArrayList<>(); ArrayList<Double> pf5 = new ArrayList<>(); ArrayList<Double> pf7 = new ArrayList<>(); ArrayList<Double> pf9 = new ArrayList<>(); ArrayList<Double> pf01 = new ArrayList<>(); /* For the web site */ /*pf0.add(0.0); pf1.add(1.0E-4); pf3.add(3.0E-4); pf5.add(5.0E-4); pf7.add(7.0E-4); pf9.add(9.0E-4); pf01.add(1.0E-3); //pfg3.add(1.0E-3); //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out)); final BestAgentsPercentageInfoCollected demo = new BestAgentsPercentageInfoCollected("Information Collected", pf0); final BestAgentsPercentageInfoCollected demo1 = new BestAgentsPercentageInfoCollected("Information Collected", pf1); final BestAgentsPercentageInfoCollected demo2 = new BestAgentsPercentageInfoCollected("Information Collected", pf3); final BestAgentsPercentageInfoCollected demo3 = new BestAgentsPercentageInfoCollected("Information Collected", pf5); final BestAgentsPercentageInfoCollected demo4 = new BestAgentsPercentageInfoCollected("Information Collected", pf7); final BestAgentsPercentageInfoCollected demo5 = new BestAgentsPercentageInfoCollected("Information Collected", pf9); //final BestAgentsPercentageInfoCollected demo6 = new BestAgentsPercentageInfoCollected("Information Collected", pf01); */ }
From source file:unalcol.termites.boxplots.BestAgentsRoundInfoCollected.java
/** * For testing from the command line.//w ww .j av a 2 s. c om * * @param args ignored. */ public static void main(final String[] args) { // double pf = Double.valueOf(args[0]); // System.out.println("pf:" + args[0]); if (args.length > 0) { experimentsDir = args[0]; } if (args.length > 1) { mazeMode = args[1]; } aMode = new String[args.length - 2]; for (int i = 2; i < args.length; i++) { aMode[i - 2] = args[i]; } /** * For saso paper */ /* double pf = 0; ArrayList<Double> pf0 = new ArrayList<>(); ArrayList<Double> pfg1 = new ArrayList<>(); ArrayList<Double> pfg2 = new ArrayList<>(); ArrayList<Double> pfg3 = new ArrayList<>(); pf0.add(0.0); pfg1.add(1.0E-4); pfg1.add(3.0E-4); pfg2.add(5.0E-4); pfg2.add(7.0E-4); pfg3.add(9.0E-4); // pfg3.add(1.0E-3); //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out)); final InformationCollected2 demo = new InformationCollected2("Information Collected", pf0); final InformationCollected2 demo1 = new InformationCollected2("Information Collected", pfg1); final InformationCollected2 demo2 = new InformationCollected2("Information Collected", pfg2); final InformationCollected2 demo3 = new InformationCollected2("Information Collected", pfg3); //demo.pack(); //RefineryUtilities.centerFrameOnScreen(demo); //demo.setVisible(true); */ /* Main with all Pictures by pf */ ArrayList<Double> failureProbs = getFailureProbs(); for (Double pf : failureProbs) { ArrayList<Double> pfi = new ArrayList<>(); pfi.add(pf); final BestAgentsRoundInfoCollected demo = new BestAgentsRoundInfoCollected("Round Info Collected", pfi); } /*ArrayList<Double> pf0 = new ArrayList<>(); ArrayList<Double> pf1 = new ArrayList<>(); ArrayList<Double> pf3 = new ArrayList<>(); ArrayList<Double> pf5 = new ArrayList<>(); ArrayList<Double> pf7 = new ArrayList<>(); ArrayList<Double> pf9 = new ArrayList<>(); ArrayList<Double> pf01 = new ArrayList<>(); /* For the web site */ /* pf0.add(0.0); pf1.add(1.0E-4); pf3.add(3.0E-4); pf5.add(5.0E-4); pf7.add(7.0E-4); pf9.add(9.0E-4); pf01.add(1.0E-3); //pfg3.add(1.0E-3); //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out)); final BestAgentsRoundInfoCollected demo = new BestAgentsRoundInfoCollected("Round Info Collected", pf0); final BestAgentsRoundInfoCollected demo1 = new BestAgentsRoundInfoCollected("Round Info Collected", pf1); final BestAgentsRoundInfoCollected demo2 = new BestAgentsRoundInfoCollected("Round Info Collected", pf3); final BestAgentsRoundInfoCollected demo3 = new BestAgentsRoundInfoCollected("Round Info Collected", pf5); final BestAgentsRoundInfoCollected demo4 = new BestAgentsRoundInfoCollected("Round Info Collected", pf7); final BestAgentsRoundInfoCollected demo5 = new BestAgentsRoundInfoCollected("Round Info Collected", pf9); //final BestAgentsRoundInfoCollected demo6 = new BestAgentsRoundInfoCollected("Round Info Collected", pf01);*/ }
From source file:visualizer.datamining.dataanalysis.NeighborhoodPreservation.java
public static void main(String[] args) throws IOException { String outfile = "precision.txt"; String pointsfile = args[0];//from w w w .j av a 2 s . c o m String projsfile = "projfiles.txt"; int nrneighbors = Integer.parseInt(args[1]); DissimilarityType disstype = DissimilarityType.EUCLIDEAN; if (args[2].trim().toLowerCase().equals("cosine")) { disstype = DissimilarityType.COSINE_BASED; } ArrayList<String> projfiles = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(new File(projsfile))); String line = null; while ((line = br.readLine()) != null) { projfiles.add(line.trim()); } NeighborhoodPreservationEngine npe = new NeighborhoodPreservationEngine(); npe.neighborhoodPreservation(outfile, pointsfile, projfiles, disstype, nrneighbors); }
From source file:de.prozesskraft.ptest.Fingerprint.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/*from w ww.ja v a 2 s. c o m*/ // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.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 opath = OptionBuilder.withArgName("PATH").hasArg() .withDescription( "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.") // .isRequired() .create("path"); Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription( "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]") // .isRequired() .create("sizetol"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes") // .isRequired() .create("md5"); Option oignore = OptionBuilder.withArgName("STRING").hasArgs() .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint") // .isRequired() .create("ignore"); Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint") // .isRequired() .create("ignorefile"); Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file") // .isRequired() .create("output"); Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(opath); options.addOption(osizetol); options.addOption(omd5); options.addOption(oignore); options.addOption(oignorefile); options.addOption(ooutput); options.addOption(of); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fingerprint", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ String path = ""; String sizetol = ""; boolean md5 = false; Float sizetolFloat = null; String output = ""; java.io.File ignorefile = null; ArrayList<String> ignore = new ArrayList<String>(); if (!(commandline.hasOption("path"))) { System.err.println("setting default for -path=."); path = "."; } else { path = commandline.getOptionValue("path"); } if (!(commandline.hasOption("sizetol"))) { System.err.println("setting default for -sizetol=0.02"); sizetol = "0.02"; sizetolFloat = 0.02F; } else { sizetol = commandline.getOptionValue("sizetol"); sizetolFloat = Float.parseFloat(sizetol); if ((sizetolFloat > 1) || (sizetolFloat < 0)) { System.err.println("use only values >=0.0 and <1.0 for -sizetol"); System.exit(1); } } if (!(commandline.hasOption("md5"))) { System.err.println("setting default for -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); System.exit(1); } if (commandline.hasOption("ignore")) { ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore"))); } if (commandline.hasOption("ignorefile")) { ignorefile = new java.io.File(commandline.getOptionValue("ignorefile")); if (!ignorefile.exists()) { System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath()); } } if (!(commandline.hasOption("output"))) { System.err.println("setting default for -output=" + path + "/fingerprint.xml"); output = path + "/fingerprint.xml"; } else { output = commandline.getOptionValue("output"); } // wenn output bereits existiert -> abbruch java.io.File outputFile = new File(output); if (outputFile.exists()) { if (commandline.hasOption("f")) { outputFile.delete(); } else { System.err .println("error: output file (" + output + ") already exists. use -f to force overwrite."); System.exit(1); } } // if ( !( commandline.hasOption("output")) ) // { // System.err.println("option -output is mandatory."); // exiter(); // } /*---------------------------- 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 ----------------------------*/ Dir dir = new Dir(); dir.setBasepath(path); dir.setOutfilexml(output); // ignore file in ein Array lesen if ((ignorefile != null) && (ignorefile.exists())) { Scanner sc = new Scanner(ignorefile); while (sc.hasNextLine()) { ignore.add(sc.nextLine()); } sc.close(); } // // autoignore hinzufuegen // String autoIgnoreString = ini.get("autoignore", "autoignore"); // ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(","))); // // debug // System.out.println("ignorefile content:"); // for(String actLine : ignore) // { // System.out.println("line: "+actLine); // } try { dir.genFingerprint(sizetolFloat, md5, ignore); } catch (NullPointerException e) { System.err.println("file/dir does not exist " + path); e.printStackTrace(); exiter(); } catch (IOException e) { e.printStackTrace(); exiter(); } System.out.println("writing to file: " + dir.getOutfilexml()); dir.writeXml(); }
From source file:lineage.LineageEngine.java
public static void main(String[] args) { Options options = new Options(); // Commands//from w w w. j a va2 s. c o m options.addOption("build", false, "Construct the sample lineage trees"); // Input/Output/Display options.addOption("i", true, "Input file path [required]"); options.addOption("o", true, "Output file path (default: input file with suffix .trees.txt)"); options.addOption("cp", false, "Input data represents cell prevalaence (CP) values"); options.addOption("sampleProfile", false, "Input file contains the SSNV sample presence-absence profile (this will disable the default SSNV calling step)"); options.addOption("n", "normal", true, "Normal sample column id in the list of samples, 0-based (e.g 0 is the first column) [required without -sampleProfile]"); options.addOption("clustersFile", true, "SSNV clusters file path"); options.addOption("s", "save", true, "Maximum number of output trees to save (default: 1)"); options.addOption("showNetwork", "net", false, "Display the constraint network"); options.addOption("showTree", "tree", true, "Number of top-ranking trees to display (default: 0)"); // SSNV filtering / calling options.addOption("maxVAFAbsent", "absent", true, "Maximum VAF to robustly consider an SSNV as absent from a sample [required without -sampleProfile]"); options.addOption("minVAFPresent", "present", true, "Minimum VAF to robustly consider an SSNV as present in a sample [required without -sampleProfile]"); options.addOption("maxVAFValid", true, "Maximum allowed VAF in a sample (default: 0.6)"); options.addOption("minProfileSupport", true, "Minimum number of robust SSNVs required for a group presence-absence profile to be labeled robust (default: 2)"); // Network Construction / Tree Search options.addOption("minClusterSize", true, "Minimum size a cluster must have to be a considered a node in the network (default: 2)"); options.addOption("minPrivateClusterSize", true, "Minimum size a private mutation cluster must have to be a considered a node in the network (default: 1)"); options.addOption("minRobustNodeSupport", true, "Minimum number of robust SSNVs required for a node to be labeled robust during tree search: non-robust nodes can be removed from the network when no valid lineage trees are found (default: 2)"); options.addOption("maxClusterDist", true, "Maximum mean VAF difference up to which two clusters can be collapsed (default: 0.2)"); options.addOption("c", "completeNetwork", false, "Add all possible edges to the constraint network (default: private nodes are connected only to closest level parents; only nodes with no other parents are descendants of root)"); options.addOption("e", true, "VAF error margin (default: 0.1)"); options.addOption("nTreeQPCheck", true, "Number of top-ranking trees on which the QP consistency check is run, we have not seen this check fail in practice (default: 0, for best performance)"); options.addOption("v", "verbose", false, "Verbose mode"); options.addOption("h", "help", false, "Print usage"); // display order ArrayList<Option> optionsList = new ArrayList<Option>(); optionsList.add(options.getOption("build")); optionsList.add(options.getOption("i")); optionsList.add(options.getOption("o")); optionsList.add(options.getOption("cp")); optionsList.add(options.getOption("sampleProfile")); optionsList.add(options.getOption("n")); optionsList.add(options.getOption("clustersFile")); optionsList.add(options.getOption("s")); optionsList.add(options.getOption("net")); optionsList.add(options.getOption("tree")); optionsList.add(options.getOption("maxVAFAbsent")); optionsList.add(options.getOption("minVAFPresent")); optionsList.add(options.getOption("maxVAFValid")); optionsList.add(options.getOption("minProfileSupport")); optionsList.add(options.getOption("minClusterSize")); optionsList.add(options.getOption("minPrivateClusterSize")); optionsList.add(options.getOption("minRobustNodeSupport")); optionsList.add(options.getOption("maxClusterDist")); optionsList.add(options.getOption("c")); optionsList.add(options.getOption("e")); optionsList.add(options.getOption("nTreeQPCheck")); optionsList.add(options.getOption("v")); optionsList.add(options.getOption("h")); CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; HelpFormatter hf = new HelpFormatter(); hf.setOptionComparator(new OptionComarator<Option>(optionsList)); try { cmdLine = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); hf.printHelp("lichee", options); System.exit(-1); } // Set-up input args Args params = new Args(); if (cmdLine.hasOption("i")) { params.inputFileName = cmdLine.getOptionValue("i"); } else { System.out.println("Required parameter: input file path [-i]"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("o")) { params.outputFileName = cmdLine.getOptionValue("o"); } else { params.outputFileName = params.inputFileName + TREES_TXT_FILE_EXTENSION; } if (cmdLine.hasOption("clustersFile")) { params.clustersFileName = cmdLine.getOptionValue("clustersFile"); } if (cmdLine.hasOption("sampleProfile")) { Parameters.INPUT_FORMAT = Format.SNV_WITH_PROFILE; } if (cmdLine.hasOption("n")) { params.normalSampleId = Integer.parseInt(cmdLine.getOptionValue("n")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: normal sample id [-n]"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("showTree")) { params.numShow = Integer.parseInt(cmdLine.getOptionValue("showTree")); } if (cmdLine.hasOption("showNetwork")) { params.showNetwork = true; } if (cmdLine.hasOption("s")) { params.numSave = Integer.parseInt(cmdLine.getOptionValue("s")); } if (cmdLine.hasOption("maxVAFAbsent")) { Parameters.MAX_VAF_ABSENT = Double.parseDouble(cmdLine.getOptionValue("maxVAFAbsent")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: -maxVAFAbsent"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("minVAFPresent")) { Parameters.MIN_VAF_PRESENT = Double.parseDouble(cmdLine.getOptionValue("minVAFPresent")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: -minVAFPresent"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("maxVAFValid")) { Parameters.MAX_ALLOWED_VAF = Double.parseDouble(cmdLine.getOptionValue("maxVAFValid")); } if (cmdLine.hasOption("minProfileSupport")) { Parameters.MIN_GROUP_PROFILE_SUPPORT = Integer.parseInt(cmdLine.getOptionValue("minProfileSupport")); } if (cmdLine.hasOption("minClusterSize")) { Parameters.MIN_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minClusterSize")); } if (cmdLine.hasOption("minPrivateClusterSize")) { Parameters.MIN_PRIVATE_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minPrivateClusterSize")); } if (cmdLine.hasOption("minRobustNodeSupport")) { Parameters.MIN_ROBUST_CLUSTER_SUPPORT = Integer .parseInt(cmdLine.getOptionValue("minRobustNodeSupport")); } if (cmdLine.hasOption("maxClusterDist")) { Parameters.MAX_COLLAPSE_CLUSTER_DIFF = Double.parseDouble(cmdLine.getOptionValue("maxClusterDist")); } if (cmdLine.hasOption("c")) { Parameters.ALL_EDGES = true; } if (cmdLine.hasOption("cp")) { Parameters.CP = true; Parameters.VAF_MAX = 1.0; Parameters.MAX_ALLOWED_VAF = 1.0; } if (cmdLine.hasOption("e")) { Parameters.VAF_ERROR_MARGIN = Double.parseDouble(cmdLine.getOptionValue("e")); } if (cmdLine.hasOption("nTreeQPCheck")) { Parameters.NUM_TREES_FOR_CONSISTENCY_CHECK = Integer.parseInt(cmdLine.getOptionValue("nTreeQPCheck")); } if (cmdLine.hasOption("h")) { new HelpFormatter().printHelp(" ", options); } // logger ConsoleHandler h = new ConsoleHandler(); h.setFormatter(new LogFormatter()); h.setLevel(Level.INFO); logger.setLevel(Level.INFO); if (cmdLine.hasOption("v")) { h.setLevel(Level.FINEST); logger.setLevel(Level.FINEST); } logger.addHandler(h); logger.setUseParentHandlers(false); if (cmdLine.hasOption("build")) { buildLineage(params); } else { new HelpFormatter().printHelp("lichee", options); System.exit(-1); } }
From source file:de.prozesskraft.ptest.Compare.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/* w w w . j a v a 2 s . co m*/ // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.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 oref = OptionBuilder.withArgName("PATH").hasArg() .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against") // .isRequired() .create("ref"); Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription( "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref") // .isRequired() .create("exam"); Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file") // .isRequired() .create("result"); Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription( "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements") // .isRequired() .create("summary"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no") // .isRequired() .create("md5"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oref); options.addOption(oexam); options.addOption(oresult); options.addOption(osummary); options.addOption(omd5); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("compare", options); System.exit(0); } else if (commandline.hasOption("v")) { System.err.println("web: " + web); System.err.println("author: " + author); System.err.println("version:" + version); System.err.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ boolean error = false; String result = ""; boolean md5 = false; String ref = null; String exam = null; if (!(commandline.hasOption("ref"))) { System.err.println("option -ref is mandatory"); error = true; } else { ref = commandline.getOptionValue("ref"); } if (!(commandline.hasOption("exam"))) { java.io.File refFile = new java.io.File(ref).getCanonicalFile(); java.io.File examFile = refFile.getParentFile(); exam = examFile.getCanonicalPath(); System.err.println("setting default: -exam=" + exam); } else { exam = commandline.getOptionValue("exam"); } if (error) { exiter(); } if (!(commandline.hasOption("result"))) { System.err.println("setting default: -result=result.txt"); result = "result.txt"; } if (!(commandline.hasOption("md5"))) { System.err.println("setting default: -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); 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 ----------------------------*/ // einlesen der referenzdaten java.io.File refPath = new java.io.File(ref); Dir refDir = new Dir(); // wenn es ein directory ist, muss der fingerprint erzeugt werden if (refPath.exists() && refPath.isDirectory()) { refDir.setBasepath(refPath.getCanonicalPath()); refDir.genFingerprint(0f, true, new ArrayList<String>()); refDir.setRespectMd5Recursive(md5); System.err.println("-ref is a directory"); } // wenn es ein fingerprint ist, muss er eingelesen werden else if (refPath.exists()) { refDir.setInfilexml(refPath.getCanonicalPath()); System.err.println("-ref is a fingerprint"); try { refDir.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } refDir.setRespectMd5Recursive(md5); } else if (!refPath.exists()) { System.err.println("-ref does not exist! " + refPath.getAbsolutePath()); exiter(); } // einlesen der prueflingsdaten java.io.File examPath = new java.io.File(exam); Dir examDir = new Dir(); // wenn es ein directory ist, muss der fingerprint erzeugt werden if (examPath.exists() && examPath.isDirectory()) { examDir.setBasepath(examPath.getCanonicalPath()); examDir.genFingerprint(0f, true, new ArrayList<String>()); examDir.setRespectMd5Recursive(md5); System.err.println("-exam is a directory"); } // wenn es ein fingerprint ist, muss er eingelesen werden else if (examPath.exists()) { examDir.setInfilexml(examPath.getCanonicalPath()); System.err.println("-exam is a fingerprint"); try { examDir.readXml(); } catch (JAXBException e) { System.err.println("error while reading xml"); e.printStackTrace(); } examDir.setRespectMd5Recursive(md5); } else if (!examPath.exists()) { System.err.println("-exam does not exist! " + examPath.getAbsolutePath()); exiter(); } // durchfuehren des vergleichs refDir.runCheck(examDir); // if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive()) if (refDir.isMatchSuccessfullRecursive()) { System.out.println("SUCCESS"); } else { System.out.println("FAILED"); } // printen der csv-ergebnis-tabelle if (commandline.hasOption("summary")) { if (commandline.getOptionValue("summary").equals("error")) { System.err.println("the results of the reference are crucial for result FAILED|SUCCESS"); System.err.println(refDir.sprintSummaryAsCsv("error")); System.err.println(examDir.sprintSummaryAsCsv("error")); } else if (commandline.getOptionValue("summary").equals("all")) { System.err.println(refDir.sprintSummaryAsCsv("all")); System.err.println(examDir.sprintSummaryAsCsv("all")); } else if (commandline.getOptionValue("summary").equals("debug")) { System.err.println(refDir.sprintSummaryAsCsv("all")); System.err.println(examDir.sprintSummaryAsCsv("all")); // printen des loggings System.err.println("------ logging of reference --------"); System.err.println(refDir.getLogAsStringRecursive()); System.err.println("------ logging of examinee --------"); System.err.println(examDir.getLogAsStringRecursive()); } else { System.err.println("for option -summary you only may use all|error"); exiter(); } } }
From source file:com.phonytive.astive.server.AstiveServer.java
public static void main(String[] args) throws Exception { astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived"); adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread"); telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned"); ArrayList<ServiceProperties> serviceProperties = new ArrayList(); serviceProperties.add(astivedSP); if (!adminDaemonSP.isDisabled()) { serviceProperties.add(adminDaemonSP); }//w ww . ja v a 2 s . co m if (!telnedSP.isDisabled()) { serviceProperties.add(telnedSP); } if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) { printUsage(); System.exit(1); } // Create a Parser CommandLineParser parser = new BasicParser(); Options start = new Options(); start.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); start.addOption("v", "version", false, "Prints the Astive Server version and exits."); start.addOption("d", "debug", false, AppLocale.getI18n("cli.option.debug")); start.addOption("q", "quiet", false, AppLocale.getI18n("cli.option.daemonMode")); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind") .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "admin" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host") .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "astived" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port") .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "telned" })).create()); start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host") .withDescription("" + AppLocale.getI18n("cli.option.host", new Object[] { "telned" })).create()); Options stop = new Options(); stop.addOption(OptionBuilder.withLongOpt("--help") .withDescription("" + AppLocale.getI18n("cli.option.printUsage")).create()); stop.addOption("h", "host", false, AppLocale.getI18n("cli.option.stop.host", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR })); stop.addOption("p", "port", false, AppLocale.getI18n("cli.option.stop.port", new Object[] { DEFAULT_AGI_SERVER_PORT })); Options deploy = new Options(); deploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); Options undeploy = new Options(); undeploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage")); if (args.length == 0) { printUsage(); System.exit(1); } else if (!isCommand(args[0])) { printUnavailableCmd(args[0]); System.exit(1); } AdminCommand cmd = AdminCommand.get(args[0]); if (cmd.equals(AdminCommand.DEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) { logger.error(AppLocale.getI18n("cli.invalid.app")); printUsage(AdminCommand.DEPLOY, deploy); System.exit(1); } if (cmd.equals(AdminCommand.UNDEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) { printUsage(AdminCommand.UNDEPLOY, undeploy); System.exit(1); } // Parse the program arguments try { if (cmd.equals(AdminCommand.START)) { CommandLine commandLine = parser.parse(start, args); if (commandLine.hasOption('h')) { printUsage(cmd, start); System.exit(0); } if (commandLine.hasOption('v')) { // Them start the server without noise } if (commandLine.hasOption("astived-bind")) { astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("astived-port")) { astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port"))); } if (commandLine.hasOption("admin-bind")) { adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind"))); } if (commandLine.hasOption("admin-port")) { adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port"))); } if (commandLine.hasOption("telned-bind")) { telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind"))); } if (commandLine.hasOption("telned-port")) { adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port"))); } if (!NetUtil.available(astivedSP.getPort())) { out.println(AppLocale.getI18n("cantStartFastAgiServerSocket", new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() })); System.exit(-1); } if (!NetUtil.available(adminDaemonSP.getPort())) { adminDaemonSP.setUnableToOpen(true); } if (!NetUtil.available(telnedSP.getPort())) { telnedSP.setUnableToOpen(true); } InitOutput.printInit(serviceProperties); AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(), astivedSP.getBindAddr()); server.start(); } if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) { logger.info("unableToAccessAdminDaemon"); } if (cmd.equals(AdminCommand.STOP)) { CommandLine commandLine = parser.parse(stop, args); if (commandLine.hasOption("--help")) { printUsage(cmd, stop); System.exit(0); } if (commandLine.hasOption('h')) { if (commandLine.getOptionValue('h') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h'))); } if (commandLine.hasOption('p')) { if (commandLine.getOptionValue('p') == null) { printUsage(cmd, stop); System.exit(0); } astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p'))); } AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.stop(); } // TODO: This needs to be researched before a full implementation. // for now is only possible to do deployments into the local server. if (cmd.equals(AdminCommand.DEPLOY)) { AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.deploy(args[1]); } if (cmd.equals(AdminCommand.UNDEPLOY)) { AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(), adminDaemonSP.getPort()); adClient.undeploy(args[1]); } } catch (java.net.ConnectException ex) { logger.info("serverNotRunning"); } catch (Exception ex) { logger.error(AppLocale.getI18n("unexpectedError", new Object[] { ex.getMessage() })); } }
From source file:de.prozesskraft.pkraft.Merge.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from www . j ava 2 s . co m ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.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 oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] instance you want to merge another instance into.") // .isRequired() .create("instance"); Option oguest = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] this instance will be merged into -instance.") // .isRequired() .create("guest"); Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.") // .isRequired() .create("basedir"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oguest); options.addOption(obasedir); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("merge", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.err.println("option -instance is mandatory"); exiter(); } if (!(commandline.hasOption("guest"))) { System.err.println("at least one option -guest is mandatory"); exiter(); } /*---------------------------- 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 ----------------------------*/ String pathToInstance = commandline.getOptionValue("instance"); java.io.File fileInstance = new java.io.File(pathToInstance); String[] pathToGuest = commandline.getOptionValues("guest"); String baseDir = null; if (commandline.hasOption("basedir")) { java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir")); if (!fileBaseDir.exists()) { System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath()); exiter(); } else if (!fileBaseDir.isDirectory()) { System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath()); exiter(); } baseDir = commandline.getOptionValue("basedir"); } // ueberpruefen ob die process.pmb files vorhanden sind // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } for (String pathGuest : pathToGuest) { java.io.File fileGuest = new java.io.File(pathGuest); // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileGuest.exists()) { System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath()); exiter(); } } // base - instance einlesen Process p1 = new Process(); p1.setInfilebinary(pathToInstance); p1.setOutfilebinary(pathToInstance); Process p2 = p1.readBinary(); // alle guests einlesen ArrayList<Process> alleGuests = new ArrayList<Process>(); for (String actPathGuest : pathToGuest) { Process p30 = new Process(); p30.setInfilebinary(actPathGuest); Process pGuest = p30.readBinary(); // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind if (!p2.getName().equals(pGuest.getName())) { System.err.println("error: instances are not from the same type (-instance=" + p2.getName() + " != -guest=" + pGuest.getName()); exiter(); } // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind if (!p2.getVersion().equals(pGuest.getVersion())) { System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!=" + pGuest.getVersion()); exiter(); } alleGuests.add(pGuest); } // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen Process p3 = new Process(); p3.setInfilebinary(pathToInstance); Process process = p3.readBinary(); // den main-prozess ueber die static function klonen // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind Process clonedProcess = cloneProcess(process, null); // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren for (Step actStep : process.getStep()) { if (actStep.getSubprocess() != null) { Process pDummy = new Process(); pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb"); Process processInSubprocess = pDummy.readBinary(); // System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb"); if (processInSubprocess != null) { Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } } // alle dependent steps der zielinstanz einsammeln // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden Map<Step, String> dependentSteps = new HashMap<Step, String>(); // alle guest prozesse merge durchfuehren for (Process actGuestProcess : alleGuests) { System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary()); // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren for (Step actStep : actGuestProcess.getStep()) { if (actStep.isAFannedMultistep()) { System.err.println("info: merging from guest instance step " + actStep.getName()); Step clonedStepForIntegrationInClonedProcess = actStep.clone(); if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) { System.err.println("info: merging step successfully."); // die downstream steps vom merge-punkt merken for (Step actStepToResetBecauseOfDependency : clonedProcess .getStepDependent(actStep.getName())) { dependentSteps.put(actStepToResetBecauseOfDependency, "dummy"); } // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden // den prozess in pradar anmelden durch aufruf des tools: pradar-attend if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) { String call5 = ini.get("apps", "pradar-attend") + " -instance " + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb"; System.err.println("info: calling: " + call5); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call5); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } else { System.err.println("error: merging step failed."); } } else { System.err.println("debug: because it's not a multistep, ignoring from guest instance step " + actStep.getName()); } } } // alle steps downstream der merge-positionen resetten for (Step actStep : dependentSteps.keySet()) { actStep.resetBecauseOfDependency(); } // speichern der ergebnis instanz clonedProcess.writeBinary(); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } }