List of usage examples for java.lang Exception Exception
public Exception(Throwable cause)
From source file:com.linkedin.helix.examples.ExampleProcess.java
public static void main(String[] args) throws Exception { String zkConnectString = "localhost:2181"; String clusterName = "storage-integration-cluster"; String instanceName = "localhost_8905"; String file = null;//from w ww . j a va 2 s. co m String stateModelValue = "MasterSlave"; int delay = 0; boolean skipZeroArgs = true;// false is for dev testing if (!skipZeroArgs || args.length > 0) { CommandLine cmd = processCommandLineArgs(args); zkConnectString = cmd.getOptionValue(zkServer); clusterName = cmd.getOptionValue(cluster); String host = cmd.getOptionValue(hostAddress); String portString = cmd.getOptionValue(hostPort); int port = Integer.parseInt(portString); instanceName = host + "_" + port; file = cmd.getOptionValue(configFile); if (file != null) { File f = new File(file); if (!f.exists()) { System.err.println("static config file doesn't exist"); System.exit(1); } } stateModelValue = cmd.getOptionValue(stateModel); if (cmd.hasOption(transDelay)) { try { delay = Integer.parseInt(cmd.getOptionValue(transDelay)); if (delay < 0) { throw new Exception("delay must be positive"); } } catch (Exception e) { e.printStackTrace(); delay = 0; } } } // Espresso_driver.py will consume this System.out.println("Starting Process with ZK:" + zkConnectString); ExampleProcess process = new ExampleProcess(zkConnectString, clusterName, instanceName, file, stateModelValue, delay); process.start(); Thread.currentThread().join(); }
From source file:lunarion.cluster.quickstart.ExampleProcess.java
public static void main(String[] args) throws Exception { String zkConnectString = "localhost:2181"; String clusterName = "storage-integration-cluster"; String instanceName = "localhost_8905"; String file = null;//from ww w .j av a 2 s .c o m String stateModelValue = "MasterSlave"; int delay = 0; boolean skipZeroArgs = true;// false is for dev testing if (!skipZeroArgs || args.length > 0) { CommandLine cmd = processCommandLineArgs(args); zkConnectString = cmd.getOptionValue(zkServer); clusterName = cmd.getOptionValue(cluster); String host = cmd.getOptionValue(hostAddress); String portString = cmd.getOptionValue(hostPort); int port = Integer.parseInt(portString); instanceName = host + "_" + port; file = cmd.getOptionValue(configFile); if (file != null) { File f = new File(file); if (!f.exists()) { System.err.println("static config file doesn't exist"); System.exit(1); } } stateModelValue = cmd.getOptionValue(stateModel); if (cmd.hasOption(transDelay)) { try { delay = Integer.parseInt(cmd.getOptionValue(transDelay)); if (delay < 0) { throw new Exception("delay must be positive"); } } catch (Exception e) { e.printStackTrace(); delay = 0; } } } // Espresso_driver.py will consume this System.out.println("Starting Process with ZK:" + zkConnectString); ExampleProcess process = new ExampleProcess(zkConnectString, clusterName, instanceName, file, stateModelValue, delay); process.start(); Runtime.getRuntime().addShutdownHook(new HelixManagerShutdownHook(process.getManager())); Thread.currentThread().join(); }
From source file:org.hammer.santamaria.mapper.dataset.CKANDataSetInput.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] pArgs) throws Exception { String id = "proportion-of-children-under-5-years-who-have-ever-breastfed-by-county-xls-2005-6"; String sId = EncodeURIComponent(id); String url = "https://africaopendata.org/api/action"; BSONObject dataset = new BasicBSONObject(); dataset.put("datasource", "Test"); dataset.put("id", id); LOG.info("---> id " + id + " - " + sId); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); LOG.info(//from w w w . jav a 2s . c o m "******************************************************************************************************"); LOG.info(" "); LOG.info(url + PACKAGE_GET + sId); LOG.info(" "); LOG.info( "******************************************************************************************************"); GetMethod method = new GetMethod(url + PACKAGE_GET + sId); method.setRequestHeader("User-Agent", "Hammer Project - SantaMaria crawler"); method.getParams().setParameter(HttpMethodParams.USER_AGENT, "Hammer Project - SantaMaria crawler"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); LOG.debug(new String(responseBody)); Document doc = Document.parse(new String(responseBody)); if (doc != null && doc.containsKey("result")) { Document result = new Document(); LOG.info(doc.get("result").getClass().toString()); if (doc.get("result") instanceof Document) { LOG.info("!!! Document result !!!!"); result = (Document) doc.get("result"); } else if (doc.get("result") instanceof ArrayList) { LOG.info("!!! Document list !!!!"); result = (Document) (((ArrayList) doc.get("result")).get(0)); } else { LOG.info("!!! NOT FOUND !!!!"); result = null; } LOG.info("result find!"); if (result != null) { dataset.put("title", result.get("title")); dataset.put("author", result.get("author")); dataset.put("author_email", result.get("author_email")); dataset.put("license_id", result.get("license_id")); } ArrayList<String> tags = new ArrayList<String>(); ArrayList<String> meta = new ArrayList<String>(); ArrayList<String> other_tags = new ArrayList<String>(); if (result.containsKey("author") && result.get("author") != null) other_tags.add(result.get("author").toString()); if (result.containsKey("title") && result.get("title") != null) other_tags.addAll(DSSUtils.GetKeyWordsFromText(result.get("title").toString())); if (result.containsKey("description") && result.get("description") != null) other_tags.addAll(DSSUtils.GetKeyWordsFromText(result.get("description").toString())); ArrayList<Document> resources = new ArrayList<Document>(); if (result != null && result.containsKey("resources")) { resources = (ArrayList<Document>) result.get("resources"); for (Document resource : resources) { if (resource.getString("format").toUpperCase().equals("JSON")) { dataset.put("dataset-type", "JSON"); dataset.put("url", resource.get("url")); dataset.put("created", resource.get("created")); dataset.put("description", resource.get("description")); dataset.put("revision_timestamp", resource.get("revision_timestamp")); meta = DSSUtils.GetMetaByResource(resource.get("url").toString()); } } } if (result != null && result.containsKey("tags")) { ArrayList<Document> tagsFromCKAN = (ArrayList<Document>) result.get("tags"); for (Document tag : tagsFromCKAN) { if (tag.containsKey("state") && tag.getString("state").toUpperCase().equals("ACTIVE")) { tags.add(tag.getString("display_name").trim().toLowerCase()); } else if (tag.containsKey("display_name")) { tags.add(tag.getString("display_name").trim().toLowerCase()); } } } dataset.put("tags", tags); dataset.put("meta", meta); dataset.put("resources", resources); dataset.put("other_tags", other_tags); } } catch (Exception e) { e.printStackTrace(); LOG.error(e); } finally { method.releaseConnection(); } //GetMetaByDocument("http://catalog.data.gov/api/action/package_show?id=1e68f387-5f1c-46c0-a0d1-46044ffef5bf"); }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public static void main(String args[]) { int numberEvents = 10000; //int brake = 1000; String server = "ags104"; int in_port = 5565; int out_port = 5575; int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("s", true, "Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("o", true, "Output TCP Port"); opts.addOption("r", true, "Range"); opts.addOption("h", false, "Help"); try {//from www . java 2s. co m CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("s")) { server = cmd.getOptionValue("s"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { in_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("o")) { String val = cmd.getOptionValue("o"); try { out_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for o. Must be integer.\n"; } } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new ParseException("Rate must be three comma seperated values or a single value"); } } catch (ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new ParseException(cmdInputErrorMsg); } DecimalFormat df = new DecimalFormat("##0"); RunTcpInTcpOutTest t = new RunTcpInTcpOutTest(); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, server, in_port, out_port, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); //for (int rate: rates) { for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, server, in_port, out_port, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:edu.msu.cme.rdp.alignment.pairwise.PairwiseKNN.java
public static void main(String[] args) throws Exception { File queryFile;//w w w . j a va2s. c om File refFile; AlignmentMode mode = AlignmentMode.glocal; int k = 1; int wordSize = 0; int prefilter = 10; // The top p closest protein targets PrintStream out = new PrintStream(System.out); Options options = new Options(); options.addOption("m", "mode", true, "Alignment mode {global, glocal, local, overlap, overlap_trimmed} (default= glocal)"); options.addOption("k", true, "K-nearest neighbors to return. (default = 1)"); options.addOption("o", "out", true, "Redirect output to file instead of stdout"); options.addOption("p", "prefilter", true, "The top p closest targets from kmer prefilter step. Set p=0 to disable the prefilter step. (default = 10) "); options.addOption("w", "word-size", true, "The word size used to find closest targets during prefilter. (default " + ProteinWordGenerator.WORDSIZE + " for protein, " + GoodWordIterator.DEFAULT_WORDSIZE + " for nucleotide)"); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("mode")) { mode = AlignmentMode.valueOf(line.getOptionValue("mode")); } if (line.hasOption('k')) { k = Integer.valueOf(line.getOptionValue('k')); if (k < 1) { throw new Exception("k must be at least 1"); } } if (line.hasOption("word-size")) { wordSize = Integer.parseInt(line.getOptionValue("word-size")); if (wordSize < 3) { throw new Exception("Word size must be at least 3"); } } if (line.hasOption("prefilter")) { prefilter = Integer.parseInt(line.getOptionValue("prefilter")); // prefilter == 0 means no prefilter if (prefilter > 0 && prefilter < k) { throw new Exception("prefilter must be at least as big as k " + k); } } if (line.hasOption("out")) { out = new PrintStream(line.getOptionValue("out")); } args = line.getArgs(); if (args.length != 2) { throw new Exception("Unexpected number of command line arguments"); } queryFile = new File(args[0]); refFile = new File(args[1]); } catch (Exception e) { new HelpFormatter().printHelp("PairwiseKNN <options> <queryFile> <dbFile>", options); System.err.println("ERROR: " + e.getMessage()); return; } PairwiseKNN theObj = new PairwiseKNN(queryFile, refFile, out, mode, k, wordSize, prefilter); theObj.match(); }
From source file:ProxyAuthTest.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Usage ProxyAuthTest <host> <port> <server_principal> <proxy_user> [testTab]"); System.exit(1);// w w w.j a va 2 s. c o m } File currentResultFile = null; String[] beeLineArgs = {}; Class.forName(driverName); String host = args[0]; String port = args[1]; String serverPrincipal = args[2]; String proxyUser = args[3]; String url = null; if (args.length > 4) { tabName = args[4]; } generateData(); generateSQL(null); try { /* * Connect via kerberos and get delegation token */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); // get delegation token for the given proxy user String token = ((HiveConnection) con).getDelegationToken(proxyUser, serverPrincipal); if ("true".equals(System.getProperty("proxyAuth.debug", "false"))) { System.out.println("Got token: " + token); } con.close(); // so that beeline won't kill the JVM System.setProperty(BEELINE_EXIT, "true"); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar" }; System.out.println("Connection with kerberos, user/password via args, using input rediction"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input redirect"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); /* * Connect using the delegation token passed via configuration object */ System.out.println("Store token into ugi and try"); storeTokenInJobConf(token); url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); System.out.println("Connecting to " + url); runTest(); con.close(); // connect using token via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken" }; System.out.println("Connection with token, user/password via args, using input redirection"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); System.out.println("Connection with token, user/password via connect, using input script"); beeLineArgs = new String[] { "-f", scriptFileName, "-a", "delegationToken" }; BeeLine.main(beeLineArgs); compareResults(currentResultFile); /* * Connect via kerberos with trusted proxy user */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal + ";hive.server2.proxy.user=" + proxyUser; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); runTest(); ((HiveConnection) con).cancelDelegationToken(token); con.close(); } catch (SQLException e) { System.out.println("*** SQLException: " + e.getMessage() + " : " + e.getSQLState()); e.printStackTrace(); } /* verify the connection fails after canceling the token */ try { url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); throw new Exception("connection should have failed after token cancelation"); } catch (SQLException e) { // Expected to fail due to canceled token } }
From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java
public static void main(String args[]) { // Example Command line args //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000 int numberEvents = 10000; // Number of Events String gisServer = "w12ags104a.jennings.home"; // GIS Server int inputTcpPort = 5565; // TCP Input Port String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0"; String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("g", true, "GIS Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("m", true, "Map Service Layer URL"); opts.addOption("f", true, "File with GeoEvents to Send"); opts.addOption("r", true, "Rates to test Start,End,Step"); opts.addOption("h", false, "Help"); try {/*from w w w. java 2 s . c om*/ CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (org.apache.commons.cli.ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new org.apache.commons.cli.ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("g")) { gisServer = cmd.getOptionValue("g"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { inputTcpPort = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("m")) { msLayerUrl = cmd.getOptionValue("m"); } if (cmd.hasOption("f")) { EventsInputFile = cmd.getOptionValue("f"); } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new org.apache.commons.cli.ParseException( "Rate must be three comma seperated values or a single value"); } } catch (org.apache.commons.cli.ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg); } // Assuming the ES port is 9220 RunTcpInBdsOutTest t = new RunTcpInBdsOutTest(); DecimalFormat df = new DecimalFormat("##0"); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); Thread.sleep(3 * 1000); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)"); final SeqReader queryReader; final List<Sequence> refSeqList; final PrintStream alignOutStream; final CompareErrorType errorProcessor; Sequence seq;/* ww w . j a va 2 s .c o m*/ Map<String, PAObject> matchMap = new HashMap(); try { CommandLine line = new PosixParser().parse(options, args); String stem; args = line.getArgs(); if (args.length != 2 && args.length != 3) { throw new Exception("Unexpected number of arguments"); } File refFile = new File(args[0]); File queryFile = new File(args[1]); if (line.hasOption("stem")) { stem = line.getOptionValue("stem"); } else { stem = queryFile.getName(); } File alignOutFile = new File(stem + "_alignments.txt"); File mismatchOutFile = new File(stem + "_mismatches.txt"); File indelOutFile = new File(stem + "_indels.txt"); File qualOutFile = null; refSeqList = SequenceReader.readFully(refFile); if (args.length == 3) { queryReader = new QSeqReader(queryFile, new File(args[2])); } else { queryReader = new SequenceReader(queryFile); } seq = queryReader.readNextSequence(); if (seq instanceof QSequence) { qualOutFile = new File(stem + "_qual.txt"); } errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile); alignOutStream = new PrintStream(alignOutFile); System.err.println("Starting CompareErrorType"); System.err.println("* Time: " + new Date()); System.err.println("* Reference File: " + refFile); System.err.println("* Query File: " + queryFile); if (args.length == 3) { System.err.println("* Qual File: " + args[2]); } System.err.println("* Query format: " + queryReader.getFormat()); System.err.println("* Alignment Output: " + alignOutFile); System.err.println("* Mismatches Output: " + mismatchOutFile); System.err.println("* Alignment Output: " + indelOutFile); if (qualOutFile != null) { System.err.println("* Quality Output: " + qualOutFile); } } catch (Exception e) { new HelpFormatter().printHelp( "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)", options); System.err.println("ERROR: " + e.getMessage()); throw new RuntimeException(e); //System.exit(1); //return; } //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix(); // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1. ScoringMatrix scoringMatrix = new ScoringMatrix( ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1); do { try { PairwiseAlignment bestResult = null; Sequence bestSeq = null; boolean bestReversed = false; String querySeqStr = seq.getSeqString().toLowerCase(); String reversedQuery = IUBUtilities.reverseComplement(querySeqStr); PAObject bestMatch = null; //checking if sequence has been seen before if (matchMap.containsKey(seq.getSeqString())) { bestMatch = matchMap.get(seq.getSeqString()); } else { for (Sequence refSeq : refSeqList) { String refSeqStr = refSeq.getSeqString().toLowerCase(); PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix, AlignmentMode.global); PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr, IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global); PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result : reversedResult; if (bestResult == null || currBest.getScore() > bestResult.getScore()) { bestResult = currBest; bestSeq = refSeq; if (currBest == reversedResult) { bestReversed = true; } else { bestReversed = false; } } //Since this is a new sequence, make a new PAObject to put into the map to compare against later bestMatch = new PAObject(bestResult, bestReversed, bestSeq); matchMap.put(seq.getSeqString(), bestMatch); } } int refStart = bestMatch.getPA().getStarti(); int refEnd = bestMatch.getPA().getEndi(); bestSeq = bestMatch.getRefSeq(); bestReversed = bestMatch.getReversed(); bestResult = bestMatch.getPA(); //output information alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t" + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t" + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : "")); alignOutStream.println(bestResult.getAlignedSeqj() + "\n"); alignOutStream.println(bestResult.getAlignedSeqi() + "\n"); //seqi is reference seq, seqj is the refseq errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(), bestResult.getAlignedSeqi(), refStart, bestReversed); } catch (Exception e) { throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e); } } while ((seq = queryReader.readNextSequence()) != null); queryReader.close(); alignOutStream.close(); errorProcessor.close(); }
From source file:Main.java
public static String fromSecondsToMMSS(int seconds) throws Exception { if (seconds > 3600) throw new Exception("more than an hour"); int m = (int) Math.floor(seconds / 60); int s = seconds - (m * 60); String mm = m > 0 ? String.format("%2d", m) + ":" : ""; String ss = m > 0 ? String.format("%02d", s) : String.format("%2d", s); return mm + ss; }
From source file:Main.java
public static String maskCardNumber(String clearcardnumber) throws Exception { if (clearcardnumber.length() < 10) { throw new Exception("Invalid number of digits"); }// ww w. j a va 2s . c o m int length = clearcardnumber.length(); String prefix = clearcardnumber.substring(0, 4); String suffix = clearcardnumber.substring(length - 4); StringBuffer mask = new StringBuffer(); mask.append(prefix).append("XXXXXXXXXX").append(suffix); return mask.toString(); }