List of usage examples for java.lang Exception Exception
public Exception(Throwable cause)
From source file:Main.java
public static String checkWifiConnection(final Activity activity) throws Exception { ConnectivityManager connManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mWifi.isConnected()) { new AlertDialog.Builder(activity).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error") .setMessage("Wifi not connected. Application will exit.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override/* w ww. jav a 2 s. c o m*/ public void onClick(DialogInterface dialog, int which) { //activity.finish(); } }).show(); throw new Exception("Wifi"); } WifiManager wifiMgr = (WifiManager) activity.getSystemService(Activity.WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); int ip = wifiInfo.getIpAddress(); return String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff)); }
From source file:Main.java
public static void isValidPort(String port) throws Exception { try {// w ww . j ava 2 s .c o m int p = Integer.parseInt(port); if (p < 1 || p > 65535) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new Exception("Invalid Port Number! '" + port + "'"); } }
From source file:com.aerospike.load.AerospikeLoad.java
public static void main(String[] args) throws IOException { Thread statPrinter = new Thread(new PrintStat(counters)); try {/* w w w . j a va 2 s.co m*/ log.info("Aerospike loader started"); Options options = new Options(); options.addOption("h", "host", true, "Server hostname (default: localhost)"); options.addOption("p", "port", true, "Server port (default: 3000)"); options.addOption("n", "namespace", true, "Namespace (default: test)"); options.addOption("s", "set", true, "Set name. (default: null)"); options.addOption("c", "config", true, "Column definition file name"); options.addOption("wt", "write-threads", true, "Number of writer threads (default: Number of cores * 5)"); options.addOption("rt", "read-threads", true, "Number of reader threads (default: Number of cores * 1)"); options.addOption("l", "rw-throttle", true, "Throttling of reader to writer(default: 10k) "); options.addOption("tt", "transaction-timeout", true, "write transaction timeout in miliseconds(default: No timeout)"); options.addOption("et", "expiration-time", true, "Expiration time of records in seconds (default: never expire)"); options.addOption("T", "timezone", true, "Timezone of source where data dump is taken (default: local timezone)"); options.addOption("ec", "abort-error-count", true, "Error count to abort (default: 0)"); options.addOption("wa", "write-action", true, "Write action if key already exists (default: update)"); options.addOption("v", "verbose", false, "Logging all"); options.addOption("u", "usage", false, "Print usage."); CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args, false); if (args.length == 0 || cl.hasOption("u")) { logUsage(options); return; } if (cl.hasOption("l")) { rwThrottle = Integer.parseInt(cl.getOptionValue("l")); } else { rwThrottle = Constants.READLOAD; } // Get all command line options params = Utils.parseParameters(cl); //Get client instance AerospikeClient client = new AerospikeClient(params.host, params.port); if (!client.isConnected()) { log.error("Client is not able to connect:" + params.host + ":" + params.port); return; } if (params.verbose) { log.setLevel(Level.DEBUG); } // Get available processors to calculate default number of threads int cpus = Runtime.getRuntime().availableProcessors(); nWriterThreads = cpus * scaleFactor; nReaderThreads = cpus; // Get writer thread count if (cl.hasOption("wt")) { nWriterThreads = Integer.parseInt(cl.getOptionValue("wt")); nWriterThreads = (nWriterThreads > 0 ? (nWriterThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nWriterThreads) : 1); log.debug("Using writer Threads: " + nWriterThreads); } writerPool = Executors.newFixedThreadPool(nWriterThreads); // Get reader thread count if (cl.hasOption("rt")) { nReaderThreads = Integer.parseInt(cl.getOptionValue("rt")); nReaderThreads = (nReaderThreads > 0 ? (nReaderThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nReaderThreads) : 1); log.debug("Using reader Threads: " + nReaderThreads); } String columnDefinitionFileName = cl.getOptionValue("c", null); log.debug("Column definition files/directory: " + columnDefinitionFileName); if (columnDefinitionFileName == null) { log.error("Column definition files/directory not specified. use -c <file name>"); return; } File columnDefinitionFile = new File(columnDefinitionFileName); if (!columnDefinitionFile.exists()) { log.error("Column definition files/directory does not exist: " + Utils.getFileName(columnDefinitionFileName)); return; } // Get data file list String[] files = cl.getArgs(); if (files.length == 0) { log.error("No data file Specified: add <file/dir name> to end of the command "); return; } List<String> allFileNames = new ArrayList<String>(); allFileNames = Utils.getFileNames(files); if (allFileNames.size() == 0) { log.error("Given datafiles/directory does not exist"); return; } for (int i = 0; i < allFileNames.size(); i++) { log.debug("File names:" + Utils.getFileName(allFileNames.get(i))); File file = new File(allFileNames.get(i)); counters.write.recordTotal = counters.write.recordTotal + file.length(); } //remove column definition file from list allFileNames.remove(columnDefinitionFileName); log.info("Number of data files:" + allFileNames.size()); /** * Process column definition file to get meta data and bin mapping. */ metadataColumnDefs = new ArrayList<ColumnDefinition>(); binColumnDefs = new ArrayList<ColumnDefinition>(); metadataConfigs = new HashMap<String, String>(); if (Parser.processJSONColumnDefinitions(columnDefinitionFile, metadataConfigs, metadataColumnDefs, binColumnDefs, params)) { log.info("Config file processed."); } else { throw new Exception("Config file parsing Error"); } // Add metadata of config to parameters String metadata; if ((metadata = metadataConfigs.get(Constants.INPUT_TYPE)) != null) { params.fileType = metadata; if (params.fileType.equals(Constants.CSV_FILE)) { // Version check metadata = metadataConfigs.get(Constants.VERSION); String[] vNumber = metadata.split("\\."); int v1 = Integer.parseInt(vNumber[0]); int v2 = Integer.parseInt(vNumber[1]); if ((v1 <= Constants.MajorV) && (v2 <= Constants.MinorV)) { log.debug("Config version used:" + metadata); } else throw new Exception("\"" + Constants.VERSION + ":" + metadata + "\" is not Supported"); // Set delimiter if ((metadata = metadataConfigs.get(Constants.DELIMITER)) != null && metadata.length() == 1) { params.delimiter = metadata.charAt(0); } else { log.warn("\"" + Constants.DELIMITER + ":" + metadata + "\" is not properly specified in config file. Default is ','"); } if ((metadata = metadataConfigs.get(Constants.IGNORE_FIRST_LINE)) != null) { params.ignoreFirstLine = metadata.equals("true"); } else { log.warn("\"" + Constants.IGNORE_FIRST_LINE + ":" + metadata + "\" is not properly specified in config file. Default is false"); } if ((metadata = metadataConfigs.get(Constants.COLUMNS)) != null) { counters.write.colTotal = Integer.parseInt(metadata); } else { throw new Exception("\"" + Constants.COLUMNS + ":" + metadata + "\" is not properly specified in config file"); } } else { throw new Exception("\"" + params.fileType + "\" is not supported in config file"); } } else { throw new Exception("\"" + Constants.INPUT_TYPE + "\" is not specified in config file"); } // add config input to column definitions if (params.fileType.equals(Constants.CSV_FILE)) { List<String> binName = null; if (params.ignoreFirstLine) { String line; BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(allFileNames.get(0)), "UTF8")); if ((line = br.readLine()) != null) { binName = Parser.getCSVRawColumns(line, params.delimiter); br.close(); if (binName.size() != counters.write.colTotal) { throw new Exception("Number of column in config file and datafile are mismatch." + " Datafile: " + Utils.getFileName(allFileNames.get(0)) + " Configfile: " + Utils.getFileName(columnDefinitionFileName)); } } } //update columndefs for metadata for (int i = 0; i < metadataColumnDefs.size(); i++) { if (metadataColumnDefs.get(i).staticValue) { } else { if (metadataColumnDefs.get(i).binValuePos < 0) { if (metadataColumnDefs.get(i).columnName == null) { if (metadataColumnDefs.get(i).jsonPath == null) { log.error("dynamic metadata having improper info" + metadataColumnDefs.toString()); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.indexOf(metadataColumnDefs.get(i).binValueHeader) != -1) { metadataColumnDefs.get(i).binValuePos = binName .indexOf(metadataColumnDefs.get(i).binValueHeader); } else { throw new Exception("binName missing in data file:" + metadataColumnDefs.get(i).binValueHeader); } } } } else { if (params.ignoreFirstLine) metadataColumnDefs.get(i).binValueHeader = binName .get(metadataColumnDefs.get(i).binValuePos); } } if ((!metadataColumnDefs.get(i).staticValue) && (metadataColumnDefs.get(i).binValuePos < 0)) { throw new Exception("Information for bin mapping is missing in config file:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).srcType == null) { throw new Exception( "Source data type is not properly mentioned:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).binNameHeader == Constants.SET && !metadataColumnDefs.get(i).srcType.equals(SrcColumnType.STRING)) { throw new Exception("Set name should be string type:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).binNameHeader.equalsIgnoreCase(Constants.SET) && params.set != null) { throw new Exception( "Set name is given both in config file and commandline. Provide only once."); } } //update columndefs for bins for (int i = 0; i < binColumnDefs.size(); i++) { if (binColumnDefs.get(i).staticName) { } else { if (binColumnDefs.get(i).binNamePos < 0) { if (binColumnDefs.get(i).columnName == null) { if (binColumnDefs.get(i).jsonPath == null) { log.error("dynamic bin having improper info"); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.indexOf(binColumnDefs.get(i).binNameHeader) != -1) { binColumnDefs.get(i).binNamePos = binName .indexOf(binColumnDefs.get(i).binNameHeader); } else { throw new Exception("binName missing in data file:" + binColumnDefs.get(i).binNameHeader); } } } } else { if (params.ignoreFirstLine) binColumnDefs.get(i).binNameHeader = binName.get(binColumnDefs.get(i).binNamePos); } } if (binColumnDefs.get(i).staticValue) { } else { if (binColumnDefs.get(i).binValuePos < 0) { if (binColumnDefs.get(i).columnName == null) { if (binColumnDefs.get(i).jsonPath == null) { log.error("dynamic bin having improper info"); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.contains(binColumnDefs.get(i).binValueHeader)) { binColumnDefs.get(i).binValuePos = binName .indexOf(binColumnDefs.get(i).binValueHeader); } else if (!binColumnDefs.get(i).binValueHeader.toLowerCase() .equals(Constants.SYSTEM_TIME)) { throw new Exception("Wrong column name mentioned in config file:" + binColumnDefs.get(i).binValueHeader); } } } } else { if (params.ignoreFirstLine) binColumnDefs.get(i).binValueHeader = binName.get(binColumnDefs.get(i).binValuePos); } //check for missing entries in config file if (binColumnDefs.get(i).binValuePos < 0 && binColumnDefs.get(i).binValueHeader == null) { throw new Exception("Information missing(Value header or bin mapping) in config file:" + binColumnDefs.get(i)); } //check for proper data type in config file. if (binColumnDefs.get(i).srcType == null) { throw new Exception( "Source data type is not properly mentioned:" + binColumnDefs.get(i)); } //check for valid destination type if ((binColumnDefs.get(i).srcType.equals(SrcColumnType.TIMESTAMP) || binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB)) && binColumnDefs.get(i).dstType == null) { throw new Exception("Destination type is not mentioned: " + binColumnDefs.get(i)); } //check for encoding if (binColumnDefs.get(i).dstType != null && binColumnDefs.get(i).encoding == null) { throw new Exception( "Encoding is not given for src-dst type conversion:" + binColumnDefs.get(i)); } //check for valid encoding if (binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB) && !binColumnDefs.get(i).encoding.equals(Constants.HEX_ENCODING)) { throw new Exception("Wrong encoding for blob data:" + binColumnDefs.get(i)); } } //Check static bin name mapped to dynamic bin value if ((binColumnDefs.get(i).binNamePos == binColumnDefs.get(i).binValuePos) && (binColumnDefs.get(i).binNamePos != -1)) { throw new Exception("Static bin name mapped to dynamic bin value:" + binColumnDefs.get(i)); } //check for missing entries in config file if (binColumnDefs.get(i).binNameHeader == null && binColumnDefs.get(i).binNameHeader.length() > Constants.BIN_NAME_LENGTH) { throw new Exception("Information missing binName or large binName in config file:" + binColumnDefs.get(i)); } } } log.info(params.toString()); log.debug("MetadataConfig:" + metadataColumnDefs); log.debug("BinColumnDefs:" + binColumnDefs); // Start PrintStat thread statPrinter.start(); // Reader pool size ExecutorService readerPool = Executors.newFixedThreadPool( nReaderThreads > allFileNames.size() ? allFileNames.size() : nReaderThreads); log.info("Reader pool size : " + nReaderThreads); // Submit all tasks to writer threadpool. for (String aFile : allFileNames) { log.debug("Submitting task for: " + aFile); readerPool.submit(new AerospikeLoad(aFile, client, params)); } // Wait for reader pool to complete readerPool.shutdown(); log.info("Shutdown down reader thread pool"); while (!readerPool.isTerminated()) ; //readerPool.awaitTermination(20, TimeUnit.MINUTES); log.info("Reader thread pool terminated"); // Wait for writer pool to complete after getting all tasks from reader pool writerPool.shutdown(); log.info("Shutdown down writer thread pool"); while (!writerPool.isTerminated()) ; log.info("Writer thread pool terminated"); // Print final statistic of aerospike-loader. log.info("Final Statistics of importer: (Succesfull Writes = " + counters.write.writeCount.get() + ", " + "Errors=" + (counters.write.writeErrors.get() + counters.write.readErrors.get() + counters.write.processingErrors.get()) + "(" + (counters.write.writeErrors.get()) + "-Write," + counters.write.readErrors.get() + "-Read," + counters.write.processingErrors.get() + "-Processing)"); } catch (Exception e) { log.error(e); if (log.isDebugEnabled()) { e.printStackTrace(); } } finally { // Stop statistic printer thread. statPrinter.interrupt(); log.info("Aerospike loader completed"); } }
From source file:Main.java
/** * Gets the child of the specified element having the specified unique * name. If there are more than one children elements with the same name * and exception is thrown./* ww w . ja v a2 s. c om*/ * * @param element The parent element * @param tagName The name of the desired child * @return The named child. * @throws Exception Child was not found or was not unique. */ public static Element getUniqueChild(Element element, String tagName) throws Exception { final Iterator goodChildren = getChildrenByTagName(element, tagName); if (goodChildren != null && goodChildren.hasNext()) { final Element child = (Element) goodChildren.next(); if (goodChildren.hasNext()) { throw new Exception("expected only one " + tagName + " tag"); } return child; } else { throw new Exception("expected one " + tagName + " tag"); } }
From source file:edu.msu.cme.rdp.seqmatch.cli.SeqmatchCheckRevSeq.java
public static void main(String[] args) throws Exception { String trainingFile = null;/* w w w . j a va 2s . c om*/ String queryFile = null; String outputFile = null; PrintWriter revOutputWriter = new PrintWriter(System.out); PrintStream correctedQueryOut = System.out; String traineeDesc = null; int numOfResults = 20; boolean checkReverse = false; float diffScoreCutoff = CheckReverseSeq.DIFF_SCORE_CUTOFF; String format = "txt"; // default try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("c")) { checkReverse = true; } if (line.hasOption("t")) { trainingFile = line.getOptionValue("t"); } else { throw new Exception("training file must be specified"); } if (line.hasOption("q")) { queryFile = line.getOptionValue("q"); } else { throw new Exception("query file must be specified"); } if (line.hasOption("o")) { outputFile = line.getOptionValue("o"); } else { throw new Exception("output file must be specified"); } if (line.hasOption("r")) { revOutputWriter = new PrintWriter(line.getOptionValue("r")); } if (line.hasOption("s")) { correctedQueryOut = new PrintStream(line.getOptionValue("s")); } if (line.hasOption("d")) { diffScoreCutoff = Float.parseFloat(line.getOptionValue("d")); } if (line.hasOption("h")) { traineeDesc = line.getOptionValue("h"); } if (line.hasOption("n")) { numOfResults = Integer.parseInt(line.getOptionValue("n")); } if (line.hasOption("f")) { format = line.getOptionValue("f"); if (!format.equals("tab") && !format.equals("dbformat") && !format.equals("xml")) { throw new IllegalArgumentException("Only dbformat, tab or xml format available"); } } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "SeqmatchCheckRevSeq", "", options, "", true); return; } SeqmatchCheckRevSeq theObj = new SeqmatchCheckRevSeq(); if (!checkReverse) { theObj.doUserLibMatch(queryFile, trainingFile, outputFile, numOfResults, format, traineeDesc); } else { theObj.checkRevSeq(queryFile, trainingFile, outputFile, revOutputWriter, correctedQueryOut, diffScoreCutoff, format, traineeDesc); } }
From source file:Main.java
public static Document loadXMLFrom(InputStream inputStream) throws Exception { Document doc = null;//from w w w. j ava 2 s.com DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); doc = builder.parse(inputStream); } catch (ParserConfigurationException pce) { throw new Exception(pce.getMessage()); } catch (SAXException se) { throw new Exception(se.getMessage()); } catch (IOException ioe) { throw new Exception(ioe.getMessage()); } finally { inputStream.close(); } return doc; }
From source file:com.ah.util.http.HttpFileTransferUtil.java
/** * upload files to ls// w w w . ja v a 2 s . c o m * @param fileNames - * @param urlParam - * @param delete - * @throws Exception - */ public static void uploadFilesToLS(String[] fileNames, String urlParam, boolean delete) throws Exception { HttpCommunication hc = uploadSettings(urlParam); for (String fileName : fileNames) { File file = new File(fileName); HttpResponse response = hc.uploadFile(null, file); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Fail to upload file " + fileName + ", statuscode=" + response.getStatusLine().getStatusCode() + ",message=" + response.getStatusLine().getReasonPhrase()); } else if (delete) { file.delete(); } } }
From source file:Stack.java
public void push(T item) throws Exception { if (top == items.length - 1) throw new Exception("Stack Full"); items[++top] = item;//from ww w .ja v a 2 s. c o m }
From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("r", "ref-seq", true, "Trim points are given as positions in a reference sequence from this file"); options.addOption("i", "inclusive", false, "Trim points are inclusive"); options.addOption("l", "length", true, "Minimum length of sequence after trimming"); options.addOption("f", "filled-ratio", true, "Minimum ratio of filled model positions of sequence after trimming"); options.addOption("o", "out", true, "Write sequences to directory (default=cwd)"); options.addOption("s", "stats", true, "Write stats to file"); PrintWriter statsOut = new PrintWriter(new NullWriter()); boolean inclusive = false; int minLength = 0; int minTrimmedLength = 0; int maxNs = 0; int maxTrimNs = 0; int trimStart = 0; int trimStop = 0; Sequence refSeq = null;//from w ww . j av a2 s. c om float minFilledRatio = 0; int expectedModelPos = -1; String[] inputFiles = null; File outdir = new File("."); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("ref-seq")) { refSeq = readRefSeq(new File(line.getOptionValue("ref-seq"))); } if (line.hasOption("inclusive")) { inclusive = true; } if (line.hasOption("length")) { minLength = Integer.valueOf(line.getOptionValue("length")); } if (line.hasOption("filled-ratio")) { minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio")); } if (line.hasOption("out")) { outdir = new File(line.getOptionValue("out")); if (!outdir.isDirectory()) { outdir = outdir.getParentFile(); System.err.println("Output option is not a directory, using " + outdir + " instead"); } } if (line.hasOption("stats")) { statsOut = new PrintWriter(line.getOptionValue("stats")); } args = line.getArgs(); if (args.length < 3) { throw new Exception("Unexpected number of arguments"); } trimStart = Integer.parseInt(args[0]); trimStop = Integer.parseInt(args[1]); inputFiles = Arrays.copyOfRange(args, 2, args.length); if (refSeq != null) { expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length(); trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model); trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model); } } catch (Exception e) { new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options); System.err.println("Error: " + e.getMessage()); } System.err.println("Starting sequence trimmer"); System.err.println("* Input files: " + Arrays.asList(inputFiles)); System.err.println("* Minimum Length: " + minLength); System.err.println("* Trim point inclusive?: " + inclusive); System.err.println("* Trim points: " + trimStart + "-" + trimStop); System.err.println("* Min filled ratio: " + minFilledRatio); System.err.println("* refSeq: " + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc())); Sequence seq; SeqReader reader; TrimStats stats; writeStatsHeader(statsOut); FastaWriter seqWriter; File in; for (String infile : inputFiles) { in = new File(infile); reader = new SequenceReader(in); seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName())); while ((seq = reader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop)); continue; } stats = getStats(seq, trimStart, trimStop); boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio); writeStats(statsOut, seq.getSeqName(), stats, passed); if (passed) { seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases)); } } reader.close(); seqWriter.close(); } statsOut.close(); }
From source file:Main.java
public static void isValidIP(String ip) throws Exception { try {/*from www .j ava 2s . c o m*/ String[] octets = ip.split("\\."); for (String s : octets) { int i = Integer.parseInt(s); if (i > 255 || i < 0) { throw new NumberFormatException(); } } } catch (NumberFormatException e) { throw new Exception("Invalid IP address! '" + ip + "'"); } }