List of usage examples for java.lang String toLowerCase
public String toLowerCase()
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host//from w w w .jav a 2 s .c o m String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }
From source file:mzmatch.ipeak.align.CowCoda.java
@SuppressWarnings("unchecked") public static void main(String args[]) { final String lbl_mcq = "mcq"; try {//w w w. j a va 2 s. co m Tool.init(); // parse the commandline options final Options options = new Options(); CmdLineParser cmdline = new CmdLineParser(options); // check whether we need to show the help cmdline.parse(args); if (options.help) { Tool.printHeader(System.out, application, version); cmdline.printUsage(System.out, ""); return; } if (options.verbose) { Tool.printHeader(System.out, application, version); cmdline.printOptions(); } // check the command-line parameters int filetype = JFreeChartTools.PDF; { if (options.ppm == -1) { System.err.println("[ERROR]: the ppm-value needs to be set."); System.exit(0); } if (options.order == -1) { System.err.println("[ERROR]: the order for the polynomial fit needs to be set."); System.exit(0); } if (options.maxrt == -1) { System.err.println("[ERROR]: the maximum retention time shift is not set."); System.exit(0); } if (options.image != null) { String extension = options.image.substring(options.image.lastIndexOf('.') + 1); if (extension.toLowerCase().equals("png")) filetype = JFreeChartTools.PNG; else if (extension.toLowerCase().equals("pdf")) filetype = JFreeChartTools.PDF; else { System.err.println( "[ERROR]: file extension of the image file needs to be either PDF or PNG."); System.exit(0); } } // if the output directories do not exist, create them if (options.output != null) Tool.createFilePath(options.output, true); if (options.image != null) Tool.createFilePath(options.image, true); if (options.selection != null) Tool.createFilePath(options.selection, true); } // load the data if (options.verbose) System.out.println("Loading the data"); double maxrt = 0; Vector<ParseResult> data = new Vector<ParseResult>(); Vector<IPeakSet<IPeak>> matchdata = new Vector<IPeakSet<IPeak>>(); for (String file : options.input) { System.out.println("- " + new File(file).getName()); // load the mass chromatogram data ParseResult result = PeakMLParser.parse(new FileInputStream(file), true); data.add(result); // select the best mass chromatograms Vector<IPeak> selection = new Vector<IPeak>(); for (IPeak peak : (IPeakSet<IPeak>) result.measurement) { maxrt = Math.max(maxrt, maxRT(peak)); double mcq = codaDW(peak); peak.addAnnotation(lbl_mcq, Double.toString(mcq), Annotation.ValueType.DOUBLE); if (mcq >= options.codadw) selection.add(peak); } // keep track of the selected mass chromatograms int id = options.input.indexOf(file); IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(selection); peakset.setMeasurementID(id); for (IPeak mc : peakset) mc.setMeasurementID(id); matchdata.add(peakset); } // match the selection together if (options.verbose) System.out.println("Matching the data"); Vector<IPeakSet<IPeak>> matches = IPeak.match((Vector) matchdata, options.ppm, new IPeak.MatchCompare<IPeak>() { public double distance(IPeak peak1, IPeak peak2) { double diff = Math.abs(peak1.getRetentionTime() - peak2.getRetentionTime()); if (diff > options.maxrt) return -1; Signal signal1 = new Signal(peak1.getSignal()); signal1.normalize(); Signal signal2 = new Signal(peak2.getSignal()); signal2.normalize(); double offset = bestOffSet(peak1, peak2, options.maxrt); for (int i = 0; i < signal2.getSize(); ++i) signal2.getX()[i] += offset; double correlation = signal2 .pearsonsCorrelation(signal1)[Statistical.PEARSON_CORRELATION]; if (correlation < 0.5) return -1; // the match-function optimizes toward 0 (it's a distance) return 1 - correlation; } }); // filter out all incomplete sets Vector<IPeakSet<IPeak>> valids = new Vector<IPeakSet<IPeak>>(); for (IPeakSet<IPeak> set : matches) { if (set.size() < options.input.size()) continue; valids.add((IPeakSet) set); } // calculate the alignment factors if (options.verbose) System.out.println("Calculating the alignment factors"); double medians[] = new double[valids.size() + 2]; DataFrame.Double dataframe = new DataFrame.Double(valids.size() + 2, options.input.size()); medians[0] = 0; medians[medians.length - 1] = maxrt; for (int i = 0; i < options.input.size(); ++i) { dataframe.set(0, i, 0.1); dataframe.set(dataframe.getNrRows() - 1, i, 0); } for (int matchid = 0; matchid < valids.size(); ++matchid) { IPeakSet<IPeak> match = valids.get(matchid); // find the most central double offsets[][] = new double[match.size()][match.size()]; for (int i = 0; i < match.size(); ++i) for (int j = i + 1; j < match.size(); ++j) { offsets[i][j] = bestOffSet(match.get(i), match.get(j), options.maxrt); offsets[j][i] = -offsets[i][j]; } int besti = 0; double bestabssum = Double.MAX_VALUE; for (int i = 0; i < match.size(); ++i) { double abssum = 0; for (int j = 0; j < match.size(); ++j) abssum += Math.abs(offsets[i][j]); if (abssum < bestabssum) { besti = i; bestabssum = abssum; } } for (int i = 0; i < match.size(); ++i) dataframe.set(matchid + 1, match.get(i).getMeasurementID(), (i == besti ? 0 : offsets[i][besti])); medians[matchid + 1] = match.get(besti).getRetentionTime(); dataframe.setRowName(matchid, Double.toString(match.get(besti).getRetentionTime())); } double minmedian = Statistical.min(medians); double maxmedian = Statistical.max(medians); // calculate for each profile the correction function PolynomialFunction functions[] = new PolynomialFunction[valids.size()]; for (int i = 0; i < options.input.size(); ++i) functions[i] = PolynomialFunction.fit(options.order, medians, dataframe.getCol(i)); // make a nice plot out of the whole thing if (options.verbose) System.out.println("Writing results"); if (options.image != null) { org.jfree.data.xy.XYSeriesCollection dataset = new org.jfree.data.xy.XYSeriesCollection(); JFreeChart linechart = ChartFactory.createXYLineChart(null, "Retention Time (seconds)", "offset", dataset, PlotOrientation.VERTICAL, true, // legend false, // tooltips false // urls ); // setup the colorkey Colormap colormap = new Colormap(Colormap.EXCEL); // get the structure behind the graph XYPlot plot = (XYPlot) linechart.getPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); // setup the plot area linechart.setBackgroundPaint(java.awt.Color.WHITE); linechart.setBorderVisible(false); linechart.setAntiAlias(true); plot.setBackgroundPaint(java.awt.Color.WHITE); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); // create the datasets for (int i = 0; i < options.input.size(); ++i) { org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i)); org.jfree.data.xy.XYSeries function = new org.jfree.data.xy.XYSeries( dataframe.getColName(i) + "-function"); dataset.addSeries(series); dataset.addSeries(function); renderer.setSeriesPaint(dataset.getSeriesCount() - 1, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesPaint(dataset.getSeriesCount() - 2, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesLinesVisible(dataset.getSeriesCount() - 2, false); renderer.setSeriesShapesVisible(dataset.getSeriesCount() - 2, true); // add the data-points for (int j = 0; j < valids.size(); ++j) series.add(medians[j], dataframe.get(j, i)); for (double x = minmedian; x < maxmedian; ++x) function.add(x, functions[i].getY(x)); } dataset.removeAllSeries(); for (int i = 0; i < options.input.size(); ++i) { Function function = functions[i]; org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i)); dataset.addSeries(series); renderer.setSeriesPaint(i, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesLinesVisible(i, false); renderer.setSeriesShapesVisible(i, true); // add the data-points for (int j = 0; j < valids.size(); ++j) series.add(medians[j], dataframe.get(j, i) - function.getY(medians[j])); } JFreeChartTools.writeAs(filetype, new FileOutputStream(options.image), linechart, 800, 500); } // save the selected if (options.selection != null) { Header header = new Header(); // set the number of peaks to be stored header.setNrPeaks(valids.size()); // create a set for the measurements SetInfo set = new SetInfo("", SetInfo.SET); header.addSetInfo(set); // create the measurement infos for (int i = 0; i < options.input.size(); ++i) { String file = options.input.get(i); // create the measurement info MeasurementInfo measurement = new MeasurementInfo(i, data.get(i).header.getMeasurementInfo(0)); measurement.addFileInfo(new FileInfo(file, file)); header.addMeasurementInfo(measurement); // add the file to the set set.addChild(new SetInfo(file, SetInfo.SET, i)); } // write the data PeakMLWriter.write(header, (Vector) valids, null, new GZIPOutputStream(new FileOutputStream(options.selection)), null); } // correct the values with the found function and save them for (int i = 0; i < options.input.size(); ++i) { Function function = functions[i]; ParseResult result = data.get(i); IPeakSet<MassChromatogram<Peak>> peakset = (IPeakSet<MassChromatogram<Peak>>) result.measurement; for (IPeak peak : peakset) align(peak, function); File filename = new File(options.input.get(i)); String name = filename.getName(); PeakMLWriter.write(result.header, (Vector) peakset.getPeaks(), null, new GZIPOutputStream(new FileOutputStream(options.output + "/" + name)), null); } } catch (Exception e) { Tool.unexpectedError(e, application); } }
From source file:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * // w w w . j a v a 2 s. c o m * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }
From source file:edu.wpi.khufnagle.webimagemanager.WebImageManager.java
/** * Defines information for the lighthouses, then runs the * photograph-collection process.// w w w . ja va 2 s. co m * @param args Command-line arguments for this program (not used in this * implementation) */ // Auto-boxing done "on the fly" to show progress of downloading images @SuppressWarnings("boxing") public static void main(final String[] args) { final long startTime = System.nanoTime(); System.out.println("***BEGIN PHOTO TRANSFER PROCESS***"); // Add data for lighthouses (next 375 lines or so) final List<LighthouseInfo> lighthouseData = new ArrayList<LighthouseInfo>(); /* * lighthouseData.add(new LighthouseInfo("Statue of Liberty", 40.689348, * -74.044726)); */// Statue of Liberty = 2080 photos w/out restrictions lighthouseData.add(new LighthouseInfo("Portland Head Light", 43.623104, -70.207867)); lighthouseData.add(new LighthouseInfo("Pemaquid Point Light", 43.836970, -69.505997)); lighthouseData.add(new LighthouseInfo("Five Mile Point (New Haven Harbor) Light", 41.248958, -72.903766)); lighthouseData.add(new LighthouseInfo("Cape Neddick (Nubble) Light", 43.165211, -70.591102)); lighthouseData.add(new LighthouseInfo("Portland Breakwater Light", 43.655516, -70.234813)); lighthouseData.add(new LighthouseInfo("Beavertail Light", 41.449368, -71.399372)); lighthouseData.add(new LighthouseInfo("Bass Harbor Head Light", 44.221976, -68.337214)); lighthouseData.add(new LighthouseInfo("Nobska Point Light", 41.515792, -70.655116)); lighthouseData.add(new LighthouseInfo("Spring Point Ledge Light", 43.652108, -70.223922)); lighthouseData.add(new LighthouseInfo("Gay Head Light", 41.348450, -70.834956)); lighthouseData.add(new LighthouseInfo("Derby Wharf Light", 42.516566, -70.883536)); lighthouseData.add(new LighthouseInfo("Rockland Breakwater Light", 44.104006, -69.077453)); lighthouseData.add(new LighthouseInfo("Sandy Neck Light", 41.722647, -70.280927)); lighthouseData.add(new LighthouseInfo("Marblehead Light", 42.505411, -70.833708)); lighthouseData.add(new LighthouseInfo("Portsmouth Harbor Light", 43.071061, -70.708634)); lighthouseData.add(new LighthouseInfo("Highland Light", 42.039122, -70.062025)); lighthouseData.add(new LighthouseInfo("Cape Elizabeth Light", 43.566058, -70.200042)); lighthouseData.add(new LighthouseInfo("Marshall Point Light", 43.917406, -69.261222)); lighthouseData.add(new LighthouseInfo("Chatham Light", 41.671407, -69.949884)); lighthouseData.add(new LighthouseInfo("Block Island Southeast Light", 41.153412, -71.552117)); lighthouseData.add(new LighthouseInfo("Edgartown Light", 41.390863, -70.503057)); lighthouseData.add(new LighthouseInfo("Watch Hill Light", 41.303884, -71.858575)); lighthouseData.add(new LighthouseInfo("Nauset Light", 41.858305, -69.951631)); lighthouseData .add(new LighthouseInfo("Fayerweather Island (Black Rock Harbor) Light", 41.142380, -73.217409)); lighthouseData.add(new LighthouseInfo("Owls Head Light", 44.092138, -69.044105)); lighthouseData.add(new LighthouseInfo("Point Judith Light", 41.361035, -71.481402)); lighthouseData.add(new LighthouseInfo("Sankaty Head Light", 41.284379, -69.966244)); lighthouseData.add(new LighthouseInfo("Eastern Point Light", 42.580229, -70.664537)); lighthouseData.add(new LighthouseInfo("Fort Pickering Light", 42.526473, -70.866465)); lighthouseData.add(new LighthouseInfo("Wood Island Light", 43.456788, -70.328976)); lighthouseData.add(new LighthouseInfo("Stonington Harbor Light", 41.328780, -71.905486)); lighthouseData.add(new LighthouseInfo("West Quoddy Head Light", 44.815073, -66.950742)); lighthouseData.add(new LighthouseInfo("Fort Point Light", 44.467265, -68.811717)); lighthouseData.add(new LighthouseInfo("Annisquam Light", 42.661874, -70.681488)); lighthouseData.add(new LighthouseInfo("Newport Harbor Light", 41.493299, -71.327038)); lighthouseData.add(new LighthouseInfo("Long Point Light", 42.033117, -70.168651)); lighthouseData.add(new LighthouseInfo("Castle Hill Light", 41.462116, -71.362919)); lighthouseData.add(new LighthouseInfo("Brant Point Light", 41.289918, -70.090287)); lighthouseData.add(new LighthouseInfo("Stratford Point Light", 41.151984, -73.103276)); lighthouseData.add(new LighthouseInfo("Boston Light", 42.327925, -70.890101)); lighthouseData.add(new LighthouseInfo("Lynde Point Light", 41.271452, -72.343142)); lighthouseData.add(new LighthouseInfo("Scituate Light", 42.204748, -70.715814)); lighthouseData.add(new LighthouseInfo("Prospect Harbor Light", 44.403285, -68.012922)); lighthouseData.add(new LighthouseInfo("Wood End Light", 42.021223, -70.193502)); lighthouseData.add(new LighthouseInfo("Rose Island Light", 41.495477, -71.342742)); lighthouseData.add(new LighthouseInfo("Saybrook Breakwater Light", 41.263158, -72.342813)); lighthouseData.add(new LighthouseInfo("Great Point Light", 41.390096, -70.048234)); lighthouseData.add(new LighthouseInfo("Cape Poge Light", 41.418798, -70.451923)); lighthouseData.add(new LighthouseInfo("Monhegan Light", 43.764779, -69.316204)); lighthouseData.add(new LighthouseInfo("Hendricks Head Light", 43.822589, -69.689761)); lighthouseData.add(new LighthouseInfo("Egg Rock Light", 44.354050, -68.138166)); lighthouseData.add(new LighthouseInfo("New London Ledge Light", 41.305826, -72.077448)); lighthouseData.add(new LighthouseInfo("Avery Point Lighthouse", 41.315245, -72.063579)); lighthouseData.add(new LighthouseInfo("Palmers Island Light", 41.626936, -70.909109)); lighthouseData.add(new LighthouseInfo("Cuckolds Light", 43.779663, -69.649982)); lighthouseData.add(new LighthouseInfo("Gull Rocks Light", 41.502451, -71.333140)); lighthouseData.add(new LighthouseInfo("Goat Island Light", 43.357826, -70.425109)); lighthouseData.add(new LighthouseInfo("East Chop Light", 41.470245, -70.567439)); lighthouseData.add(new LighthouseInfo("Neds Point Light", 41.650859, -70.795638)); lighthouseData.add(new LighthouseInfo("Sakonnet Point Light", 41.453090, -71.202382)); lighthouseData.add(new LighthouseInfo("Narrows (Bug) Light", 42.323137, -70.919158)); lighthouseData.add(new LighthouseInfo("Plum Island Light", 42.815119, -70.818981)); lighthouseData.add(new LighthouseInfo("Block Island North Light", 41.227639, -71.575811)); lighthouseData.add(new LighthouseInfo("Mount Desert Rock Light", 43.968582, -68.128306)); lighthouseData.add(new LighthouseInfo("Duxbury Pier Light", 41.987375, -70.648498)); lighthouseData.add(new LighthouseInfo("Long Island Head Light", 42.330197, -70.957712)); lighthouseData.add(new LighthouseInfo("Prudence Island Light", 41.605881, -71.303535)); lighthouseData.add(new LighthouseInfo("Plum Beach Light", 41.530248, -71.405202)); lighthouseData.add(new LighthouseInfo("Doubling Point Light", 43.882503, -69.806792)); lighthouseData.add(new LighthouseInfo("Dice Head Light", 44.382732, -68.819022)); lighthouseData.add(new LighthouseInfo("Ram Island Ledge Light", 43.631457, -70.187366)); lighthouseData.add(new LighthouseInfo("New London Harbor Light", 41.316619, -72.089743)); lighthouseData.add(new LighthouseInfo("Lime Rock Light", 41.477536, -71.325924)); lighthouseData.add(new LighthouseInfo("Ten Pound Island Light", 42.601865, -70.665556)); lighthouseData.add(new LighthouseInfo("Bristol Ferry Light", 41.642842, -71.260319)); lighthouseData.add(new LighthouseInfo("Musselbed Shoals Light", 41.636261, -71.259958)); lighthouseData.add(new LighthouseInfo("Conimicut Light", 41.716969, -71.345106)); lighthouseData.add(new LighthouseInfo("Tongue Point Light", 41.166590, -73.177497)); lighthouseData.add(new LighthouseInfo("Bass River Light", 41.651746, -70.169473)); lighthouseData.add(new LighthouseInfo("Hospital Point Light", 42.546413, -70.856164)); lighthouseData.add(new LighthouseInfo("Newburyport Range Light", 42.811524, -70.864838)); lighthouseData.add(new LighthouseInfo("Dutch Island Light", 41.496702, -71.404299)); lighthouseData.add(new LighthouseInfo("Heron Neck Light", 44.025216, -68.861966)); lighthouseData.add(new LighthouseInfo("Pumpkin Island Light", 44.309166, -68.742876)); lighthouseData.add(new LighthouseInfo("Whaleback Light", 43.058744, -70.696306)); lighthouseData.add(new LighthouseInfo("Hyannis Harbor Light", 41.636267, -70.288439)); lighthouseData.add(new LighthouseInfo("Stage Harbor Light", 41.658692, -69.983689)); lighthouseData.add(new LighthouseInfo("Lovells Island Range Light", 42.332440, -70.930214)); lighthouseData.add(new LighthouseInfo("Hog Island Shoal Light", 41.632338, -71.273198)); lighthouseData.add(new LighthouseInfo("Ram Island Light", 43.803935, -69.599349)); lighthouseData.add(new LighthouseInfo("Bridgeport Harbor Light", 41.156718, -73.179950)); lighthouseData.add(new LighthouseInfo("Straitsmouth Island Light", 42.662236, -70.588157)); lighthouseData.add(new LighthouseInfo("Squirrel Point Light", 43.816520, -69.802402)); lighthouseData.add(new LighthouseInfo("Mayos Beach Light", 41.930755, -70.032097)); lighthouseData.add(new LighthouseInfo("Race Point Light", 42.062314, -70.243084)); lighthouseData.add(new LighthouseInfo("Point Gammon Light", 41.609647, -70.266196)); lighthouseData.add(new LighthouseInfo("Wings Neck Light", 41.680235, -70.661250)); lighthouseData.add(new LighthouseInfo("West Chop Light", 41.480806, -70.599796)); lighthouseData.add(new LighthouseInfo("Bird Island Light", 41.669295, -70.717341)); lighthouseData.add(new LighthouseInfo("Clarks Point Light", 41.593176, -70.901416)); lighthouseData.add(new LighthouseInfo("Thacher Island Light", 42.639168, -70.574759)); lighthouseData.add(new LighthouseInfo("White Island Light", 42.967228, -70.623249)); lighthouseData.add(new LighthouseInfo("Wickford Harbor Light", 41.572618, -71.436831)); lighthouseData.add(new LighthouseInfo("Whale Rock Light", 41.444597, -71.423584)); lighthouseData.add(new LighthouseInfo("Burnt Island Light", 43.825133, -69.640262)); lighthouseData.add(new LighthouseInfo("Rockland Harbor Southwest Light", 44.082720, -69.096310)); lighthouseData.add(new LighthouseInfo("Saddleback Ledge Light", 44.014232, -68.726461)); lighthouseData.add(new LighthouseInfo("Grindle Point Light", 44.281451, -68.942967)); lighthouseData.add(new LighthouseInfo("Winter Harbor Light", 44.361421, -68.087742)); lighthouseData.add(new LighthouseInfo("Peck's Ledge Light", 41.077298, -73.369811)); lighthouseData.add(new LighthouseInfo("Sheffield Island Light", 41.048251, -73.419931)); lighthouseData.add(new LighthouseInfo("Whitlocks Mill Light", 45.162793, -67.227395)); lighthouseData.add(new LighthouseInfo("Boon Island Light", 43.121183, -70.475845)); lighthouseData.add(new LighthouseInfo("Southwest Ledge Light", 41.234443, -72.912092)); lighthouseData.add(new LighthouseInfo("Broad Sound Channel Inner Range Light", 42.326933, -70.984649)); lighthouseData.add(new LighthouseInfo("Spectacle Island Light", 42.326898, -70.984772)); lighthouseData.add(new LighthouseInfo("Deer Island Light", 42.339836, -70.954525)); lighthouseData.add(new LighthouseInfo("Nayatt Point Light", 41.725120, -71.338926)); lighthouseData.add(new LighthouseInfo("Doubling Point Range Lights", 43.882860, -69.795652)); lighthouseData.add(new LighthouseInfo("Burkehaven Light", 43.371669, -72.065869)); lighthouseData.add(new LighthouseInfo("Loon Island Light", 43.392123, -72.059977)); lighthouseData.add(new LighthouseInfo("Curtis Island Light", 44.201372, -69.048865)); lighthouseData.add(new LighthouseInfo("Butler Flats Light", 41.603775, -70.894556)); lighthouseData.add(new LighthouseInfo("Graves Light", 42.365098, -70.869191)); lighthouseData.add(new LighthouseInfo("Stamford Harbor Light", 41.013643, -73.542577)); lighthouseData.add(new LighthouseInfo("Billingsgate Light", 41.871624, -70.068982)); lighthouseData.add(new LighthouseInfo("Monomoy Point Light", 41.559310, -69.993650)); lighthouseData.add(new LighthouseInfo("Bishop & Clerks Light", 41.574154, -70.249963)); lighthouseData.add(new LighthouseInfo("Plymouth Light", 42.003737, -70.600565)); lighthouseData.add(new LighthouseInfo("Cleveland Ledge Light", 41.630927, -70.694201)); lighthouseData.add(new LighthouseInfo("Tarpaulin Cove Light", 41.468822, -70.757514)); lighthouseData.add(new LighthouseInfo("Minots Ledge Light", 42.269678, -70.759136)); lighthouseData.add(new LighthouseInfo("Dumpling Rock Light", 41.538167, -70.921427)); lighthouseData.add(new LighthouseInfo("Bakers Island Light", 42.536470, -70.785995)); lighthouseData.add(new LighthouseInfo("Cuttyhunk Light", 41.414391, -70.949558)); lighthouseData.add(new LighthouseInfo("Egg Rock Light", 42.433346, -70.897386)); lighthouseData.add(new LighthouseInfo("Ipswich Range Light", 42.685360, -70.766128)); lighthouseData.add(new LighthouseInfo("Borden Flats Light", 41.704450, -71.174395)); lighthouseData.add(new LighthouseInfo("Bullocks Point Light", 41.737740, -71.364179)); lighthouseData.add(new LighthouseInfo("Pomham Rocks Light", 41.777618, -71.369594)); lighthouseData.add(new LighthouseInfo("Sabin Point Light", 41.762010, -71.374234)); lighthouseData.add(new LighthouseInfo("Fuller Rock Light", 41.794055, -71.379720)); lighthouseData.add(new LighthouseInfo("Gould Island Light", 41.537826, -71.344804)); lighthouseData.add(new LighthouseInfo("Warwick Light", 41.667111, -71.378413)); lighthouseData.add(new LighthouseInfo("Sassafras Point Light", 41.802496, -71.390272)); lighthouseData.add(new LighthouseInfo("Conanicut Light", 41.573484, -71.371767)); lighthouseData.add(new LighthouseInfo("Poplar Point Light", 41.571053, -71.439189)); lighthouseData.add(new LighthouseInfo("Halfway Rock Light", 43.655873, -70.037402)); lighthouseData.add(new LighthouseInfo("Seguin Island Light", 43.707554, -69.758118)); lighthouseData.add(new LighthouseInfo("Pond Island Light", 43.740031, -69.770273)); lighthouseData.add(new LighthouseInfo("Perkins Island Light", 43.786764, -69.785256)); lighthouseData.add(new LighthouseInfo("Latimer Reef Light", 41.304503, -71.933292)); lighthouseData.add(new LighthouseInfo("Morgan Point Light", 41.316669, -71.989327)); lighthouseData.add(new LighthouseInfo("Franklin Island Light", 43.892184, -69.374842)); lighthouseData.add(new LighthouseInfo("Matinicus Rock Light", 43.783605, -68.854898)); lighthouseData.add(new LighthouseInfo("Tenants Harbor Light", 43.961107, -69.184877)); lighthouseData.add(new LighthouseInfo("Whitehead Light", 43.978706, -69.124285)); lighthouseData.add(new LighthouseInfo("Two Bush Island Light", 43.964239, -69.073942)); lighthouseData.add(new LighthouseInfo("Indian Island Light", 44.165470, -69.061004)); lighthouseData.add(new LighthouseInfo("Browns Head Light", 44.111774, -68.909482)); lighthouseData.add(new LighthouseInfo("Goose Rocks Light", 44.135394, -68.830526)); lighthouseData.add(new LighthouseInfo("Sperry Light", 41.221221, -72.423110)); lighthouseData.add(new LighthouseInfo("Isle au Haut Light", 44.064733, -68.651339)); lighthouseData.add(new LighthouseInfo("Deer Island Thorofare Light", 44.134338, -68.703202)); lighthouseData.add(new LighthouseInfo("Herrick Cove Light", 43.411136, -72.041706)); lighthouseData.add(new LighthouseInfo("Eagle Island Light", 44.217634, -68.767743)); lighthouseData.add(new LighthouseInfo("Burnt Coat Harbor Light", 44.134176, -68.447258)); lighthouseData.add(new LighthouseInfo("Faulkner's Island Light", 41.211612, -72.655088)); lighthouseData.add(new LighthouseInfo("Blue Hill Bay Light", 44.248746, -68.497880)); lighthouseData.add(new LighthouseInfo("Great Duck Island Light", 44.142193, -68.245836)); lighthouseData.add(new LighthouseInfo("Bear Island Light", 44.283485, -68.269858)); lighthouseData.add(new LighthouseInfo("Baker Island Light", 44.241266, -68.198923)); lighthouseData.add(new LighthouseInfo("Crabtree Ledge Light", 44.475613, -68.199383)); lighthouseData.add(new LighthouseInfo("Statford Shoal Light", 41.059557, -73.101394)); lighthouseData.add(new LighthouseInfo("Petit Manan Light", 44.367574, -67.864129)); lighthouseData.add(new LighthouseInfo("Penfield Reef Light", 41.117101, -73.222070)); lighthouseData.add(new LighthouseInfo("Narraguagus Light", 44.462467, -67.837844)); lighthouseData.add(new LighthouseInfo("Nash Island Light", 44.464305, -67.747299)); lighthouseData.add(new LighthouseInfo("Moose Peak Light", 44.474244, -67.533471)); lighthouseData.add(new LighthouseInfo("Green's Ledge Light", 41.041551, -73.443974)); lighthouseData.add(new LighthouseInfo("Libby Island Light", 44.568236, -67.367339)); lighthouseData.add(new LighthouseInfo("Great Captain Island Light", 40.982478, -73.623706)); lighthouseData.add(new LighthouseInfo("Avery Rock Light", 44.654358, -67.344137)); lighthouseData.add(new LighthouseInfo("Little River Light", 44.650873, -67.192325)); lighthouseData.add(new LighthouseInfo("Lubec Channel Light", 44.841955, -66.976731)); lighthouseData.add(new LighthouseInfo("St. Croix River Light", 45.128762, -67.133594)); /* * "Clean out" photo directories before beginning photo transfer process. */ final File photosDir = new File("photos"); final File[] photoLighthouseDirsToDelete = photosDir.listFiles(); if (photoLighthouseDirsToDelete != null) { for (final File photoLighthouseDir : photoLighthouseDirsToDelete) { // Use Apache Commons IO (again) to recursively delete the directory // and all of the files within it if (photoLighthouseDir.exists() && photoLighthouseDir.isDirectory()) { try { FileUtils.deleteDirectory(photoLighthouseDir); System.out.println("Deleted directory \"" + photoLighthouseDir + "\" successfully."); } catch (final IOException ioe) { System.err.println( "Could not delete directory: \"" + photoLighthouseDir + "\" successfully!"); } } } } // Keep track of elapsed time long estimatedTime = System.nanoTime() - startTime; String elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime); System.out.println("Estimated elapsed time: " + elapsedTime + "."); System.out.println(); /* * Keep track of total number of photographs transferred from Flickr * websites to disks across _all_ lighthouses */ int totalNumPhotosTransferred = 0; /* * Keep track of total number of photographs that _should_ be transferred * from Flickr for _all_ lighthouses */ int totalNumPhotos = 0; for (final LighthouseInfo lighthousePieceOfData : lighthouseData) { System.out.println("Processing photos of " + lighthousePieceOfData.getName() + "..."); /* * URL for accessing Flickr APIs. For a given lighthouse, this URL * provides an XML file in response that lists information about every * geotagged, Creative Commons-enabled photograph for that lighthouse * on Flickr. */ // GET Parameter Explanation: // method - Use the "search photos" method for the Flickr APIs // // api_key - A unique key that I use to get the results // // text - Find all lighthouses whose title, tags, or description // contains the word "lighthouse" // // license - Find all photos with a Creative Commons license _except_ // those that do not allow for modification on my part // // content_type - Find photos only (no videos) // // has_geo - Implicitly set to true; implies that all photos are // geotagged // // lat - The latitude of the center of the "search circle" // // lon - The longitude of the center of the "search circle" // // radius - The radius of the "search circle," in _kilometers_ (NOT // miles) // // extras - Also include a URL to the "raw" photo (small version) final String inputURLText = "http://ycpi.api.flickr.com/services/rest/?" + "method=flickr.photos.search" + "&api_key=3ea8366b020383eb91f170c6f41748f5" + "&text=lighthouse" + "&license=1,2,4,5,7" + "&content_type=1" + "&has_geo" + "&lat=" + lighthousePieceOfData.getLatitude() + "&lon=" + lighthousePieceOfData.getLongitude() + "&radius=1" + "&extras=url_s"; // Output file where XML web response will be stored temporarily final String outputFileName = "output.xml"; /* * Convert the name of the lighthouse to a "computer friendly" version * with all lower-case letters and underscores replacing spaces, * apostrophes, and parenthesis */ String lighthouseName = lighthousePieceOfData.getName(); lighthouseName = lighthouseName.toLowerCase(); lighthouseName = lighthouseName.replace(' ', '_'); lighthouseName = lighthouseName.replace('\'', '_'); lighthouseName = lighthouseName.replace('(', '_'); lighthouseName = lighthouseName.replace(')', '_'); // Will contain the textual links to each "raw" photo website Set<String> rawPhotoURLs = new HashSet<String>(); // Make sure file for XML output does not exist at first // (don't want to use an old, incorrect version accidentally) final File outputXMLFile = new File(outputFileName); if (outputXMLFile.exists()) { outputXMLFile.delete(); } System.out.println("Cleaned output XML file containing photo URLs on disk successfully."); /* * Access the list of photographs for a given lighthouse and copy them * to the XML file on disk */ final WebDataExtractor extractor = new WebDataExtractor(inputURLText, outputFileName); System.out.println("Looking for XML file containing lighthosue photo information..."); extractor.transferURLToFile(); System.out.println("Found XML file containing lighthouse photo URLs."); /* * Object for extracting the "raw" URLs from each piece of photo data * in the XML file */ final XMLParser parser = new FlickrXMLOutputParser(outputFileName); // Complete the extraction process rawPhotoURLs = parser.parseFile("//photo/@url_s"); final int numPhotos = rawPhotoURLs.size(); totalNumPhotos += numPhotos; int i = 0; // Counter for keeping track of progress /* * Keep track of photos transferred successfully (which might be less * than the total number of photos defined int the XML output from * Flickr, especially if connection issues occur */ int numPhotosTransferred = 0; for (final String photoURL : rawPhotoURLs) { System.out.print("Transferring photos..."); i++; /* * Go to a website containing a "raw" JPEG image file and save it * accordingly on disk in the photo folder corresponding to the * lighthouse name */ final WebDataExtractor rawPhotoExtractor = new WebDataExtractor(photoURL, "photos/" + lighthouseName + "/lighthouse_photo_" + Integer.toString(i) + ".jpg"); final boolean transferSuccessful = rawPhotoExtractor.transferURLToFile(); if (transferSuccessful) { numPhotosTransferred++; } // Simple progress tracker System.out.printf("%d of %d (%.1f%%) complete.\n", i, numPhotos, i * 1.0 / numPhotos * 100.0); } // Indicate number of photos successfully transferred to disk if (numPhotosTransferred == numPhotos && numPhotos > 0) { System.out.println("All photos transferred to disk successfully!"); } else if (numPhotos == 0) { System.out.println("It appears there are no photos available for this lighthouse..."); } else if (numPhotosTransferred == 1 && numPhotos > 1) { System.out.println("1 photo transferred to disk successfully."); } else if (numPhotosTransferred == 1 && numPhotos == 1) { System.out.println("The photo transferred to disk successfully!"); } else { System.out.println(numPhotosTransferred + " photos transferred to disk successfully."); } // Keep track of elapsed time estimatedTime = System.nanoTime() - startTime; elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime); System.out.println("Estimated elapsed time: " + elapsedTime + "."); // Add extra line in between lighthouses in output stream System.out.println(); /* * Keep track of total number of photos transferred so far across * _all_lighthouses */ totalNumPhotosTransferred += numPhotosTransferred; } // Display "grand" total (which is hopefully greater than 0) System.out.println("***GRAND TOTAL: " + totalNumPhotosTransferred + " OF " + totalNumPhotos + " PHOTOS TRANSFERRED SUCCESSFULLY***"); estimatedTime = System.nanoTime() - startTime; elapsedTime = WebImageManager.calculateElapsedTime(estimatedTime); System.out.println("TOTAL ELAPSED TIME: " + elapsedTime.toUpperCase()); }
From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java
/** * @param args the command line arguments */// www . j ava 2 s . c o m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println( "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String Combined_Prot = ""; boolean DefaultProtFiltering = true; float Freq = 0f; int TopNPep = 6; int TopNFrag = 6; String FilterWeight = "GW"; float MinWeight = 0.9f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); boolean ExportSaint = false; boolean SAINT_MS1 = false; boolean SAINT_MS2 = true; HashMap<String, String[]> BaitList = new HashMap<>(); HashMap<String, String> BaitName = new HashMap<>(); HashMap<String, String[]> ControlList = new HashMap<>(); HashMap<String, String> ControlName = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } case "Combined_Prot": { Combined_Prot = value; break; } case "DefaultProtFiltering": { DefaultProtFiltering = Boolean.parseBoolean(value); break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "ProteinFDR": { tandemPara.ProtFDR = Float.parseFloat(value); break; } case "FilterWeight": { FilterWeight = value; break; } case "MinWeight": { MinWeight = Float.parseFloat(value); break; } case "TopNFrag": { TopNFrag = Integer.parseInt(value); break; } case "TopNPep": { TopNPep = Integer.parseInt(value); break; } case "Freq": { Freq = Float.parseFloat(value); break; } //<editor-fold defaultstate="collapsed" desc="SaintOutput"> case "ExportSaintInput": { ExportSaint = Boolean.parseBoolean(value); break; } case "QuantitationType": { switch (value) { case "MS1": { SAINT_MS1 = true; SAINT_MS2 = false; break; } case "MS2": { SAINT_MS1 = false; SAINT_MS2 = true; break; } case "BOTH": { SAINT_MS1 = true; SAINT_MS2 = true; break; } } break; } // case "BaitInputFile": { // SaintBaitFile = value; // break; // } // case "PreyInputFile": { // SaintPreyFile = value; // break; // } // case "InterationInputFile": { // SaintInteractionFile = value; // break; // } default: { if (type.startsWith("BaitName_")) { BaitName.put(type.substring(9), value); } if (type.startsWith("BaitFile_")) { BaitList.put(type.substring(9), value.split("\t")); } if (type.startsWith("ControlName_")) { ControlName.put(type.substring(12), value); } if (type.startsWith("ControlFile_")) { ControlList.put(type.substring(12), value.split("\t")); } break; } //</editor-fold> } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Check if the prot.xml file can be found if (!new File(Combined_Prot).exists()) { Logger.getRootLogger().info("ProtXML file: " + Combined_Prot + " cannot be found, the export protein summary table will be empty."); } LCMSID protID = null; //Parse prot.xml and generate protein master list given an FDR if (Combined_Prot != null && !Combined_Prot.equals("")) { protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot); if (!"".equals(Combined_Prot) && protID == null) { protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath); ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f); //Use DIA-Umpire default protein FDR calculation if (DefaultProtFiltering) { protID.RemoveLowLocalPWProtein(0.8f); protID.RemoveLowMaxIniProbProtein(0.9f); protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR); } //Get protein FDR calculation without other filtering else { protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR); } protID.LoadSequence(); protID.WriteLCMSIDSerialization(Combined_Prot); } Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size()); } HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>(); //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); try { File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.ClearAssignPeakCluster(); FileList.add(DiaFile); HashMap<String, FragmentPeak> FragMap = new HashMap<>(); IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap); } } } //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection"> Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset"); ArrayList<LCMSID> SummaryList = new ArrayList<>(); for (DIAPack diafile : FileList) { if (protID != null) { //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true); diafile.IDsummary.ReMapProPep(); } if ("GW".equals(FilterWeight)) { diafile.IDsummary.SetFilterByGroupWeight(); } else if ("PepW".equals(FilterWeight)) { diafile.IDsummary.SetFilterByWeight(); } SummaryList.add(diafile.IDsummary); } FragmentSelection fragselection = new FragmentSelection(SummaryList); fragselection.freqPercent = Freq; fragselection.GeneratePepFragScoreMap(); fragselection.GenerateTopFragMap(TopNFrag); fragselection.GenerateProtPepScoreMap(MinWeight); fragselection.GenerateTopPepMap(TopNPep); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Writing general reports"> ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID, fragselection); export.Export(TopNPep, TopNFrag, Freq); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files"> if (ExportSaint && protID != null) { HashMap<String, DIAPack> Filemap = new HashMap<>(); for (DIAPack DIAfile : FileList) { Filemap.put(DIAfile.GetBaseName(), DIAfile); } FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt"); FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt"); FileWriter interactionfileMS1 = null; FileWriter interactionfileMS2 = null; if (SAINT_MS1) { interactionfileMS1 = new FileWriter( WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt"); } if (SAINT_MS2) { interactionfileMS2 = new FileWriter( WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt"); } HashMap<String, String> PreyID = new HashMap<>(); for (String samplekey : ControlName.keySet()) { String name = ControlName.get(samplekey); for (String file : ControlList.get(samplekey)) { baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n"); LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary; if (SAINT_MS1) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID, 1); } if (SAINT_MS2) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID, 2); } } } for (String samplekey : BaitName.keySet()) { String name = BaitName.get(samplekey); for (String file : BaitList.get(samplekey)) { baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n"); LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary; if (SAINT_MS1) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID, 1); } if (SAINT_MS2) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID, 2); } } } baitfile.close(); if (SAINT_MS1) { interactionfileMS1.close(); } if (SAINT_MS2) { interactionfileMS2.close(); } for (String AccNo : PreyID.keySet()) { preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n"); } preyfile.close(); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * // w w w .j av a2 s. c om * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:com.bright.json.PGS.java
public static void main(String[] args) throws FileNotFoundException { String fileBasename = null;/*from w w w .j a v a 2 s . co m*/ JFileChooser chooser = new JFileChooser(); try { FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Select the Excel file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } String fileName = chooser.getSelectedFile().toString(); InputStream inp = new FileInputStream(fileName); Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { try { workbook = new XSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fileName.toLowerCase().endsWith("xls")) { try { workbook = new HSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Sheet nodeSheet = workbook.getSheet("Devices"); Sheet interfaceSheet = workbook.getSheet("Interfaces"); System.out.println("Read nodes sheet."); // Row nodeRow = nodeSheet.getRow(1); // System.out.println(row.getCell(0).toString()); // System.exit(0); JTextField uiHost = new JTextField("demo.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("demo.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("root"); // TextPrompt puiUser = new TextPrompt("root", uiUser); JTextField uiPass = new JPasswordField(""); // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies); Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies); Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies); Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies); Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies); // System.out.println(switches.get("switch01")); // System.out.println("Size of the map: "+ switches.size()); // System.exit(0); cmDevice newnode = new cmDevice(); cmDevice.deviceObject devObj = new cmDevice.deviceObject(); cmDevice.switchObject switchObj = new cmDevice.switchObject(); // cmDevice.netObject netObj = new cmDevice.netObject(); List<String> emptyslist = new ArrayList<String>(); // Row nodeRow = nodeSheet.getRow(1); // Row ifRow = interfaceSheet.getRow(1); // System.out.println(nodeRow.getCell(0).toString()); // nodeRow.getCell(3).getStringCellValue() Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>(); // Map<String,netObject> helperMap = new HashMap<String,netObject>(); // Iterator<Row> rows = interfaceSheet.rowIterator (); // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) { // List<netObject> netList = new ArrayList<netObject>(); for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) { Row ifRow = interfaceSheet.getRow(i); if (ifRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } System.out.println("Row nr: " + ifRow.getRowNum()); cmDevice.netObject netObj = new cmDevice.netObject(); ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>(); netObj.setBaseType("NetworkInterface"); netObj.setCardType(ifRow.getCell(3).getStringCellValue()); netObj.setChildType(ifRow.getCell(4).getStringCellValue()); netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false); netObj.setIp(ifRow.getCell(7).getStringCellValue()); // netObj.setMac(ifRow.getCell(0).toString()); //netObj.setModified(true); netObj.setName(ifRow.getCell(1).getStringCellValue()); netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue())); //netObj.setOldLocalUniqueKey(0L); netObj.setRevision(""); netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setStartIf("ALWAYS"); netObj.setToBeRemoved(false); netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue()); //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()); netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMembers(new ArrayList<String>(Arrays .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); // ifmap.put(ifRow.getCell(0).getStringCellValue(), new // HashMap<String, cmDevice.netObject>()); // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ; // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(), // netObj); // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap); if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) { ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>()); } helperList = ifmap.get(ifRow.getCell(0).getStringCellValue()); helperList.add(netObj); ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList); continue; } for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) { Row nodeRow = nodeSheet.getRow(i); if (nodeRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } newnode.setService("cmdevice"); newnode.setCall("addDevice"); Map<String, Long> ifmap2 = new HashMap<String, Long>(); for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue())) ifmap2.put(j.getName(), j.getUniqueKey()); switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue())); System.out.println(nodeRow.getCell(8).getStringCellValue()); System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue())); switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue()); switchObj.setBaseType("SwitchPort"); devObj.setBaseType("Device"); // devObj.setCreationTime(0L); devObj.setCustomPingScript(""); devObj.setCustomPingScriptArgument(""); devObj.setCustomPowerScript(""); devObj.setCustomPowerScriptArgument(""); devObj.setCustomRemoteConsoleScript(""); devObj.setCustomRemoteConsoleScriptArgument(""); devObj.setDisksetup(""); devObj.setBmcPowerResetDelay(0L); devObj.setBurning(false); devObj.setEthernetSwitch(switchObj); devObj.setExcludeListFull(""); devObj.setExcludeListGrab(""); devObj.setExcludeListGrabnew(""); devObj.setExcludeListManipulateScript(""); devObj.setExcludeListSync(""); devObj.setExcludeListUpdate(""); devObj.setFinalize(""); devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue())); devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue()); devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue()); devObj.setIndexInsideContainer(0L); devObj.setInitialize(""); devObj.setInstallBootRecord(false); devObj.setInstallMode(""); devObj.setIoScheduler(""); devObj.setLastProvisioningNode(0L); devObj.setMac(nodeRow.getCell(6).getStringCellValue()); devObj.setModified(true); devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue())); devObj.setChildType("PhysicalNode"); //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true // : false); devObj.setHostname(nodeRow.getCell(0).getStringCellValue()); devObj.setModified(true); devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue())); devObj.setUseExclusivelyFor("Category"); devObj.setNextBootInstallMode(""); devObj.setNotes(""); devObj.setOldLocalUniqueKey(0L); devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue()); // System.out.println(ifmap.get("excelnode001").size()); // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey()); devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue())); devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue())); devObj.setProvisioningTransport("RSYNCDAEMON"); devObj.setPxelabel(""); // "rack": 90194313218, // "rackHeight": 1, // "rackPosition": 4, devObj.setRaidconf(""); devObj.setRevision(""); devObj.setSoftwareImageProxy(null); devObj.setStartNewBurn(false); devObj.setTag("00000000a000"); devObj.setToBeRemoved(false); // devObj.setUcsInfoConfigured(null); // devObj.setUniqueKey(12345L); devObj.setUserdefined1(""); devObj.setUserdefined2(""); ArrayList<Object> mylist = new ArrayList<Object>(); ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>(); ArrayList<Object> emptylist = new ArrayList<Object>(); devObj.setFsexports(emptylist); devObj.setFsmounts(emptylist); devObj.setGpuSettings(emptylist); devObj.setFspartAssociations(emptylist); devObj.setPowerDistributionUnits(emptyslist); devObj.setRoles(emptylist); devObj.setServices(emptylist); devObj.setStaticRoutes(emptylist); mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue()); devObj.setNetworks(mylist2); mylist.add(devObj); mylist.add(1); newnode.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(newnode); // To be used from a real console and not Eclipse String message = JSonRequestor.doRequest(json2, cmURL, cookies); continue; } JOptionPane optionPaneF = new JOptionPane("The nodes have been added!"); JDialog myDialogF = optionPaneF.createDialog(null, "Complete: "); myDialogF.setModal(false); myDialogF.setVisible(true); doLogout(cmURL, cookies); // System.exit(0); }
From source file:com.github.vatbub.awsvpnlauncher.Main.java
public static void main(String[] args) { Common.getInstance().setAppName("awsVpnLauncher"); FOKLogger.enableLoggingOfUncaughtExceptions(); prefs = new Preferences(Main.class.getName()); // enable the shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (session != null) { if (session.isConnected()) { session.disconnect();/*from w w w . j av a 2s .c om*/ } } })); UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> { if (oldVersion != null) { FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName() + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion()); } }); List<String> argsAsList = new ArrayList<>(Arrays.asList(args)); for (String arg : args) { if (arg.toLowerCase().matches("mockappversion=.*")) { // Set the mock version String version = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockAppVersion(version); argsAsList.remove(arg); } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) { // Set the mock build number String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockBuildNumber(buildnumber); argsAsList.remove(arg); } else if (arg.toLowerCase().matches("mockpackaging=.*")) { // Set the mock packaging String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockPackaging(packaging); argsAsList.remove(arg); } } args = argsAsList.toArray(new String[0]); try { mvnRepoConfig = new Config( new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"), Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true); projectConfig = new Config( new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"), Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true); } catch (IOException e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e); } try { installUpdates(args); } catch (Exception e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e); } if (args.length == 0) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } switch (args[0].toLowerCase()) { case "setup": setup(); break; case "launch": initAWSConnection(); launch(); break; case "terminate": initAWSConnection(); terminate(); break; case "config": // require a second arg if (args.length == 2) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } config(Property.valueOf(args[1]), args[2]); break; case "getconfig": // require a second arg if (args.length == 1) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } getConfig(Property.valueOf(args[1])); break; case "printconfig": printConfig(); break; case "deleteconfig": // require a second arg if (args.length == 1) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } deleteConfig(Property.valueOf(args[1])); break; case "ssh": String sshInstanceId; if (args.length == 2) { // a instanceID is specified sshInstanceId = args[1]; } else { String instanceIdsPrefValue = prefs.getPreference("instanceIDs", ""); if (instanceIdsPrefValue.equals("")) { throw new NotEnoughArgumentsException( "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter."); } List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";")); if (instanceIds.size() == 1) { // exactly one instance found sshInstanceId = instanceIds.get(0); } else { FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:"); for (String instanceId : instanceIds) { FOKLogger.severe(Main.class.getName(), instanceId); } throw new NotEnoughArgumentsException( "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter."); } } initAWSConnection(); ssh(sshInstanceId); break; default: printHelpMessage(); } }
From source file:mamo.vanillaVotifier.VanillaVotifier.java
public static void main(String[] args) { String[] javaVersion = System.getProperty("java.version").split("\\."); if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2 && Integer.parseInt(javaVersion[1]) >= 6)) { System.out.println(("You need at least Java 1.6 to run this program! Current version: " + System.getProperty("java.version") + ".")); return;//w ww .ja v a2 s. c o m } VanillaVotifier votifier = new VanillaVotifier(); for (String arg : args) { if (arg.equalsIgnoreCase("-report-exceptions")) { votifier.reportExceptions = true; } else if (arg.equalsIgnoreCase("-help")) { votifier.getLogger().printlnTranslation("s58"); return; } else { votifier.getLogger().printlnTranslation("s55", new AbstractMap.SimpleEntry<String, Object>("option", arg)); return; } } votifier.getLogger().printlnTranslation("s42"); if (!(loadConfig(votifier) && startServer(votifier))) { return; } Scanner in = new Scanner(System.in); while (true) { String command; try { command = in.nextLine(); } catch (NoSuchElementException e) { // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring. continue; } catch (Exception e) { votifier.getLogger().printlnTranslation("s57", new AbstractMap.SimpleEntry<String, Object>("exception", e)); if (!stopServer(votifier)) { System.exit(0); // "return" somehow isn't enough. } return; } if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) { if (command.split(" ").length == 1) { stopServer(votifier); break; } else { votifier.getLogger().printlnTranslation("s17"); } } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) { if (command.split(" ").length == 1) { Listener listener = new Listener() { @Override public void onEvent(Event event, VanillaVotifier votifier) { if (event instanceof ServerStoppedEvent) { if (loadConfig((VanillaVotifier) votifier) && startServer((VanillaVotifier) votifier)) { votifier.getServer().getListeners().remove(this); } else { System.exit(0); } } } }; votifier.getServer().getListeners().add(listener); if (!stopServer(votifier)) { // Kill the process if the server doesn't stop System.exit(0); // "return" somehow isn't enough. return; } } else { votifier.getLogger().printlnTranslation("s56"); } } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) { String[] commandArgs = command.split(" "); int keySize; if (commandArgs.length == 1) { keySize = 2048; } else if (commandArgs.length == 2) { try { keySize = Integer.parseInt(commandArgs[1]); } catch (NumberFormatException e) { votifier.getLogger().printlnTranslation("s19"); continue; } if (keySize < 512) { votifier.getLogger().printlnTranslation("s51"); continue; } if (keySize > 16384) { votifier.getLogger().printlnTranslation("s52"); continue; } } else { votifier.getLogger().printlnTranslation("s20"); continue; } votifier.getLogger().printlnTranslation("s16"); votifier.getConfig().genKeyPair(keySize); try { votifier.getConfig().save(); } catch (Exception e) { votifier.getLogger().printlnTranslation("s21", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } votifier.getLogger().printlnTranslation("s23"); } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) { String[] commandArgs = command.split(" "); if (commandArgs.length == 2) { try { votifier.getTester().testVote(new Vote("TesterService", commandArgs[1], votifier.getConfig().getInetSocketAddress().getAddress().getHostName())); } catch (Exception e) { // GeneralSecurityException, IOException votifier.getLogger().printlnTranslation("s27", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } } else { votifier.getLogger().printlnTranslation("s26"); } } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) { if (command.split(" ").length >= 2) { try { votifier.getTester() .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n")); } catch (Exception e) { // GeneralSecurityException, IOException votifier.getLogger().printlnTranslation("s35", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } } else { votifier.getLogger().printlnTranslation("s34"); } } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s31"); } else { votifier.getLogger().printlnTranslation("s32"); } } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s36"); } else { votifier.getLogger().printlnTranslation("s37"); } } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s40"); } else { votifier.getLogger().printlnTranslation("s41"); } } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s43"); } else { votifier.getLogger().printlnTranslation("s44"); } } else { votifier.getLogger().printlnTranslation("s33"); } } }
From source file:cc.osint.graphd.client.ProtographClient.java
public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: " + ProtographClient.class.getSimpleName() + " <host> <port>"); return;/*from w ww . j a va 2 s. c om*/ } String host = args[0]; int port = Integer.parseInt(args[1]); ProtographClient client = new ProtographClient(host, port); // Read commands from the stdin. ConsoleReader reader = new ConsoleReader(); for (;;) { String line = reader.readLine(); if (line == null) { break; } // Sends the received line to the server. //client.send(line + "\r\n"); List<JSONObject> results = client.exec(line.trim() + "\n"); if (null == results) { log.info("no result!"); } else { if (results.size() == 0) { log.info("OK"); } else { int c = 0; for (JSONObject result : results) { c++; log.info(c + ": " + result.toString(4)); } } } // If user typed the 'bye' command, wait until the server closes // the connection. if (line.toLowerCase().equals("bye")) { client.disconnect(); break; } } client.disconnect(); }