List of usage examples for java.lang StringBuilder StringBuilder
@HotSpotIntrinsicCandidate
public StringBuilder()
From source file:edu.cmu.sv.modelinference.runner.Main.java
public static void main(String[] args) { Options cmdOpts = createCmdOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;/* ww w . j a va2s .com*/ try { cmd = parser.parse(cmdOpts, args, true); } catch (ParseException exp) { logger.error(exp.getMessage()); System.err.println(exp.getMessage()); Util.printHelpAndExit(Main.class, cmdOpts); } String inputType = cmd.getOptionValue(INPUT_TYPE_ARG); String tool = cmd.getOptionValue(TOOL_TYPE_ARG); String logFile = cmd.getOptionValue(LOG_FILE_ARG).replaceFirst("^~", System.getProperty("user.home")); LogHandler<?> logHandler = null; boolean found = false; for (LogHandler<?> lh : logHandlers) { if (lh.getHandlerName().equals(tool)) { logHandler = lh; found = true; break; } } if (!found) { StringBuilder sb = new StringBuilder(); Iterator<LogHandler<?>> logIter = logHandlers.iterator(); while (logIter.hasNext()) { sb.append(logIter.next().getHandlerName()); if (logIter.hasNext()) sb.append(", "); } logger.error("Did not find tool for arg " + tool); System.err.println("Supported tools: " + Util.getSupportedHandlersString(logHandlers)); Util.printHelpAndExit(Main.class, cmdOpts); } logger.info("Using loghandler for logtype: " + logHandler.getHandlerName()); logHandler.process(logFile, inputType, cmd.getArgs()); }
From source file:facade.examples.Collections.java
/** * Run the examples/*from ww w . j a v a 2 s.c o m*/ * @param args <i>ignored</i> */ public static void main(String[] args) { /* RESISTORS IN PARALLEL WITH FACADE */ System.out.println("-> With facade: "); /* Empty collection of resistors */ Collection<Double> resistors = new ArrayList<Double>(); /* adding values. on() modifies the collection in place */ on(resistors).add(1.5, 3.0, 15.0, 30.0, 150.0); /* computing resistance. with() works on a collection copy. */ double r = 1.0 / with(resistors).map(inverse).reduce(sum); /* pretty printing the resistors */ System.out.println("[ " + with(resistors).join(", ") + " ]"); /* printing the equivalent resistor */ System.out.println(r); /* --------------------------------------------------------------- */ System.out.println(); /* --------------------------------------------------------------- */ /* RESISTORS IN PARALLEL WITH CLASSIC JAVA */ System.out.println("-> Without facade: "); /* Empty collection of resistors */ resistors = new ArrayList<Double>(); /* adding values */ resistors.add(1.5); resistors.add(3.0); resistors.add(15.0); resistors.add(30.0); resistors.add(150.0); /* computing resistance */ double sum = 0.0; for (Double resistor : resistors) { sum += 1.0 / resistor; } r = 1.0 / sum; /* pretty printing the resistors */ StringBuilder sb = new StringBuilder(); sb.append("[ "); Iterator<Double> it = resistors.iterator(); if (it.hasNext()) { sb.append(it.next()); } while (it.hasNext()) { sb.append(", ").append(it.next()); } sb.append(" ]"); System.out.println(sb.toString()); /* printing the equivalent resistor */ System.out.println(r); }
From source file:com.lsq.httpclient.netpay.BasicInfo.java
public static void main(String[] args) throws Exception { // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("F://test/pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA"); // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("F://??/rsa_public_key_2048.pem", "pem", "RSA"); ///*from w w w . j a va 2s . c o m*/ // final String url = "http://localhost:8080/interfaceWeb/basicInfo"; // final String url = "https://testapp.sicpay.com:11008/interfaceWeb/basicInfo"; //? // final String url = "http://120.31.132.120:8082/interfaceWeb/basicInfo"; // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:\\document\\key\\000158120120\\GHT_ROOT.pem", "pem", "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:\\document\\key\\000000153990021\\000000153990021.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/000000158120121/000000158120121.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/000000152110003.pem", "pem", null, "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/test_pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA"); // PublicKey yhPubKey = TestUtil.getPublicKey(); // PrivateKey hzfPriKey = TestUtil.getPrivateKey(); // final String url = "http://epay.gaohuitong.com:8083/interfaceWeb/basicInfo"; // final String url = "http://gpay.gaohuitong.com:8086/interfaceWeb2/basicInfo"; // final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:/document/key/549440155510001/GHT_ROOT.pem", "pem", "RSA"); // final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/549440155510001/549440155510001.pem", "pem", null, "RSA"); // final String url = "https://portal.sicpay.com:8087/interfaceWeb/basicInfo"; final String url = TestUtil.interface_url + "basicInfo"; final PublicKey yhPubKey = TestUtil.getPublicKey(); final PrivateKey hzfPriKey = TestUtil.getPrivateKey(); int i = 0; // int j = 0; while (i < 1) { i++; try { HttpClient4Util httpClient4Util = new HttpClient4Util(); StringBuilder sBuilder = new StringBuilder(); sBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sBuilder.append("<merchant>"); sBuilder.append("<head>"); sBuilder.append("<version>2.0.0</version>"); // sBuilder.append("<agencyId>549440155510001</agencyId>"); sBuilder.append("<agencyId>" + TestUtil.merchantId + "</agencyId>"); sBuilder.append("<msgType>01</msgType>"); sBuilder.append("<tranCode>100001</tranCode>"); sBuilder.append("<reqMsgId>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + i + i + "</reqMsgId>"); sBuilder.append("<reqDate>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "</reqDate>"); sBuilder.append("</head>"); sBuilder.append("<body>"); sBuilder.append("<handleType>0</handleType>"); sBuilder.append("<merchantName>LIBTEST1</merchantName>"); sBuilder.append("<shortName>UNCLE HENRY(A)</shortName>"); sBuilder.append("<city>344344</city>"); sBuilder.append( "<merchantAddress>UNIT C 15/FHUA CHIAO COMM CTR 678 NATHAN RD MONGKOK KL</merchantAddress>"); sBuilder.append("<servicePhone>13250538964</servicePhone>"); sBuilder.append("<orgCode></orgCode>"); sBuilder.append("<merchantType>01</merchantType>"); sBuilder.append("<category>5399</category>"); sBuilder.append("<corpmanName>?</corpmanName>"); sBuilder.append("<corpmanId>440103198112214218</corpmanId>"); sBuilder.append("<corpmanPhone>13926015921</corpmanPhone>"); sBuilder.append("<corpmanMobile>13926015921</corpmanMobile>"); sBuilder.append("<corpmanEmail>>zhanglibo@sicpay.com</corpmanEmail>"); sBuilder.append("<bankCode>105</bankCode>"); sBuilder.append("<bankName></bankName>"); sBuilder.append("<bankaccountNo>6250502002603958</bankaccountNo>"); sBuilder.append("<bankaccountName>?</bankaccountName>"); sBuilder.append("<autoCus>0</autoCus>"); sBuilder.append("<remark></remark>"); sBuilder.append("<licenseNo>91440184355798892G</licenseNo>"); // sBuilder.append("<taxRegisterNo></taxRegisterNo>"); // sBuilder.append("<subMerchantNo></subMerchantNo>"); // sBuilder.append("<inviteMerNo></inviteMerNo>"); // sBuilder.append("<county></county>"); // sBuilder.append("<appid>wx04df48e919ef7b28</appid>"); // sBuilder.append("<pid>2015062600009243</pid>"); // sBuilder.append("<childEnter>1</childEnter>"); // sBuilder.append("<ghtEnter>0</ghtEnter>"); // sBuilder.append("<addrType>BUSINESS_ADDRESS</addrType>"); // sBuilder.append("<contactType>LEGAL_PERSON</contactType>"); // sBuilder.append("<mcc>200101110640354</mcc>"); // sBuilder.append("<licenseType>NATIONAL_LEGAL_MERGE</licenseType>"); // sBuilder.append("<authPayDir>http://epay.gaohuitong.com/channel/|http://test.pengjv.com/channel/</authPayDir>"); // sBuilder.append("<scribeAppid>wx04df48e919ef7b28</scribeAppid>"); // sBuilder.append("<contactMan></contactMan>"); // sBuilder.append("<telNo>18675857506</telNo>"); // sBuilder.append("<mobilePhone>18675857506</mobilePhone>"); // sBuilder.append("<email>CSC@sicpay.com</email>"); // sBuilder.append("<licenseBeginDate>20150826</licenseBeginDate>"); // sBuilder.append("<licenseEndDate>20991231</licenseEndDate>"); // sBuilder.append("<licenseRange>?????????????</licenseRange>"); sBuilder.append("</body>"); sBuilder.append("</merchant>"); String plainXML = sBuilder.toString(); byte[] plainBytes = plainXML.getBytes("UTF-8"); String keyStr = "4D22R4846VFJ8HH4"; byte[] keyBytes = keyStr.getBytes("UTF-8"); byte[] base64EncryptDataBytes = Base64.encodeBase64( CryptoUtil.AESEncrypt(plainBytes, keyBytes, "AES", "AES/ECB/PKCS5Padding", null)); String encryptData = new String(base64EncryptDataBytes, "UTF-8"); byte[] base64SingDataBytes = Base64 .encodeBase64(CryptoUtil.digitalSign(plainBytes, hzfPriKey, "SHA1WithRSA")); String signData = new String(base64SingDataBytes, "UTF-8"); byte[] base64EncyrptKeyBytes = Base64 .encodeBase64(CryptoUtil.RSAEncrypt(keyBytes, yhPubKey, 2048, 11, "RSA/ECB/PKCS1Padding")); String encrtptKey = new String(base64EncyrptKeyBytes, "UTF-8"); List<NameValuePair> nvps = new LinkedList<NameValuePair>(); nvps.add(new BasicNameValuePair("encryptData", encryptData)); nvps.add(new BasicNameValuePair("encryptKey", encrtptKey)); // nvps.add(new BasicNameValuePair("agencyId", "549440155510001")); nvps.add(new BasicNameValuePair("agencyId", TestUtil.merchantId)); nvps.add(new BasicNameValuePair("signData", signData)); nvps.add(new BasicNameValuePair("tranCode", "100001")); // nvps.add(new BasicNameValuePair("callBack","http://localhost:801/callback/ghtBindCard.do")); // byte[] retBytes = httpClient4Util.doPost("http://localhost:8080/quickInter/channel/commonSyncInter.do", null, nvps, null); byte[] retBytes = httpClient4Util.doPost(url, null, nvps, null); // byte[] retBytes =httpClient4Util.doPost("http://epay.gaohuitong.com:8082/quickInter/channel/commonSyncInter.do", null, nvps, null); // byte[] retBytes = httpClient4Util.doPost("http://192.168.80.113:8080/quickInter/channel/commonSyncInter.do", null, nvps, null); String response = new String(retBytes, "UTF-8"); System.out.println(" ||" + new String(retBytes, "UTF-8") + "||"); TestEncype t = new TestEncype(); System.out.println(": ||" + t.respDecryption(response) + "||"); System.out.println("i" + i); } catch (Exception e) { e.printStackTrace(); } } }
From source file:appmain.AppMain.java
public static void main(String[] args) { try {/*from w w w . j a v a 2 s . c o m*/ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); UIManager.put("OptionPane.yesButtonText", "Igen"); UIManager.put("OptionPane.noButtonText", "Nem"); } catch (Exception ex) { ex.printStackTrace(); } try { AppMain app = new AppMain(); app.init(); File importFolder = new File(DEFAULT_IMPORT_FOLDER); if (!importFolder.isDirectory() || !importFolder.exists()) { JOptionPane.showMessageDialog(null, "Az IMPORT mappa nem elrhet!\n" + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: " + importFolder.getAbsolutePath(), "Informci", JOptionPane.INFORMATION_MESSAGE); return; } File exportFolder = new File(DEFAULT_EXPORT_FOLDER); if (!exportFolder.isDirectory() || !exportFolder.exists()) { JOptionPane.showMessageDialog(null, "Az EXPORT mappa nem elrhet!\n" + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: " + exportFolder.getAbsolutePath(), "Informci", JOptionPane.INFORMATION_MESSAGE); return; } List<File> xmlFiles = app.getXMLFiles(importFolder); if (xmlFiles == null || xmlFiles.isEmpty()) { JOptionPane.showMessageDialog(null, "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(), "Informci", JOptionPane.INFORMATION_MESSAGE); return; } StringBuilder fileList = new StringBuilder(); xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName())); int ret = JOptionPane.showConfirmDialog(null, "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?", "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (ret == JOptionPane.OK_OPTION) { String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis() + ".csv"; File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName); app.writeCSV(csv, Arrays.asList(app.getHeaderLine())); xmlFiles.stream().forEach(xml -> { List<String> lines = app.readXMLData(xml); if (lines != null) app.writeCSV(csv, lines); }); if (csv.isFile() && csv.exists()) { JOptionPane.showMessageDialog(null, "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(), "Informci", JOptionPane.INFORMATION_MESSAGE); app.openFile(csv); } } else { JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci", JOptionPane.INFORMATION_MESSAGE); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba", JOptionPane.ERROR_MESSAGE); } }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
public static void main(String[] args) { // check & validate cmdline options OptionGroup opt_g = getCMDLineOptionsGroups(); Options opt = getCMDLineOptions();//w ww .j a v a 2s. c om opt.addOptionGroup(opt_g); CommandLineParser cli = new DefaultParser(); try { CommandLine cl = cli.parse(opt, args); if (cl.hasOption("v")) { VerboseOutputFilter.SHOW_VERBOSE = true; } switch (opt_g.getSelected()) { case "V": try { URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation(); String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8"); JarFile jarFile = new JarFile(jarPath); Manifest m = jarFile.getManifest(); StringBuilder versionInfo = new StringBuilder(); for (Object key : m.getMainAttributes().keySet()) { versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString())) .append("\n"); } System.out.println(versionInfo.toString()); } catch (Exception e) { log.error("Version info could not be read."); } break; case "h": HelpFormatter help = new HelpFormatter(); String header = ""; //TODO: missing infotext StringBuilder footer = new StringBuilder("Supported configuration properties :"); help.printHelp("CodeGen -h | -V | -g [...]", header, opt, footer.toString()); break; case "g": // target dir if (cl.hasOption("t")) { File target = new File(cl.getOptionValue("t")); if (target.isDirectory() && target.canExecute() && target.canWrite()) { config.setProperty("target.dir", cl.getOptionValue("t")); } else { log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t")); break; } } else { config.setProperty("target.dir", System.getProperty("java.io.tmpdir")); } // project dir if (cl.hasOption("p")) { File project = new File(cl.getOptionValue("p")); if (!project.exists()) { if (!project.mkdirs()) { log.error("Project dir '{}' can't be created!", cl.getOptionValue("p")); break; } } if (project.isDirectory() && project.canExecute() && project.canWrite()) { config.setProperty("project.dir", cl.getOptionValue("p")); } else { log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p")); break; } } generateAppfromXML(cl.getOptionValue("g")); break; } } catch (ParseException e) { log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage()); } }
From source file:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java
/** * Main entry point - for use outside the interactive shell. * @param args//from w ww. j av a 2s. co m * @throws Exception */ public static void main(String[] args) throws Exception { String brmsPackageName = "SRAMPPackage"; //$NON-NLS-1$ String tag = "LATEST"; //$NON-NLS-1$ String brmsBaseUrl = "http://localhost:8080/drools-guvnor"; //$NON-NLS-1$ String brmsUserId = "admin"; //$NON-NLS-1$ String brmsPassword = "admin"; //$NON-NLS-1$ if (args.length > 0) brmsPackageName = args[0]; if (args.length > 1) tag = args[1]; if (args.length > 2) brmsBaseUrl = args[2]; if (args.length > 3) brmsUserId = args[3]; if (args.length > 4) brmsPassword = args[4]; StringBuilder argLine = new StringBuilder(); argLine.append(brmsPackageName).append(" ").append(tag) //$NON-NLS-1$ .append(" ").append(brmsBaseUrl) //$NON-NLS-1$ .append(" ").append(brmsUserId) //$NON-NLS-1$ .append(" ").append(brmsPassword); //$NON-NLS-1$ SrampAtomApiClient client = new SrampAtomApiClient("http://localhost:8080/s-ramp-server"); //$NON-NLS-1$ QName clientVarName = new QName("s-ramp", "client"); //$NON-NLS-1$ //$NON-NLS-2$ Pkg2SrampCommand cmd = new Pkg2SrampCommand(); ShellContext context = new SimpleShellContext(); context.setVariable(clientVarName, client); cmd.setArguments(new Arguments(argLine.toString())); cmd.setContext(context); cmd.execute(); }
From source file:hyperheuristics.main.comparisons.ComputeIndicators.java
public static void main(String[] args) throws IOException, InterruptedException { int[] numberOfObjectivesArray = new int[] { 2, 4 }; String[] problems = new String[] { "OO_MyBatis", "OA_AJHsqldb", "OA_AJHotDraw", "OO_BCEL", "OO_JHotDraw", "OA_HealthWatcher", // "OA_TollSystems", "OO_JBoss" }; String[] heuristicFunctions = new String[] { LowLevelHeuristic.CHOICE_FUNCTION, LowLevelHeuristic.MULTI_ARMED_BANDIT, LowLevelHeuristic.RANDOM }; String[] algorithms = new String[] { "NSGA-II", // "SPEA2" };/*from www . java 2s . co m*/ MetricsUtil metricsUtil = new MetricsUtil(); DecimalFormat decimalFormatter = new DecimalFormat("0.00E0"); Mean mean = new Mean(); StandardDeviation standardDeviation = new StandardDeviation(); InvertedGenerationalDistance igd = new InvertedGenerationalDistance(); GenerationalDistance gd = new GenerationalDistance(); Spread spread = new Spread(); Coverage coverage = new Coverage(); for (int objectives : numberOfObjectivesArray) { try (FileWriter IGDWriter = new FileWriter("experiment/IGD_" + objectives + ".tex"); FileWriter spreadWriter = new FileWriter("experiment/SPREAD_" + objectives + ".tex"); FileWriter GDWriter = new FileWriter("experiment/GD_" + objectives + ".tex"); FileWriter coverageWriter = new FileWriter("experiment/COVERAGE_" + objectives + ".tex")) { StringBuilder latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\\documentclass{paper}\n").append("\n") .append("\\usepackage[T1]{fontenc}\n").append("\\usepackage[latin1]{inputenc}\n") .append("\\usepackage[hidelinks]{hyperref}\n").append("\\usepackage{tabulary}\n") .append("\\usepackage{booktabs}\n").append("\\usepackage{multirow}\n") .append("\\usepackage{amsmath}\n").append("\\usepackage{mathtools}\n") .append("\\usepackage{graphicx}\n").append("\\usepackage{array}\n") .append("\\usepackage[linesnumbered,ruled,inoutnumbered]{algorithm2e}\n") .append("\\usepackage{subfigure}\n").append("\\usepackage[hypcap]{caption}\n") .append("\\usepackage{pdflscape}\n").append("\n").append("\\begin{document}\n").append("\n") .append("\\begin{landscape}\n").append("\n"); pfKnown: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR found for $PF_{known}$ for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, Double> igdMap = new HashMap<>(); HashMap<String, Double> gdMap = new HashMap<>(); HashMap<String, Double> spreadMap = new HashMap<>(); HashMap<String, Double> coverageMap = new HashMap<>(); for (String algorithm : algorithms) { double[][] mecbaFront = metricsUtil .readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); igdMap.put(algorithm, igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives)); gdMap.put(algorithm, gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm, spread.spread(mecbaFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm, coverage.coverage(mecbaFront, trueFrontMatrix)); for (String heuristic : heuristicFunctions) { double[][] heuristicFront = metricsUtil.readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/FUN.txt"); igdMap.put(algorithm + "-" + heuristic, igd .invertedGenerationalDistance(heuristicFront, trueFrontMatrix, objectives)); gdMap.put(algorithm + "-" + heuristic, gd.generationalDistance(heuristicFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm + "-" + heuristic, spread.spread(heuristicFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm + "-" + heuristic, coverage.coverage(heuristicFront, trueFrontMatrix)); } } latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTableBuilder = new StringBuilder(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicIGD = igdMap.get(heuristic); double heuristicGD = gdMap.get(heuristic); double heuristicSpread = spreadMap.get(heuristic); double heuristicCoverage = coverageMap.get(heuristic); if (heuristicIGD < bestMeanIGD) { bestMeanIGD = heuristicIGD; bestHeuristicIGD = heuristic; } if (heuristicGD < bestMeanGD) { bestMeanGD = heuristicGD; bestHeuristicGD = heuristic; } if (heuristicSpread > bestMeanSpread) { bestMeanSpread = heuristicSpread; bestHeuristicSpread = heuristic; } if (heuristicCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || igdMap.get(heuristic).equals(igdMap.get(bestHeuristicIGD)); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(igdMap.get(heuristic))); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || gdMap.get(heuristic).equals(gdMap.get(bestHeuristicGD)); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(gdMap.get(heuristic))); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || spreadMap.get(heuristic).equals(spreadMap.get(bestHeuristicSpread)); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(spreadMap.get(heuristic))); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || coverageMap.get(heuristic).equals(coverageMap.get(bestHeuristicCoverage)); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder.append(decimalFormatter.format(coverageMap.get(heuristic))); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } averages: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR averages found for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, double[]> igdMap = new HashMap<>(); HashMap<String, double[]> gdMap = new HashMap<>(); HashMap<String, double[]> spreadMap = new HashMap<>(); HashMap<String, double[]> coverageMap = new HashMap<>(); mocaito: { for (String algorithm : algorithms) { double[] mecbaIGDs = new double[EXECUTIONS]; double[] mecbaGDs = new double[EXECUTIONS]; double[] mecbaSpreads = new double[EXECUTIONS]; double[] mecbaCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] mecbaFront = metricsUtil.readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem + "-" + i + ".NaoDominadas"); mecbaIGDs[i] = igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaGDs[i] = gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaSpreads[i] = spread.spread(mecbaFront, trueFrontMatrix, objectives); mecbaCoverages[i] = coverage.coverage(mecbaFront, trueFrontMatrix); } igdMap.put(algorithm, mecbaIGDs); gdMap.put(algorithm, mecbaGDs); spreadMap.put(algorithm, mecbaSpreads); coverageMap.put(algorithm, mecbaCoverages); } } for (String algorithm : algorithms) { for (String heuristic : heuristicFunctions) { double[] hhIGDs = new double[EXECUTIONS]; double[] hhGDs = new double[EXECUTIONS]; double[] hhSpreads = new double[EXECUTIONS]; double[] hhCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] hhFront = metricsUtil .readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/EXECUTION_" + i + "/FUN.txt"); hhIGDs[i] = igd.invertedGenerationalDistance(hhFront, trueFrontMatrix, objectives); hhGDs[i] = gd.generationalDistance(hhFront, trueFrontMatrix, objectives); hhSpreads[i] = spread.spread(hhFront, trueFrontMatrix, objectives); hhCoverages[i] = coverage.coverage(hhFront, trueFrontMatrix); } igdMap.put(algorithm + "-" + heuristic, hhIGDs); gdMap.put(algorithm + "-" + heuristic, hhGDs); spreadMap.put(algorithm + "-" + heuristic, hhSpreads); coverageMap.put(algorithm + "-" + heuristic, hhCoverages); } } HashMap<String, HashMap<String, Boolean>> igdResult = KruskalWallisTest.test(igdMap); HashMap<String, HashMap<String, Boolean>> gdResult = KruskalWallisTest.test(gdMap); HashMap<String, HashMap<String, Boolean>> spreadResult = KruskalWallisTest.test(spreadMap); HashMap<String, HashMap<String, Boolean>> coverageResult = KruskalWallisTest .test(coverageMap); latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); latexTableBuilder = new StringBuilder(); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicMeanIGD = mean.evaluate(igdMap.get(heuristic)); double heuristicMeanGD = mean.evaluate(gdMap.get(heuristic)); double heuristicMeanSpread = mean.evaluate(spreadMap.get(heuristic)); double heuristicMeanCoverage = mean.evaluate(coverageMap.get(heuristic)); if (heuristicMeanIGD < bestMeanIGD) { bestMeanIGD = heuristicMeanIGD; bestHeuristicIGD = heuristic; } if (heuristicMeanGD < bestMeanGD) { bestMeanGD = heuristicMeanGD; bestHeuristicGD = heuristic; } if (heuristicMeanSpread > bestMeanSpread) { bestMeanSpread = heuristicMeanSpread; bestHeuristicSpread = heuristic; } if (heuristicMeanCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicMeanCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || !igdResult.get(heuristic).get(bestHeuristicIGD); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(mean.evaluate(igdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(igdMap.get(heuristic))) + ")"); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || !gdResult.get(heuristic).get(bestHeuristicGD); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(mean.evaluate(gdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(gdMap.get(heuristic))) + ")"); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || !spreadResult.get(heuristic).get(bestHeuristicSpread); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(mean.evaluate(spreadMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(spreadMap.get(heuristic))) + ")"); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || !coverageResult.get(heuristic).get(bestHeuristicCoverage); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder .append(decimalFormatter.format(mean.evaluate(coverageMap.get(heuristic)))) .append(" (") .append(decimalFormatter .format(standardDeviation.evaluate(coverageMap.get(heuristic)))) .append(")"); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } latexTableBuilder.append("\\end{landscape}\n\n").append("\\end{document}"); String latexTable = latexTableBuilder.toString(); IGDWriter.write(latexTable); spreadWriter.write(latexTable); GDWriter.write(latexTable); coverageWriter.write(latexTable); } } }
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 www. ja va 2 s. co m BufferedWriter outBuff = null; try { File inFile = new File(args[0]); File fastaFile = new File(args[1]); File outFile = new File(args[2]); File blastFile = new File(args[3]); //Primero cargo todos los datos del archivo xml del blast BufferedReader buffReader = new BufferedReader(new FileReader(blastFile)); StringBuilder stBuilder = new StringBuilder(); String line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); System.out.println("Creating blastoutput..."); BlastOutput blastOutput = new BlastOutput(stBuilder.toString()); System.out.println("BlastOutput created! :)"); stBuilder.delete(0, stBuilder.length()); HashMap<String, String> blastProteinsMap = new HashMap<String, String>(); ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations(); for (Iteration iteration : iterations) { blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString()); } //freeing some memory blastOutput = null; //------------------------------------------------------------------------ //Initializing writer for output file outBuff = new BufferedWriter(new FileWriter(outFile)); //reading gene annotation xml file..... buffReader = new BufferedReader(new FileReader(inFile)); stBuilder = new StringBuilder(); line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); XMLElement genesXML = new XMLElement(stBuilder.toString()); //freeing some memory I don't need anymore stBuilder.delete(0, stBuilder.length()); //reading file with the reference proteins set ArrayList<String> proteinsReferenceSet = new ArrayList<String>(); buffReader = new BufferedReader(new FileReader(fastaFile)); while ((line = buffReader.readLine()) != null) { if (line.charAt(0) == '>') { proteinsReferenceSet.add(line.split("\\|")[1]); } } buffReader.close(); Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME); List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME); System.out.println("There are " + contigs.size() + " contigs to be checked... "); outBuff.write("There are " + contigs.size() + " contigs to be checked... \n"); outBuff.write("Proteins reference set: \n"); for (String st : proteinsReferenceSet) { outBuff.write(st + ","); } outBuff.write("\n"); for (Element elem : contigs) { ContigXML contig = new ContigXML(elem); //escribo el id del contig en el que estoy outBuff.write("Checking contig: " + contig.getId() + "\n"); outBuff.flush(); List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME); System.out.println("geneList.size() = " + geneList.size()); int numeroDeGenesParaAnalizar = geneList.size() / FACTOR; if (numeroDeGenesParaAnalizar == 0) { numeroDeGenesParaAnalizar++; } ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>(); outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: " + numeroDeGenesParaAnalizar + "\n"); for (int j = 0; j < numeroDeGenesParaAnalizar; j++) { int geneIndex; boolean geneIsDismissed = false; do { geneIsDismissed = false; geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size())); PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) { geneIsDismissed = true; } } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed); indicesUtilizados.add(geneIndex); System.out.println("geneIndex = " + geneIndex); //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: " + gene.getAnnotationUniprotId() + "\n"); outBuff.write("eValue: " + gene.getEvalue() + "\n"); //--------------PETICION POST HTTP BLAST---------------------- PostMethod post = new PostMethod(BLAST_URL); post.addParameter("program", "blastx"); post.addParameter("sequence", gene.getSequence()); post.addParameter("database", "uniprotkb"); post.addParameter("email", "ppareja@era7.com"); post.addParameter("exp", "1e-10"); post.addParameter("stype", "dna"); // execute the POST HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("status post = " + status); InputStream inStream = post.getResponseBodyAsStream(); String fileName = "jobid.txt"; FileOutputStream outStream = new FileOutputStream(new File(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); String jobId = buffReader.readLine(); buffReader.close(); System.out.println("jobId = " + jobId); //--------------HTTP CHECK JOB STATUS REQUEST---------------------- GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId); String jobStatus = ""; do { try { Thread.sleep(1000);//sleep for 1000 ms } catch (InterruptedException ie) { //If this thread was intrrupted by nother thread } status = client.executeMethod(get); //System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobStatus.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); jobStatus = buffReader.readLine(); //System.out.println("jobStatus = " + jobStatus); buffReader.close(); } while (!jobStatus.equals(FINISHED_JOB_STATUS)); //Once I'm here the blast should've already finished //--------------JOB RESULTS HTTP REQUEST---------------------- get = new GetMethod(JOB_RESULT_URL + jobId + "/out"); status = client.executeMethod(get); System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobResults.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //--------parsing the blast results file----- TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>(); buffReader = new BufferedReader(new FileReader(new File(fileName))); while ((line = buffReader.readLine()) != null) { if (line.length() > 3) { String prefix = line.substring(0, 3); if (prefix.equals("TR:") || prefix.equals("SP:")) { String[] columns = line.split(" "); String id = columns[1]; //System.out.println("id = " + id); String e = ""; String[] arraySt = line.split("\\.\\.\\."); if (arraySt.length > 1) { arraySt = arraySt[1].trim().split(" "); int contador = 0; for (int k = 0; k < arraySt.length && contador <= 2; k++) { String string = arraySt[k]; if (!string.equals("")) { contador++; if (contador == 2) { e = string; } } } } else { //Number before e- String[] arr = arraySt[0].split("e-")[0].split(" "); String numeroAntesE = arr[arr.length - 1]; String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0]; e = numeroAntesE + "e-" + numeroDespuesE; } double eValue = Double.parseDouble(e); //System.out.println("eValue = " + eValue); GeneEValuePair g = new GeneEValuePair(id, eValue); featuresBlast.add(g); } } } GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(), gene.getEvalue()); System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id); System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue); boolean blastContainsGene = false; for (GeneEValuePair geneEValuePair : featuresBlast) { if (geneEValuePair.id.equals(currentGeneEValuePair.id)) { blastContainsGene = true; //le pongo la e que tiene en el wu-blast para poder comparar currentGeneEValuePair.eValue = geneEValuePair.eValue; break; } } if (blastContainsGene) { outBuff.write("The protein was found in the WU-BLAST result.. \n"); //Una vez que se que esta en el blast tengo que ver que sea la mejor GeneEValuePair first = featuresBlast.first(); outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id + " , " + first.eValue + "\n"); if (first.id.equals(currentGeneEValuePair.id)) { outBuff.write("Proteins with best eValue match up \n"); } else { if (first.eValue == currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has the same eValue \n"); } else if (first.eValue > currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has a worse eValue :) \n"); } else { outBuff.write( "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n"); //System.exit(-1); if (proteinsReferenceSet.contains(first.id)) { //The protein is in the reference set and that shouldn't happen outBuff.write( "The protein was found on the reference set, checking if it belongs to the same contig...\n"); String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId()); if (iterationSt != null) { outBuff.write( "The protein was found in the BLAST used at the beginning of the annotation process.\n"); Iteration iteration = new Iteration(iterationSt); ArrayList<Hit> hits = iteration.getIterationHits(); boolean contigFound = false; Hit errorHit = null; for (Hit hit : hits) { if (hit.getHitDef().indexOf(contig.getId()) >= 0) { contigFound = true; errorHit = hit; break; } } if (contigFound) { outBuff.write( "ERROR: A hit from the same contig was find in the Blast file: \n" + errorHit.toString() + "\n"); } else { outBuff.write("There is no hit with the same contig! :)\n"); } } else { outBuff.write( "The protein is NOT in the BLAST used at the beginning of the annotation process.\n"); } } else { //The protein was not found on the reference set so everything's ok outBuff.write( "The protein was not found on the reference, everything's ok :)\n"); } } } } else { outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n"); //System.exit(-1); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { //closing outputfile outBuff.close(); } catch (IOException ex) { Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:com.serotonin.m2m2.Main.java
/** * * @param args/*www . ja v a2s . c om*/ * @throws Exception */ public static void main(String[] args) throws Exception { Providers.add(ICoreLicense.class, new CoreLicenseDefinition()); Common.MA_HOME = System.getProperty("ma.home"); Common.M2M2_HOME = Common.MA_HOME; new File(Common.MA_HOME, "RESTART").delete(); Common.envProps = new ReloadingProperties("env"); openZipFiles(); ClassLoader moduleClassLoader = loadModules(); Lifecycle lifecycle = new Lifecycle(); Providers.add(ILifecycle.class, lifecycle); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { ((ILifecycle) Providers.get(ILifecycle.class)).terminate(); } }); try { lifecycle.initialize(moduleClassLoader); if ((!GraphicsEnvironment.isHeadless()) && (Desktop.isDesktopSupported()) && (Common.envProps.getBoolean("web.openBrowserOnStartup"))) { Desktop.getDesktop().browse(new URI(new StringBuilder().append("http://localhost:") .append(Common.envProps.getInt("web.port", 8088)).toString())); } } catch (Exception e) { LOG.error("Error during initialization", e); lifecycle.terminate(); } }
From source file:dhtaccess.benchmark.LatencyMeasure.java
public static void main(String[] args) { boolean details = false; int repeats = DEFAULT_REPEATS; boolean doPut = true; // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("d", "details", false, "requests secret hash and TTL"); options.addOption("r", "repeats", true, "number of requests"); options.addOption("n", "no-put", false, "does not put"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/* ww w.java2s. com*/ try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } if (cmd.hasOption('d')) { details = true; } optVal = cmd.getOptionValue('r'); if (optVal != null) { repeats = Integer.parseInt(optVal); } if (cmd.hasOption('n')) { doPut = false; } args = cmd.getArgs(); // parse arguments if (args.length < 1) { usage(COMMAND); System.exit(1); } // prepare for RPC int numAccessor = args.length; DHTAccessor[] accessorArray = new DHTAccessor[numAccessor]; try { for (int i = 0; i < numAccessor; i++) { accessorArray[i] = new DHTAccessor(args[i]); } } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // generate key prefix Random rnd = new Random(System.currentTimeMillis()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < KEY_PREFIX_LENGTH; i++) { sb.append((char) ('a' + rnd.nextInt(26))); } String keyPrefix = sb.toString(); String valuePrefix = VALUE_PREFIX; // benchmarking System.out.println("Repeats " + repeats + " times."); if (doPut) { System.out.println("Putting: " + keyPrefix + "<number>"); for (int i = 0; i < repeats; i++) { byte[] key = null, value = null; try { key = (keyPrefix + i).getBytes(ENCODE); value = (valuePrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; acc.put(key, value, TTL); } } System.out.println("Benchmarking by getting."); int count = 0; long startTime = System.currentTimeMillis(); if (details) { for (int i = 0; i < repeats; i++) { byte[] key = null; try { key = (keyPrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; Set<DetailedGetResult> valueSet = acc.getDetails(key); if (valueSet != null && !valueSet.isEmpty()) { count++; } } } else { for (int i = 0; i < repeats; i++) { byte[] key = null; try { key = (keyPrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; Set<byte[]> valueSet = acc.get(key); if (valueSet != null && !valueSet.isEmpty()) { count++; } } } System.out.println(System.currentTimeMillis() - startTime + " msec."); System.out.println("Rate of successful gets: " + count + " / " + repeats); }