List of usage examples for java.util ArrayList add
public boolean add(E e)
From source file:de.prozesskraft.pkraft.Startinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from w ww. j av a2 s .c o m ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/" + "../etc/pkraft-startinstance.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 obasedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[optional, default .] base directory where instance shourd run.") // .isRequired() .create("basedir"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[optional] definition file of the process you want to start an instance from.") // .isRequired() .create("definition"); Option onostart = OptionBuilder.withArgName("") // .hasArg() .withDescription( "[optional] oppresses the start of the instance. (only create the process-instance)") // .isRequired() .create("nostart"); Option opdomain = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] domain of the process (mandatory if you omit -definition)") // .isRequired() .create("pdomain"); Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pname"); Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pversion"); Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg() .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.") // .isRequired() .create("commitfile"); Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg() .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE") // .isRequired() .create("commitvariable"); Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription( "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.") // .isRequired() .create("commitfiledummy"); Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription( "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.") // .isRequired() .create("commitvariabledummy"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(obasedir); options.addOption(odefinition); options.addOption(onostart); options.addOption(opname); options.addOption(opversion); options.addOption(ocommitfile); options.addOption(ocommitvariable); options.addOption(ocommitfiledummy); options.addOption(ocommitvariabledummy); /*---------------------------- 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("startinstance", 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("definition")) && (!(commandline.hasOption("pname")) || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion")) || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) { System.err.println("you must not use option -definition with -pversion or -pname or -pdomain"); 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 ----------------------------*/ Process p1 = new Process(); String pathToDefinition = ""; if (commandline.hasOption("definition")) { pathToDefinition = commandline.getOptionValue("definition"); } else if (commandline.hasOption("pname") && commandline.hasOption("pversion") && commandline.hasOption("pdomain")) { pathToDefinition.replaceAll("/+$", ""); pathToDefinition = ini.get("process", "domain-installation-directory") + "/" + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/" + commandline.getOptionValue("pversion") + "/process.xml"; } else { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert java.io.File xmlDefinition = new java.io.File(pathToDefinition); if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) { System.err.println("process definition does not exist: " + pathToDefinition); exiter(); } p1.setInfilexml(xmlDefinition.getCanonicalPath()); Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e1) { System.err.println(e1.getMessage()); } // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will // root-verzeichnis erstellen if (commandline.hasOption("basedir")) { p2.setBaseDir(commandline.getOptionValue("basedir")); } p2.makeRootdir(); // den pfad fuers binary setzen p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); // step, an den die commits gehen, soll 'root' sein. Step stepRoot = p2.getRootStep(); // committen von files (ueber einen glob) if (commandline.hasOption("commitfile")) { for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) { String[] parts = actOptionCommitfile.split("="); File userFile = new File(); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfile " + actOptionCommitfile); exiter(); } // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (File actFile : actCommit.getFile()) { if (actFile.getKey().equals(userFile.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actFile.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) { File newFile = actFile.clone(); newFile.setGlob(userFile.getGlob()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + newFile.getKey() + "=" + newFile.getGlob() + ")"); actCommit.addFile(newFile); break; } else { System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " " + actFile.getKey() + "-files into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actFile.setGlob(userFile.getGlob()); actFile.setGlobdir(p2.getBaseDir()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + actFile.getKey() + "=" + actFile.getGlob() + ")"); break; } } } } } } // committen von files (ueber einen glob) if (commandline.hasOption("commitfiledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitFiledummy = new Commit(); commitFiledummy.setName("fileDummy"); stepRoot.addCommit(commitFiledummy); for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) { String[] parts = actOptionCommitfiledummy.split("="); File userFile = new File(); commitFiledummy.addFile(userFile); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy); exiter(); } userFile.setGlobdir(p2.getBaseDir()); System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' (" + userFile.getKey() + "=" + userFile.getGlob() + ")"); } } if (commandline.hasOption("commitvariable")) { for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) { if (actOptionCommitvariable.matches(".+=.+")) { String[] parts = actOptionCommitvariable.split("="); Variable userVariable = new Variable(); if (parts.length == 1) { userVariable.setKey("default"); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariable"); exiter(); } // commit.addVariable(variable); // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (Variable actVariable : actCommit.getVariable()) { if (actVariable.getKey().equals(userVariable.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actVariable.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getVariable(actVariable.getKey()).size() < actVariable .getMaxoccur()) { Variable newVariable = actVariable.clone(); newVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + newVariable.getKey() + "=" + newVariable.getValue() + ")"); actCommit.addVariable(newVariable); break; } else { System.err.println("fatal: you only may commit " + actVariable.getMaxoccur() + " " + actVariable.getKey() + "-variable(s) into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")"); break; } } } } } else { System.err.println("-commitvariable " + actOptionCommitvariable + " does not match pattern \"NAME=VALUE\"."); exiter(); } } } if (commandline.hasOption("commitvariabledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitVariabledummy = new Commit(); commitVariabledummy.setName("variableDummy"); stepRoot.addCommit(commitVariabledummy); for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) { String[] parts = actOptionCommitvariabledummy.split("="); Variable userVariable = new Variable(); commitVariabledummy.addVariable(userVariable); if (parts.length == 1) { userVariable.setKey(parts[0]); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariabledummy"); exiter(); } System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' (" + userVariable.getKey() + "=" + userVariable.getValue() + ")"); } } // if (commandline.hasOption("basedir")) // { // p2.setBaseDir(commandline.getOptionValue("basedir")); // } // commit.doIt(); stepRoot.commit(); // root-verzeichnis erstellen p2.makeRootdir(); // den pfad fuers binary setzen // p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); try { Thread.sleep(1500, 0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Runtime.getRuntime().exec("process-manager -help"); // starten nur, falls es nicht abgewaehlt wurde if (!commandline.hasOption("nostart")) { System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary()); String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary(); System.err.println("calling: " + aufrufString); ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(aufrufString.split(" "))); ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary()); // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // System.out.println("PATH: "+path); // java.lang.Process p = pb.start(); System.err.println("pid: " + p.hashCode()); } else { System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary()); } }
From source file:minikbextractor.MiniKBextractor.java
/** * @param args the command line arguments *///from w w w . ja v a2 s .c om public static void main(String[] args) { String adomFile = "in/agronomicTaxon.owl"; ArrayList<Source> sources = new ArrayList(); SparqlProxy spInAgrovoc = SparqlProxy .getSparqlProxy("http://amarger.murloc.fr:8080/Agrovoc2KB_TESTClass_out/"); HashMap<String, String> limitSpOutAgrovoc = new HashMap<>(); //limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_5608", "http://amarger.murloc.fr:8080/Agrovoc_mini_Paspalum/"); limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_148", "http://amarger.murloc.fr:8080/Agrovoc_mini_Aegilops/"); //imitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_5435", "http://amarger.murloc.fr:8080/Agrovoc_mini_Oryza/"); limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_7950", "http://amarger.murloc.fr:8080/Agrovoc_mini_Triticum/"); String nameAgrovoc = "Agrovoc"; sources.add(new Source(spInAgrovoc, nameAgrovoc, limitSpOutAgrovoc, adomFile)); SparqlProxy spInTaxRef = SparqlProxy.getSparqlProxy("http://amarger.murloc.fr:8080/TaxRef2RKB_out_TEST/"); HashMap<String, String> limitSpOutTaxRef = new HashMap<>(); //limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/195870", "http://amarger.murloc.fr:8080/TaxRef_mini_Paspalum/"); limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/188834", "http://amarger.murloc.fr:8080/TaxRef_mini_Aegilops/"); //limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/195564", "http://amarger.murloc.fr:8080/TaxRef_mini_Oryza/"); limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/198676", "http://amarger.murloc.fr:8080/TaxRef_mini_Triticum/"); //String limitUriTaxRef = "http://inpn.mnhn.fr/espece/cd_nom/187444"; //Poaceae String nameTaxRef = "TaxRef "; sources.add(new Source(spInTaxRef, nameTaxRef, limitSpOutTaxRef, adomFile)); SparqlProxy spInNCBI = SparqlProxy.getSparqlProxy("http://amarger.murloc.fr:8080/Ncbi2RKB_out/"); HashMap<String, String> limitSpOutNCBI = new HashMap<>(); //limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=147271", "http://amarger.murloc.fr:8080/NCBI_mini_Paspalum/"); limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4480", "http://amarger.murloc.fr:8080/NCBI_mini_Aegilops/"); //limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4527", "http://amarger.murloc.fr:8080/NCBI_mini_Oryza/"); limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4564", "http://amarger.murloc.fr:8080/NCBI_mini_Triticum/"); String nameNCBI = "NCBI"; sources.add(new Source(spInNCBI, nameNCBI, limitSpOutNCBI, adomFile)); for (Source s : sources) { //System.out.println(s.getStatUnderLimit()); s.exportAllSubRKB(); System.out.println("------------------------------------"); } System.exit(0); }
From source file:in.sc.dao.ProductHelper.java
public static void main(String[] args) { HashMap a = new HashMap(); ArrayList brandL = new ArrayList(); brandL.add("apple"); brandL.add("sony"); // a.put(category, 137); // a.put(country, 1); a.put(brand, brandL);/* w ww . j a v a 2 s.co m*/ String whereC = " AND (CAST(TRIM(f13) AS DECIMAL(10,2)) =1 or CAST(TRIM(f13) AS DECIMAL(10,2)) =2) and CAST(TRIM(f14) AS DECIMAL(10,2)) BETWEEN 1.3 AND 2.7 "; // a.put(unique_id, "panasonic-p66-mega"); a.put(from, 0); a.put(whereclause, whereC); try { ArrayList<ProductBean> data = (ArrayList) new ProductHelper().getProductLists1(a); int cnt = 0; for (Object o : data) { // System.out.println("" + o); cnt++; } // System.out.println("count " + cnt); } catch (Exception e) { e.printStackTrace(); } }
From source file:ConsumerTool.java
public static void main(String[] args) { ArrayList<ConsumerTool> threads = new ArrayList(); ConsumerTool consumerTool = new ConsumerTool(); String[] unknown = CommandLineSupport.setOptions(consumerTool, args); if (unknown.length > 0) { System.out.println("Unknown options: " + Arrays.toString(unknown)); System.exit(-1);//from www.jav a 2 s . c o m } consumerTool.showParameters(); for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) { consumerTool = new ConsumerTool(); CommandLineSupport.setOptions(consumerTool, args); consumerTool.start(); threads.add(consumerTool); } while (true) { Iterator<ConsumerTool> itr = threads.iterator(); int running = 0; while (itr.hasNext()) { ConsumerTool thread = itr.next(); if (thread.isAlive()) { running++; } } if (running <= 0) { System.out.println("All threads completed their work"); break; } try { Thread.sleep(1000); } catch (Exception e) { } } Iterator<ConsumerTool> itr = threads.iterator(); while (itr.hasNext()) { ConsumerTool thread = itr.next(); } }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
/** * @param args/* w w w .ja v a2 s.c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { String duration = null; String scenarioFile = null; // ------------------------------------------------------------------- // INITIALIZE LOGGING // ------------------------------------------------------------------- String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // ------------------------------------------------------------------- // PARSE COMMAND LINE PARAMETERS // ------------------------------------------------------------------- CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("s", "scenario", true, "[required] Workload scenario file"); options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation"); options.addOption("r", "runtime", true, "maximum runtime (no events will be started after finishing runtime)"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("g", "gui", false, "Show controlling GUI"); options.addOption("h", "help", false, "Print this help"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("b", "baseline", true, "Output files of previous baseline run"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (!argsLine.hasOption("scenario")) { INIT_LOG.fatal("Missing scenario description file"); System.exit(-1); } else scenarioFile = argsLine.getOptionValue("scenario"); if (argsLine.hasOption("r")) duration = argsLine.getOptionValue("r"); if (argsLine.hasOption("runtime")) duration = argsLine.getOptionValue("runtime"); // ------------------------------------------------------------------- // CREATE TENANT SCHEDULE // ------------------------------------------------------------------- INIT_LOG.info("Create schedule"); Schedule schedule = new Schedule(duration, scenarioFile); HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents(); ArrayList<Integer> tenantList = schedule.getTenantList(); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) { int tenantID = tenantList.get(tenInd); for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) { BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID) .getBenchmarkSettings(tenEvent); // update benchmark Settings benchmarkSettings.setTenantID(tenantID); // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = benchmarkSettings.getBenchmark(); String[] pluginList = plugins.split(","); String configFile = benchmarkSettings.getConfigFile(); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setTenantId(tenantID); wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID)); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID))); wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID)); wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID)); wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID)); wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID)); wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID)); String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"), tenantID); int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString)); wrkld.setTerminals(terminals); int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1")); if (taSize < 0) INIT_LOG.fatal("taSize must not be negative!"); wrkld.setTaSize(taSize); wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false)); wrkld.setIsolationMode(setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID)); wrkld.setScaleFactor(Double .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID))); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or // single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID); rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string), tenantID); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format( "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Tenant " + tenantID + ": Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format( "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)), tenantID)); activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)), tenantID)); if (activeTerminals > terminals) { LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); if (numTxnTypes == 0 && pluginList.length == 1) { // if it is a single workload run, <transactiontypes /> // w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format("Tenant " + tenantID + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID)); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = Integer .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID)); } ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset)); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); if (benchmarkSettings.getBenchmarkSlaFile() != null) wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile()); LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt); bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent)); bench.setTenantID(tenantID); bench.setBenchmarkSettings(benchmarkSettings); benchList.add(bench); } } } // create result collector ResultCollector rCollector = new ResultCollector(tenantList); // execute benchmarks in parallel ArrayList<Thread> benchThreads = new ArrayList<Thread>(); for (BenchmarkModule benchmark : benchList) { BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine); Thread t = new Thread(benchThread); t.start(); benchThreads.add(t); benchmark.getWorkloadConfiguration().setrCollector(rCollector); } // waiting for completion of all benchmarks for (Thread t : benchThreads) { t.join(); } // print statistics int analysisBuckets = -1; if (argsLine.hasOption("analysis-buckets")) analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets")); String output = null; if (argsLine.hasOption("o")) output = argsLine.getOptionValue("o"); String baseline = null; if (argsLine.hasOption("b")) baseline = argsLine.getOptionValue("b"); rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline); // create GUI if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) { try { Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector, output); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java
public static void main(String[] args) { if (args.length != 4) { System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n" + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n" + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n"); } else {//from w ww . ja v a2 s . c o m BufferedWriter outBuff = null; try { File inFile = new File(args[0]); File fastaFile = new File(args[1]); File outFile = new File(args[2]); File blastFile = new File(args[3]); //Primero cargo todos los datos del archivo xml del blast BufferedReader buffReader = new BufferedReader(new FileReader(blastFile)); StringBuilder stBuilder = new StringBuilder(); String line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); System.out.println("Creating blastoutput..."); BlastOutput blastOutput = new BlastOutput(stBuilder.toString()); System.out.println("BlastOutput created! :)"); stBuilder.delete(0, stBuilder.length()); HashMap<String, String> blastProteinsMap = new HashMap<String, String>(); ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations(); for (Iteration iteration : iterations) { blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString()); } //freeing some memory blastOutput = null; //------------------------------------------------------------------------ //Initializing writer for output file outBuff = new BufferedWriter(new FileWriter(outFile)); //reading gene annotation xml file..... buffReader = new BufferedReader(new FileReader(inFile)); stBuilder = new StringBuilder(); line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); XMLElement genesXML = new XMLElement(stBuilder.toString()); //freeing some memory I don't need anymore stBuilder.delete(0, stBuilder.length()); //reading file with the reference proteins set ArrayList<String> proteinsReferenceSet = new ArrayList<String>(); buffReader = new BufferedReader(new FileReader(fastaFile)); while ((line = buffReader.readLine()) != null) { if (line.charAt(0) == '>') { proteinsReferenceSet.add(line.split("\\|")[1]); } } buffReader.close(); Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME); List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME); System.out.println("There are " + contigs.size() + " contigs to be checked... "); outBuff.write("There are " + contigs.size() + " contigs to be checked... \n"); outBuff.write("Proteins reference set: \n"); for (String st : proteinsReferenceSet) { outBuff.write(st + ","); } outBuff.write("\n"); for (Element elem : contigs) { ContigXML contig = new ContigXML(elem); //escribo el id del contig en el que estoy outBuff.write("Checking contig: " + contig.getId() + "\n"); outBuff.flush(); List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME); System.out.println("geneList.size() = " + geneList.size()); int numeroDeGenesParaAnalizar = geneList.size() / FACTOR; if (numeroDeGenesParaAnalizar == 0) { numeroDeGenesParaAnalizar++; } ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>(); outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: " + numeroDeGenesParaAnalizar + "\n"); for (int j = 0; j < numeroDeGenesParaAnalizar; j++) { int geneIndex; boolean geneIsDismissed = false; do { geneIsDismissed = false; geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size())); PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) { geneIsDismissed = true; } } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed); indicesUtilizados.add(geneIndex); System.out.println("geneIndex = " + geneIndex); //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: " + gene.getAnnotationUniprotId() + "\n"); outBuff.write("eValue: " + gene.getEvalue() + "\n"); //--------------PETICION POST HTTP BLAST---------------------- PostMethod post = new PostMethod(BLAST_URL); post.addParameter("program", "blastx"); post.addParameter("sequence", gene.getSequence()); post.addParameter("database", "uniprotkb"); post.addParameter("email", "ppareja@era7.com"); post.addParameter("exp", "1e-10"); post.addParameter("stype", "dna"); // execute the POST HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("status post = " + status); InputStream inStream = post.getResponseBodyAsStream(); String fileName = "jobid.txt"; FileOutputStream outStream = new FileOutputStream(new File(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); String jobId = buffReader.readLine(); buffReader.close(); System.out.println("jobId = " + jobId); //--------------HTTP CHECK JOB STATUS REQUEST---------------------- GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId); String jobStatus = ""; do { try { Thread.sleep(1000);//sleep for 1000 ms } catch (InterruptedException ie) { //If this thread was intrrupted by nother thread } status = client.executeMethod(get); //System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobStatus.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); jobStatus = buffReader.readLine(); //System.out.println("jobStatus = " + jobStatus); buffReader.close(); } while (!jobStatus.equals(FINISHED_JOB_STATUS)); //Once I'm here the blast should've already finished //--------------JOB RESULTS HTTP REQUEST---------------------- get = new GetMethod(JOB_RESULT_URL + jobId + "/out"); status = client.executeMethod(get); System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobResults.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //--------parsing the blast results file----- TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>(); buffReader = new BufferedReader(new FileReader(new File(fileName))); while ((line = buffReader.readLine()) != null) { if (line.length() > 3) { String prefix = line.substring(0, 3); if (prefix.equals("TR:") || prefix.equals("SP:")) { String[] columns = line.split(" "); String id = columns[1]; //System.out.println("id = " + id); String e = ""; String[] arraySt = line.split("\\.\\.\\."); if (arraySt.length > 1) { arraySt = arraySt[1].trim().split(" "); int contador = 0; for (int k = 0; k < arraySt.length && contador <= 2; k++) { String string = arraySt[k]; if (!string.equals("")) { contador++; if (contador == 2) { e = string; } } } } else { //Number before e- String[] arr = arraySt[0].split("e-")[0].split(" "); String numeroAntesE = arr[arr.length - 1]; String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0]; e = numeroAntesE + "e-" + numeroDespuesE; } double eValue = Double.parseDouble(e); //System.out.println("eValue = " + eValue); GeneEValuePair g = new GeneEValuePair(id, eValue); featuresBlast.add(g); } } } GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(), gene.getEvalue()); System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id); System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue); boolean blastContainsGene = false; for (GeneEValuePair geneEValuePair : featuresBlast) { if (geneEValuePair.id.equals(currentGeneEValuePair.id)) { blastContainsGene = true; //le pongo la e que tiene en el wu-blast para poder comparar currentGeneEValuePair.eValue = geneEValuePair.eValue; break; } } if (blastContainsGene) { outBuff.write("The protein was found in the WU-BLAST result.. \n"); //Una vez que se que esta en el blast tengo que ver que sea la mejor GeneEValuePair first = featuresBlast.first(); outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id + " , " + first.eValue + "\n"); if (first.id.equals(currentGeneEValuePair.id)) { outBuff.write("Proteins with best eValue match up \n"); } else { if (first.eValue == currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has the same eValue \n"); } else if (first.eValue > currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has a worse eValue :) \n"); } else { outBuff.write( "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n"); //System.exit(-1); if (proteinsReferenceSet.contains(first.id)) { //The protein is in the reference set and that shouldn't happen outBuff.write( "The protein was found on the reference set, checking if it belongs to the same contig...\n"); String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId()); if (iterationSt != null) { outBuff.write( "The protein was found in the BLAST used at the beginning of the annotation process.\n"); Iteration iteration = new Iteration(iterationSt); ArrayList<Hit> hits = iteration.getIterationHits(); boolean contigFound = false; Hit errorHit = null; for (Hit hit : hits) { if (hit.getHitDef().indexOf(contig.getId()) >= 0) { contigFound = true; errorHit = hit; break; } } if (contigFound) { outBuff.write( "ERROR: A hit from the same contig was find in the Blast file: \n" + errorHit.toString() + "\n"); } else { outBuff.write("There is no hit with the same contig! :)\n"); } } else { outBuff.write( "The protein is NOT in the BLAST used at the beginning of the annotation process.\n"); } } else { //The protein was not found on the reference set so everything's ok outBuff.write( "The protein was not found on the reference, everything's ok :)\n"); } } } } else { outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n"); //System.exit(-1); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { //closing outputfile outBuff.close(); } catch (IOException ex) { Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java
/** * * @param args/*from www . ja v a 2 s .c om*/ * @throws Exception */ public static void main(String[] args) throws Exception { ArrayList<String> acs = new ArrayList<>(); acs.add("P84022"); HashMap<String, MoleculeEntry> prots = UniprotkbUtils.getInstance("9606") .getUniprotEntriesFromUniprotAccessions(acs); for (MoleculeEntry entry : prots.values()) { System.out.println(entry); for (String pdb : entry.getPdbs()) { System.out.println("# " + pdb); for (ChainMapping chain : entry.getChains(pdb)) { System.out.println("- " + pdb + ": " + chain.getChain()); } } System.out.println("Diseases: " + StringUtils.join(entry.getDiseases(), ", ")); } }
From source file:jCloisterZone.CarcassonneEnvironment.java
public static void main(String[] args) { int repetitions = 100; double[] scores = new double[repetitions]; RRLJCloisterClient client = new LocalCarcassonneClient("config.ini"); ServerIF server = null;/*w w w .j ava2 s. co m*/ Game game = client.getGame(); Player firstPlayer = null; ArrayList<PlayerSlot> slots = new ArrayList<PlayerSlot>(); for (int r = 0; r < repetitions; r++) { client.createGame(); if (game == null) { server = new LocalCarcassonneServer(client.getGame()); PlayerSlot slot = new PlayerSlot(0, PlayerSlot.SlotType.AI, "RANDOM" + 0, client.getClientId()); slot.setAiClassName(RandomAIPlayer.class.getName()); slots.add(slot); for (int j = 1; j < Integer.parseInt(args[0]); j++) { slot = new PlayerSlot(j, PlayerSlot.SlotType.AI, "AI" + j, client.getClientId()); slot.setAiClassName(LegacyAiPlayer.class.getName()); slots.add(slot); } game = client.getGame(); } else { // Reset the UIs server.stopGame(); game.clearUserInterface(); // Clear the slots and re-add them. for (int i = 0; i < PlayerSlot.COUNT; i++) { server.updateSlot(new PlayerSlot(i), null); } } Collections.shuffle(slots); for (int i = 0; i < slots.size(); i++) { PlayerSlot slot = slots.get(i); PlayerSlot cloneSlot = new PlayerSlot(i, slot.getType(), slot.getNick(), slot.getOwner()); cloneSlot.setAiClassName(slot.getAiClassName()); server.updateSlot(cloneSlot, LegacyAiPlayer.supportedExpansions()); } server.startGame(); Phase phase = game.getPhase(); // Cycle through (probably only once) to keep the game moving. while (phase != null && !phase.isEntered()) { // Modifying phases to proxyless versions if (phase.getClass().equals(CreateGamePhase.class)) phase = game.getPhases().get(ProxylessCreateGamePhase.class); if (phase.getClass().equals(DrawPhase.class)) phase = game.getPhases().get(ProxylessDrawPhase.class); phase.setEntered(true); phase.enter(); phase = game.getPhase(); if (game.getTurnPlayer().getNick().equals("RANDOM0")) firstPlayer = game.getTurnPlayer(); } int score = firstPlayer.getPoints(); scores[r] = score; System.out.println(score); } Mean m = new Mean(); StandardDeviation sd = new StandardDeviation(); System.out.println("Mean: " + m.evaluate(scores) + ", SD: " + sd.evaluate(scores)); }
From source file:edu.harvard.i2b2.patientMapping.serviceClient.PatientMappingQueryClient.java
public static void main(String[] args) throws Exception { PDORequestMessageModel pdoFactory = new PDORequestMessageModel(); String conceptPath = new String( "\\RPDR\\Labtests\\LAB\\(LLB16) Chemistry\\(LLB21) General Chemistries\\CA"); ArrayList<String> paths = new ArrayList<String>(); // paths.add(conceptPath); conceptPath = new String("\\RPDR\\Labtests\\LAB\\(LLB16) Chemistry\\(LLB21) General Chemistries\\GGT"); paths.add(conceptPath); // conceptPath = new // String("\\RPDR\\Labtests\\LAB\\(LLB16) Chemistry\\(LLB21) General Chemistries\\GGT"); // paths.add(conceptPath); ArrayList<String> ppaths = new ArrayList<String>(); conceptPath = new String("\\Providers\\BWH"); // ppaths.add(conceptPath); String xmlStr = pdoFactory.requestXmlMessage(null, "1545", new Integer(1), new Integer(20), false); String result = sendPDOQueryRequestREST(xmlStr); // FileWriter fwr = new FileWriter("c:\\testdir\\response.txt"); // fwr.write(result); log.debug(result);//w w w . java2 s . co m PDOItem set = new PDOItem(); set.fullPath = "\\RPDR\\Labtests\\LAB\\(LLB16) Chemistry\\(LLB21) General Chemistries\\CA"; set.hasValueDisplayProperty = true; PDOValueModel valdp = new PDOValueModel(); valdp.left = 0.0; valdp.right = 8.4; valdp.color = "red"; valdp.height = "Very Low"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 8.4; valdp.right = 8.9; valdp.color = "gold"; valdp.height = "Low"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 8.9; valdp.right = 10.0; valdp.color = "green"; valdp.height = "Medium"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 10.0; valdp.right = 10.6; valdp.color = "gold"; valdp.height = "Tall"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 10.6; valdp.right = Integer.MAX_VALUE; valdp.color = "red"; valdp.height = "Very Tall"; set.valDisplayProperties.add(valdp); set.tableType = "fact"; TimelineRow row = new TimelineRow(); row.pdoItems.add(set); row.displayName = "Calcium (Group:CA)"; ArrayList<TimelineRow> rows = new ArrayList<TimelineRow>(); rows.add(row); set = new PDOItem(); set.fullPath = "\\RPDR\\Labtests\\LAB\\(LLB16) Chemistry\\(LLB21) General Chemistries\\GGT"; set.hasValueDisplayProperty = true; valdp = new PDOValueModel(); valdp.left = 0.0; valdp.right = 1.0; valdp.color = "red"; valdp.height = "Very Low"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 1.0; valdp.right = 19.0; valdp.color = "gold"; valdp.height = "Low"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 19.0; valdp.right = 34.0; valdp.color = "green"; valdp.height = "Medium"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 34.0; valdp.right = 82.0; valdp.color = "gold"; valdp.height = "Tall"; set.valDisplayProperties.add(valdp); valdp = new PDOValueModel(); valdp.left = 82.0; valdp.right = Integer.MAX_VALUE; valdp.color = "red"; valdp.height = "Very Tall"; set.valDisplayProperties.add(valdp); set.tableType = "fact"; row = new TimelineRow(); row.pdoItems.add(set); row.displayName = "Gamma Glutamyltrans (Group:GGT)"; rows.add(row); // testWritelld(result, rows, true); testWriteTableFile(result); }
From source file:com.hp.test.framework.Reporting.Utlis.java
public static void main(String ar[]) throws IOException { ArrayList<String> runs_list = new ArrayList<String>(); String basepath = replacelogs(); String path = basepath + "ATU Reports\\Results"; File directory = new File(path); File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html"; for (File dir : subdirs) { runs_list.add(dir.getName()); }/*from ww w .j a v a 2s . c o m*/ String Reports_path = basepath + "ATU Reports\\"; int LatestRun = Utlis.getLastRun(Reports_path); String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path); UpdateTestCaseDesciption.basepath = Last_run_path; UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html"); UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html"); // GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun)); genarateFailureReport(new File(htmlReport), Reports_path + "Results\\"); Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path); int success = replaceCounts(runCounts, path); if (success == 0) { File SourceFile = new File(path + "\\lineChart_temp.js"); File RenameFile = new File(path + "\\lineChart.js"); renameOriginalFile(SourceFile, RenameFile); File SourceFile1 = new File(path + "\\barChart_temp.js"); File RenameFile1 = new File(path + "\\barChart.js"); renameOriginalFile(SourceFile1, RenameFile1); Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun)); try { Utlis.replaceMainTable(false, new File(Reports_path + "index.html")); Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html")); Utlis.replaceMainTable(true, new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); fileList.add( new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); for (File f : fileList) { Utlis.replaceMainTable(true, f); } } catch (Exception ex) { log.info("Error in updating Report format" + ex.getMessage()); } Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; // HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); // HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path); ArrayList<String> to_list = new ArrayList<String>(); ReportingProperties reportingproperties = new ReportingProperties(); String temp_eml = reportingproperties.getProperty("TOLIST"); String JenkinsURL = reportingproperties.getProperty("JENKINSURL"); String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory"); Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots")); Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots")); String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix"); if (cleanScreenshotsDir) { if (!CleanFilesinDir(ScreenShotsDir)) { log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir); } else { log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess"); } } List<String> scr_fileList; List<String> html_fileList; if (generatescreenshots) { scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); int len = scr_fileList.size(); len = len + 1; screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", ScreenShotsDir + "screenshot_" + len + ".png"); File source = new File(Reports_path + "Results\\HtmlReport.html"); File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html"); // Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING); FileUtils.copyFile(source, dest); scr_fileList.clear(); } scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); html_fileList = GetFileListinDir(ScreenShotsDir, "html"); if (temp_eml.length() > 1) { String[] to_list_temp = temp_eml.split(","); if (to_list_temp.length > 0) { for (String to_list_temp1 : to_list_temp) { to_list.add(to_list_temp1); } } if (to_list.size() > 0) { screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", Last_run_path + "screenshot.png"); // cleanTempDir.cleanandCreate(Reports_path, LatestRun); // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip"); if (generatescreenshots) { SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList); } else { SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html", Last_run_path + "screenshot.png"); } // FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip")); // FileUtils.deleteDirectory(new File(Reports_path + "temp")); } } } }