List of usage examples for java.util HashMap HashMap
public HashMap()
From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();/*w w w. j a v a 2s . co m*/ // Register logging options CmdlineOptions options = new CmdlineOptions("RDBMSIndexTool", argv); CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length != 1) { usage(); System.exit(3); } // load database schema project ClassLoader cloader = RDBMSIndexTool.class.getClassLoader(); InputStream istream = cloader.getResourceAsStream("net/ontopia/topicmaps/impl/rdbms/config/schema.xml"); Project dbp = DatabaseProjectReader.loadProject(istream); // open database connection String propfile = args[0]; ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(new File(propfile)), true); Connection conn = cf.requestConnection(); try { DatabaseMetaData dbm = conn.getMetaData(); boolean downcase = dbm.storesLowerCaseIdentifiers(); Map extra_indexes = new TreeMap(); Map missing_indexes = new TreeMap(); Iterator tables = dbp.getTables().iterator(); while (tables.hasNext()) { Table table = (Table) tables.next(); String table_name = (downcase ? table.getName().toLowerCase() : table.getName()); //! System.out.println("T :" + table_name); // get primary keys from database Map pkeys = getPrimaryKeys(table_name, dbm); // get indexes from database Map indexes = getIndexes(table_name, dbm); Map dindexes = new HashMap(); if (table.getPrimaryKeys() != null) { String pkey = table_name + '(' + StringUtils.join(table.getPrimaryKeys(), ',') + ')'; if (!pkeys.containsKey(pkey)) System.out.println("PKM: " + pkey); } Iterator iter = table.getIndexes().iterator(); while (iter.hasNext()) { Index index = (Index) iter.next(); String i = table_name + '(' + StringUtils.join(index.getColumns(), ',') + ')'; String index_name = (downcase ? index.getName().toLowerCase() : index.getName()); dindexes.put(i, index_name); } Set extra = new HashSet(indexes.keySet()); extra.removeAll(dindexes.keySet()); extra.removeAll(pkeys.keySet()); if (!extra.isEmpty()) { Iterator i = extra.iterator(); while (i.hasNext()) { Object k = i.next(); extra_indexes.put(k, indexes.get(k)); } } Set missing = new HashSet(dindexes.keySet()); missing.addAll(pkeys.keySet()); missing.removeAll(indexes.keySet()); if (!missing.isEmpty()) { Iterator i = missing.iterator(); while (i.hasNext()) { Object k = i.next(); missing_indexes.put(k, dindexes.get(k)); } } } if (!extra_indexes.isEmpty()) System.out.println("/* --- Extra indexes ----------------------------------------- */"); Iterator eiter = extra_indexes.keySet().iterator(); while (eiter.hasNext()) { Object k = eiter.next(); System.out.println("drop index " + extra_indexes.get(k) + "; /* " + k + " */"); } if (!missing_indexes.isEmpty()) System.out.println("/* --- Missing indexes---------------------------------------- */"); Iterator miter = missing_indexes.keySet().iterator(); while (miter.hasNext()) { Object k = miter.next(); System.out.println("create index " + missing_indexes.get(k) + " on " + k + ";"); } } finally { conn.rollback(); conn.close(); } }
From source file:it.polimi.tower4clouds.rdf_history_db.Main.java
public static void main(String[] args) { // args = "-fakemessages 10 -waitfakemessages 1000".split(" "); PropertiesConfiguration releaseProperties = null; try {// ww w. j a v a 2 s . c om releaseProperties = new PropertiesConfiguration("release.properties"); } catch (ConfigurationException e) { logger.error("Internal error", e); System.exit(1); } APP_NAME = releaseProperties.getString("application.name"); APP_FILE_NAME = releaseProperties.getString("dist.file.name"); APP_VERSION = releaseProperties.getString("release.version"); Main m = new Main(); JCommander jc = new JCommander(m, args); if (m.help) { jc.setProgramName(APP_FILE_NAME); jc.usage(); System.exit(0); } logger.info("{} {}", APP_NAME, APP_VERSION); HashMap<String, String> paramsMap = new HashMap<String, String>(); for (ParameterDescription param : jc.getParameters()) if (param.isAssigned()) { String name = param.getLongestName().replaceAll("-", ""); String value = null; try { value = Main.class.getField(name).get(m).toString(); } catch (Exception e) { } paramsMap.put(name, value); } perform(paramsMap); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaCreator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file"); inputOpt.setArgs(1);/*from ww w. j a va 2 s. c o m*/ inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output directory"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); URI targetUri = URI.createURI("morsa://" + commandLine.getOptionValue(OUT)); Class<?> inClazz = MorsaCreator.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa", new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory())); Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); Resource targetResource = resourceSet.createResource(targetUri); Map<String, Object> saveOpts = new HashMap<String, Object>(); //URI of the MongoDB database (e.g. localhost) saveOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost"); saveOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000); saveOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false); targetResource.save(saveOpts); LOG.log(Level.INFO, "Start moving elements"); targetResource.getContents().clear(); targetResource.getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Start saving"); targetResource.save(saveOpts); LOG.log(Level.INFO, "Saved"); targetResource.unload(); } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:com.fiveclouds.jasper.JasperRunner.java
public static void main(String[] args) { // Set-up the options for the utility Options options = new Options(); Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)"); options.addOption(report);//from w w w . j av a 2 s . c o m Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)"); driver.setRequired(true); options.addOption(driver); options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)"); options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel"); options.addOption("username", true, "database username"); options.addOption("password", true, "database password"); options.addOption("output", true, "the output filename (i.e. path/to/report.pdf"); options.addOption("help", false, "print this message"); Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("use value as report property").create("D"); options.addOption(propertyOption); // Parse the options and build the report CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jasper-runner", options); } else { System.out.println("Building report " + cmd.getOptionValue("report")); try { Class.forName(cmd.getOptionValue("driver")); Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"), cmd.getOptionValue("username"), cmd.getOptionValue("password")); System.out.println("Connected to " + cmd.getOptionValue("jdbcurl")); JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report")); JRPdfExporter pdfExporter = new JRPdfExporter(); Properties properties = cmd.getOptionProperties("D"); Map<String, Object> parameters = new HashMap<String, Object>(); Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>(); for (JRParameter param : jasperReport.getParameters()) { reportParameters.put(param.getName(), param); } for (Object propertyKey : properties.keySet()) { String parameterName = String.valueOf(propertyKey); String parameterValue = String.valueOf(properties.get(propertyKey)); JRParameter reportParam = reportParameters.get(parameterName); if (reportParam != null) { if (reportParam.getValueClass().equals(String.class)) { System.out.println( "Property " + parameterName + " set to String = " + parameterValue); parameters.put(parameterName, parameterValue); } else if (reportParam.getValueClass().equals(Integer.class)) { System.out.println( "Property " + parameterName + " set to Integer = " + parameterValue); parameters.put(parameterName, Integer.parseInt(parameterValue)); } else { System.err.print("Unsupported type for property " + parameterName); System.exit(1); } } else { System.out.println("Property " + parameterName + " not found in the report! IGNORING"); } } JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection); pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print); pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output")); System.out.println("Exporting report to " + cmd.getOptionValue("output")); pdfExporter.exportReport(); } catch (JRException e) { System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")"); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { System.err.print("Unable to find the database driver, is it on the classpath?"); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.print("An SQL exception has occurred (" + e.getMessage() + ")"); e.printStackTrace(); System.exit(1); } } } catch (ParseException e) { System.err.print("Unable to parse command line options (" + e.getMessage() + ")"); System.exit(1); } }
From source file:iac.cnr.it.TestSearcher.java
public static void main(String[] args) throws IOException, ParseException { /** Command line parser and options */ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OPT_INDEX, true, "Index path"); options.addOption(OPT_QUERY, true, "The query"); CommandLine cmd = null;/*from www. ja va2 s.c o m*/ try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { logger.fatal("Error while parsing command line arguments"); System.exit(1); } /** Check for mandatory options */ if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) { usage(); System.exit(0); } /** Read options */ File casePath = new File(cmd.getOptionValue(OPT_INDEX)); String query = cmd.getOptionValue(OPT_QUERY); /** Check correctness of the path containing an ISODAC case */ if (!casePath.exists() || !casePath.isDirectory()) { logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid"); System.exit(1); } /** Check existance of the info.dat file */ File infoFile = new File(casePath, INFO_FILENAME); if (!infoFile.exists()) { logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")"); System.exit(1); } /** Load the mapping image_uuid --> image_filename */ imagesMap = new HashMap<Integer, String>(); BufferedReader reader = new BufferedReader(new FileReader(infoFile)); while (reader.ready()) { String line = reader.readLine(); logger.info("Read the line: " + line); String currentID = line.split("\t")[0]; String currentImgFile = line.split("\t")[1]; imagesMap.put(Integer.parseInt(currentID), currentImgFile); logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map"); } reader.close(); /** Load all the directories containing an index */ ArrayList<String> indexesDirs = new ArrayList<String>(); for (File f : casePath.listFiles()) { logger.info("Analyzing: " + f); if (f.isDirectory()) indexesDirs.add(f.getAbsolutePath()); } logger.info(indexesDirs.size() + " directories found!"); /** Set-up the searcher */ Searcher searcher = null; try { String[] array = indexesDirs.toArray(new String[indexesDirs.size()]); searcher = new Searcher(array); TopDocs results = searcher.search(query, Integer.MAX_VALUE); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < numTotalHits; i++) { Document doc = searcher.doc(hits[i].doc); String path = doc.get(FIELD_PATH); String filename = doc.get(FIELD_FILENAME); String image_uuid = doc.get(FIELD_IMAGE_ID); if (path != null) { //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score); // System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid); System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + imagesMap.get(Integer.parseInt(image_uuid))); } else { System.out.println((i + 1) + ". " + "No path for this document"); } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { if (searcher != null) searcher.close(); } }
From source file:PrefsUtil.java
public static void main(String[] args) { try {// w w w.j ava2s. co m Map map = new HashMap(); map.put("0", "A"); map.put("1", "B"); map.put("2", "C"); map.put("3", "D"); map.put("5", "f"); Preferences prefs = Preferences.userNodeForPackage(String.class); String RECENT_FILES = "XXX"; List recentFiles = PrefsUtil.getList(prefs, RECENT_FILES); PrefsUtil.clear(prefs, RECENT_FILES); PrefsUtil.putList(prefs, recentFiles, RECENT_FILES); //System.out.println( PrefsUtil.getList( prefs, RECENT_FILES ) ); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.example.bigtable.simplecli.HBaseCLI.java
/** * The main method for the CLI. This method takes the command line * arguments and runs the appropriate commands. */// ww w. ja v a 2 s. c om public static void main(String[] args) { // We use Apache commons-cli to check for a help option. Options options = new Options(); Option help = new Option("help", "print this message"); options.addOption(help); // create the parser CommandLineParser parser = new BasicParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println(exp.getMessage()); usage(); System.exit(1); } // Create a list of commands that are supported. Each // command defines a run method and some methods for // printing help. // See the definition of each command below. HashMap<String, Command> commands = new HashMap<String, Command>(); commands.put("create", new CreateCommand("create")); commands.put("scan", new ScanCommand("scan")); commands.put("get", new GetCommand("get")); commands.put("put", new PutCommand("put")); commands.put("list", new ListCommand("list")); Command command = null; List<String> argsList = Arrays.asList(args); if (argsList.size() > 0) { command = commands.get(argsList.get(0)); } // Check for the help option and if it's there // display the appropriate help. if (line.hasOption("help")) { // If there is a command listed (e.g. create -help) // then show the help for that command if (command == null) { help(commands.values()); } else { help(command); } System.exit(0); } else if (command == null) { // No valid command was given so print the usage. usage(); System.exit(0); } try { Connection connection = ConnectionFactory.createConnection(); try { try { // Run the command with the arguments after the command name. command.run(connection, argsList.subList(1, argsList.size())); } catch (InvalidArgsException e) { System.out.println("ERROR: Invalid arguments"); usage(command); System.exit(0); } } finally { // Make sure the connection is closed even if // an exception occurs. connection.close(); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.roncoo.pay.permission.utils.EncryptUtil.java
public static void main(String[] args) { String loginName = "513781560@qq.com"; Long timeStamp = System.currentTimeMillis(); String key = "rcPayLoginSign268"; String sign = RonCooSignUtil.getSign(key, timeStamp, loginName); String url = "http://192.168.1.181:8080/roncoo-dev-admin/mydata/getByLoginName"; Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", loginName); params.put("timeStamp", timeStamp); params.put("sign", sign); String json = JSON.toJSONString(params); String httpResponse = RoncooHttpClientUtils.post(url, json); Map<String, Object> parseObject = JSONObject.parseObject(httpResponse, Map.class); String code = (String) parseObject.get("code"); String desc = (String) parseObject.get("desc"); System.out.println(code);/*from w w w . j av a 2 s. c o m*/ JSONObject data = (JSONObject) parseObject.get("data"); Map<String, Object> mapInfo = JSONObject.parseObject(data.toJSONString(), Map.class); String returnPWD = (String) mapInfo.get("pwd"); String userId = (String) mapInfo.get("userId"); System.out.println(httpResponse); }
From source file:io.covert.binary.analysis.ExecutorThread.java
public static void main(String[] args) throws Exception { HashMap<String, Object> substitutionMap = new HashMap<String, Object>(); substitutionMap.put("file", "/home/jtrost/workspace/hadoop-binary-analysis/pom.xml"); ExecutorThread e = new ExecutorThread("sha1sum", new String[] { "${file}" }, substitutionMap, new int[] { 0, 1 }, Long.MAX_VALUE, new File("/tmp")); e.start();//from w w w. j a va 2s. c o m e.join(); System.out.println("exitCode = " + e.getExitCode()); System.out.println("exitCode = " + e.getExecuteException()); if (e.isProcessStarted() && !e.isProcessDestroyed()) { System.out.println("stdout: " + new String(e.getStdOut().toByteArray())); System.out.println("stderr: " + new String(e.getStdErr().toByteArray())); } else if (e.isProcessStarted()) { System.out.println("Process was launched, but process destroyed"); } else { System.out.println("Process not launched"); } }
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 {/* w w w . ja va 2s . com*/ 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); } } } }