List of usage examples for java.lang StringBuilder toString
@Override
@HotSpotIntrinsicCandidate
public String toString()
From source file:com.cloudhopper.sxmp.PostUTF8MO.java
static public void main(String[] args) throws Exception { String URL = "https://sms-staging.twitter.com/receive/cloudhopper"; // this is a Euro currency symbol //String text = "\u20AC"; // shorter arabic //String text = "\u0623\u0647\u0644\u0627"; // even longer arabic //String text = "\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649"; String text = ""; for (int i = 0; i < 140; i++) { text += "\u0623"; }/*from w ww .ja v a 2 s .c om*/ String srcAddr = "+14159129228"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "23"; //text += " " + ticketId; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <ticketId>" + ticketId + "</ticketId>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"UTF-8\">" + HexUtil.toHexString(text.getBytes("UTF-8")) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:com.github.s4ke.moar.cli.Main.java
public static void main(String[] args) throws ParseException, IOException { // create Options object Options options = new Options(); options.addOption("rf", true, "file containing the regexes to test against (multiple regexes are separated by one empty line)"); options.addOption("r", true, "regex to test against"); options.addOption("mf", true, "file/folder to read the MOA from"); options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)"); options.addOption("sf", true, "file to read the input string(s) from"); options.addOption("s", true, "string to test the MOA/Regex against"); options.addOption("m", false, "multiline matching mode (search in string for regex)"); options.addOption("ls", false, "treat every line of the input string file as one string"); options.addOption("t", false, "trim lines if -ls is set"); options.addOption("d", false, "only do determinism check"); options.addOption("help", false, "prints this dialog"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("moar-cli", options); return;//from ww w . j a v a 2 s. c o m } List<String> patternNames = new ArrayList<>(); List<MoaPattern> patterns = new ArrayList<>(); List<String> stringsToCheck = new ArrayList<>(); if (cmd.hasOption("r")) { String regexStr = cmd.getOptionValue("r"); try { patterns.add(MoaPattern.compile(regexStr)); patternNames.add(regexStr); } catch (Exception e) { System.out.println(e.getMessage()); } } if (cmd.hasOption("rf")) { String fileName = cmd.getOptionValue("rf"); List<String> regexFileContents = readFileContents(new File(fileName)); int emptyLineCountAfterRegex = 0; StringBuilder regexStr = new StringBuilder(); for (String line : regexFileContents) { if (emptyLineCountAfterRegex >= 1) { if (regexStr.length() > 0) { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } regexStr.setLength(0); emptyLineCountAfterRegex = 0; } if (line.trim().equals("")) { if (regexStr.length() > 0) { ++emptyLineCountAfterRegex; } } else { regexStr.append(line); } } if (regexStr.length() > 0) { try { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } catch (Exception e) { System.out.println(e.getMessage()); return; } regexStr.setLength(0); } } if (cmd.hasOption("mf")) { String fileName = cmd.getOptionValue("mf"); File file = new File(fileName); if (file.isDirectory()) { System.out.println(fileName + " is a directory, using all *.moar files as patterns"); File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar")); for (File moar : moarFiles) { String jsonString = readWholeFile(moar); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(moar.getAbsolutePath()); } } else { System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)"); String jsonString = readWholeFile(file); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(fileName); } } if (cmd.hasOption("s")) { String str = cmd.getOptionValue("s"); stringsToCheck.add(str); } if (cmd.hasOption("sf")) { boolean treatLineAsString = cmd.hasOption("ls"); boolean trim = cmd.hasOption("t"); String fileName = cmd.getOptionValue("sf"); StringBuilder stringBuilder = new StringBuilder(); boolean firstLine = true; for (String str : readFileContents(new File(fileName))) { if (treatLineAsString) { if (trim) { str = str.trim(); if (str.length() == 0) { continue; } } stringsToCheck.add(str); } else { if (!firstLine) { stringBuilder.append("\n"); } if (firstLine) { firstLine = false; } stringBuilder.append(str); } } if (!treatLineAsString) { stringsToCheck.add(stringBuilder.toString()); } } if (cmd.hasOption("d")) { //at this point we have already built the Patterns //so just give the user a short note. System.out.println("All Regexes seem to be deterministic."); return; } if (patterns.size() == 0) { System.out.println("no patterns to check"); return; } if (cmd.hasOption("mo")) { String folder = cmd.getOptionValue("mo"); File folderFile = new File(folder); if (!folderFile.exists()) { System.out.println(folder + " does not exist. creating..."); if (!folderFile.mkdirs()) { System.out.println("folder " + folder + " could not be created"); } } int cnt = 0; for (MoaPattern pattern : patterns) { String patternAsJSON = MoarJSONSerializer.toJSON(pattern); try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) { writer.write(patternAsJSON); } } System.out.println("stored " + cnt + " patterns in " + folder); } if (stringsToCheck.size() == 0) { System.out.println("no strings to check"); return; } boolean multiline = cmd.hasOption("m"); for (String string : stringsToCheck) { int curPattern = 0; for (MoaPattern pattern : patterns) { MoaMatcher matcher = pattern.matcher(string); if (!multiline) { if (matcher.matches()) { System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\""); } else { System.out.println( "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\""); } } else { StringBuilder buffer = new StringBuilder(string); int additionalCharsPerMatch = ("<match>" + "</match>").length(); int matchCount = 0; while (matcher.nextMatch()) { buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch, matcher.getEnd() + matchCount * additionalCharsPerMatch, "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>"); ++matchCount; } System.out.println(buffer.toString()); } } ++curPattern; } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageReaderMongoServiceTestClient client = new StorageReaderMongoServiceTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_READER_SERVICE_URL = "http://192.168.84.34:8080/storage-reader"; String QUERY_SIMPLE_SENSORID = "1000692"; String QUERY_SIMPLE_STARTTIME = "1387565891068"; String QUERY_SIMPLE_ENDTIME = "1387565996633"; String QUERY_SIMPLE_PROPERTYKEY = "value"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;/*from w ww . j a v a 2s.co m*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.DEFAULT: " + body); // The result is an array of simple events serialized as JSON using Apache Thrift. // The simple events can be deserialized into Java objects using Apache Thrift. ObjectMapper mapper = new ObjectMapper(); JsonNode nodeArray = mapper.readTree(body); for (JsonNode node : nodeArray) { byte[] bytes = node.toString().getBytes(); TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); SimpleEvent event = new SimpleEvent(); deserializer.deserialize(event, bytes); System.out.println(event.toString()); } } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/average"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Get status code status = response.getStatusLine().getStatusCode(); if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.AVERAGE: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/maximum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query13 = new HttpGet(requestUrl.toString()); query13.setHeader("Content-type", "application/json"); response = client.execute(query13); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MAXIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/minimum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query14 = new HttpGet(requestUrl.toString()); query14.setHeader("Content-type", "application/json"); response = client.execute(query14); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MINIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java
public static void main(String[] args) { // Get benchmark properties StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark(); benchmark.loadClientProperties();/*w ww . j av a2 s . c o m*/ // ProaSense Storage Reader Service configuration properties String STORAGE_READER_SERVICE_URL = benchmark.clientProperties .getProperty("proasense.storage.reader.service.url"); String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.collectionid"); String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.starttime"); String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.endtime"); String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.collectionid"); String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.starttime"); String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.endtime"); String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.collectionid"); String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.starttime"); String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.endtime"); String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.collectionid"); String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.starttime"); String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.endtime"); String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.collectionid"); String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.starttime"); String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.endtime"); String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.collectionid"); String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.starttime"); String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.endtime"); String propertyKey = "value"; // Default HTTP client and common property variables for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null; StatusLine status = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); try { status = client.execute(query11).getStatusLine(); System.out.println("SIMPLE.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/value"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", "value")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL); query12.setHeader("Content-type", "application/json"); try { status = client.execute(query12).getStatusLine(); System.out.println("SIMPLE.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL); query13.setHeader("Content-type", "application/json"); try { status = client.execute(query13).getStatusLine(); System.out.println("SIMPLE.MAXIMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL); query14.setHeader("Content-type", "application/json"); try { status = client.execute(query14).getStatusLine(); System.out.println("SIMPLE.MINUMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for derived events HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL); query21.setHeader("Content-type", "application/json"); try { status = client.execute(query21).getStatusLine(); System.out.println("DERIVED.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for derived events HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL); query22.setHeader("Content-type", "application/json"); try { status = client.execute(query22).getStatusLine(); System.out.println("DERIVED.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL); query23.setHeader("Content-type", "application/json"); try { status = client.execute(query23).getStatusLine(); System.out.println("DERIVED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL); query24.setHeader("Content-type", "application/json"); try { status = client.execute(query24).getStatusLine(); System.out.println("DERIVED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for predicted events HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL); query31.setHeader("Content-type", "application/json"); try { status = client.execute(query31).getStatusLine(); System.out.println("PREDICTED.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for predicted events HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL); query32.setHeader("Content-type", "application/json"); try { status = client.execute(query32).getStatusLine(); System.out.println("PREDICTED.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for predicted events HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL); query33.setHeader("Content-type", "application/json"); try { status = client.execute(query33).getStatusLine(); System.out.println("PREDICTED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL); query34.setHeader("Content-type", "application/json"); try { status = client.execute(query34).getStatusLine(); System.out.println("PREDICTED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for anomaly events HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL); query41.setHeader("Content-type", "application/json"); try { status = client.execute(query41).getStatusLine(); System.out.println("ANOMALY.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for recommendation events HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL); query51.setHeader("Content-type", "application/json"); try { status = client.execute(query51).getStatusLine(); System.out.println("RECOMMENDATION.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for recommendation events HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL); query52.setHeader("Content-type", "application/json"); try { status = client.execute(query52).getStatusLine(); System.out.println("RECOMMENDATION.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL); query53.setHeader("Content-type", "application/json"); try { status = client.execute(query53).getStatusLine(); System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("RECOMMENDATION.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for feedback events HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("FEEDBACK.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:tuit.java
@SuppressWarnings("ConstantConditions") public static void main(String[] args) { System.out.println(licence);//from ww w. j a va 2 s . c o m //Declare variables File inputFile; File outputFile; File tmpDir; File blastnExecutable; File properties; File blastOutputFile = null; // TUITPropertiesLoader tuitPropertiesLoader; TUITProperties tuitProperties; // String[] parameters = null; // Connection connection = null; MySQL_Connector mySQL_connector; // Map<Ranks, TUITCutoffSet> cutoffMap; // BLASTIdentifier blastIdentifier = null; // RamDb ramDb = null; CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)"); options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)"); options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)"); options.addOption(tuit.V, "verbose", false, "Enable verbose output"); options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output"); options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases"); options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases"); options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy"); Option option = new Option(tuit.REDUCE, "reduce", true, "Pack identical (100% similar sequences) records in the given sample file"); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); option = new Option(tuit.COMBINE, "combine", true, "Combine a set of given reduction files into an HMP Tree-compatible taxonomy"); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); options.addOption(tuit.NORMALIZE, "normalize", false, "If used in combination with -combine ensures that the values are normalized by the root value"); HelpFormatter formatter = new HelpFormatter(); try { //Get TUIT directory final File tuitDir = new File( new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) .getParent()); final File ramDbFile = new File(tuitDir, tuit.RAM_DB); //Setup logger Log.getInstance().setLogName("tuit.log"); //Read command line final CommandLine commandLine = parser.parse(options, args, true); //Check if the REDUCE option is on if (commandLine.hasOption(tuit.REDUCE)) { final String[] fileList = commandLine.getOptionValues(tuit.REDUCE); for (String s : fileList) { final Path path = Paths.get(s); Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "..."); final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor .fromPath(path); ReductorFileOperator.save(nucleotideFastaSequenceReductor, path.resolveSibling(path.getFileName().toString() + ".rdc")); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Check if COMBINE is on if (commandLine.hasOption(tuit.COMBINE)) { final boolean normalize = commandLine.hasOption(tuit.NORMALIZE); final String[] fileList = commandLine.getOptionValues(tuit.COMBINE); //TODO: implement a test for format here final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>(); final TreeFormatter treeFormatter = TreeFormatter .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat()); for (String s : fileList) { final Path path = Paths.get(s); Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "..."); treeFormatter.loadFromPath(path); final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf("."))); hmpTreesOutputs.add(output); treeFormatter.erase(); } final Path destination; if (commandLine.hasOption(OUT)) { destination = Paths.get(commandLine.getOptionValue(tuit.OUT)); } else { destination = Paths.get("merge.tcf"); } CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination); Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } if (!commandLine.hasOption(tuit.P)) { throw new ParseException("No properties file option found, exiting."); } else { properties = new File(commandLine.getOptionValue(tuit.P)); } //Load properties tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties); tuitProperties = tuitPropertiesLoader.getTuitProperties(); //Create tmp directory and blastn executable tmpDir = new File(tuitProperties.getTMPDir().getPath()); blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath()); //Check for deploy if (commandLine.hasOption(tuit.DEPLOY)) { if (commandLine.hasOption(tuit.USE_DB)) { NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir); } else { NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Check for update if (commandLine.hasOption(tuit.UPDATE)) { if (commandLine.hasOption(tuit.USE_DB)) { NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir); } else { //No need to specify a different way to update the database other than just deploy in case of the RAM database NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Connect to the database if (commandLine.hasOption(tuit.USE_DB)) { mySQL_connector = MySQL_Connector.newDefaultInstance( "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/", tuitProperties.getDBConnection().getLogin().trim(), tuitProperties.getDBConnection().getPassword().trim()); mySQL_connector.connectToDatabase(); connection = mySQL_connector.getConnection(); } else { //Probe for ram database if (ramDbFile.exists() && ramDbFile.canRead()) { Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map..."); try { ramDb = RamDb.loadSelfFromFile(ramDbFile); } catch (IOException ie) { if (ie instanceof java.io.InvalidClassException) throw new IOException("The RAM-based taxonomic database needs to be updated."); } } else { Log.getInstance().log(Level.SEVERE, "The RAM database either has not been deployed, or is not accessible." + "Please use the --deploy option and check permissions on the TUIT directory. " + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option."); return; } } if (commandLine.hasOption(tuit.B)) { blastOutputFile = new File(commandLine.getOptionValue(tuit.B)); if (!blastOutputFile.exists() || !blastOutputFile.canRead()) { throw new Exception("BLAST output file either does not exist, or is not readable."); } else if (blastOutputFile.isDirectory()) { throw new Exception("BLAST output file points to a directory."); } } //Check vital parameters if (!commandLine.hasOption(tuit.IN)) { throw new ParseException("No input file option found, exiting."); } else { inputFile = new File(commandLine.getOptionValue(tuit.IN)); Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log"); } //Correct the output file option if needed if (!commandLine.hasOption(tuit.OUT)) { outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT); } else { outputFile = new File(commandLine.getOptionValue(tuit.OUT)); } //Adjust the output level if (commandLine.hasOption(tuit.V)) { Log.getInstance().setLevel(Level.FINE); Log.getInstance().log(Level.INFO, "Using verbose output for the log"); } else { Log.getInstance().setLevel(Level.INFO); } //Try all files if (inputFile != null) { if (!inputFile.exists() || !inputFile.canRead()) { throw new Exception("Input file either does not exist, or is not readable."); } else if (inputFile.isDirectory()) { throw new Exception("Input file points to a directory."); } } if (!properties.exists() || !properties.canRead()) { throw new Exception("Properties file either does not exist, or is not readable."); } else if (properties.isDirectory()) { throw new Exception("Properties file points to a directory."); } //Create blast parameters final StringBuilder stringBuilder = new StringBuilder(); for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) { stringBuilder.append(database.getUse()); stringBuilder.append(" ");//Gonna insert an extra space for the last database } String remote; String entrez_query; if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) { remote = "-remote"; entrez_query = "-entrez_query"; parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue() }; } else { if (!commandLine.hasOption(tuit.B)) { if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .startsWith("NOT") || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .startsWith("ALL")) { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist", TUITFileOperatorHelper.restrictToEntrez(tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue() .toUpperCase().replace("NOT", "OR")) .getAbsolutePath(), "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .equals("")) { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } else { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), /*"-gilist", TUITFileOperatorHelper.restrictToEntrez( tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!! "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } } } //Prepare a cutoff Map if (tuitProperties.getSpecificationParameters() != null && tuitProperties.getSpecificationParameters().size() > 0) { cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size()); for (SpecificationParameters specificationParameters : tuitProperties .getSpecificationParameters()) { cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()), TUITCutoffSet.newDefaultInstance( Double.parseDouble( specificationParameters.getCutoffSet().getPIdentCutoff().getValue()), Double.parseDouble(specificationParameters.getCutoffSet() .getQueryCoverageCutoff().getValue()), Double.parseDouble( specificationParameters.getCutoffSet().getAlpha().getValue()))); } } else { cutoffMap = new HashMap<Ranks, TUITCutoffSet>(); } final TUITFileOperatorHelper.OutputFormat format; if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) { format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK; } else { format = TUITFileOperatorHelper.OutputFormat.TUIT; } try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator .newInstance(format, cutoffMap);) { nucleotideFastaTUITFileOperator.setInputFile(inputFile); nucleotideFastaTUITFileOperator.setOutputFile(outputFile); final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep(); final boolean cleanup; if (cleanupString.equals("no")) { Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted."); cleanup = true; } else { Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept."); cleanup = false; } //Create blast identifier ExecutorService executorService = Executors.newSingleThreadExecutor(); if (commandLine.hasOption(tuit.USE_DB)) { if (blastOutputFile == null) { blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir, blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection, cutoffMap, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup); } else { try { blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput( nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup); } catch (JAXBException e) { Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName() + ", please check input. The file must be XML formatted."); } catch (Exception e) { e.printStackTrace(); } } } else { if (blastOutputFile == null) { blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir, blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup, ramDb); } else { try { blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput( nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup, ramDb); } catch (JAXBException e) { Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName() + ", please check input. The file must be XML formatted."); } catch (Exception e) { e.printStackTrace(); } } } Future<?> runnableFuture = executorService.submit(blastIdentifier); runnableFuture.get(); executorService.shutdown(); } } catch (ParseException pe) { Log.getInstance().log(Level.SEVERE, (pe.getMessage())); formatter.printHelp("tuit", options); } catch (SAXException saxe) { Log.getInstance().log(Level.SEVERE, saxe.getMessage()); } catch (FileNotFoundException fnfe) { Log.getInstance().log(Level.SEVERE, fnfe.getMessage()); } catch (TUITPropertyBadFormatException tpbfe) { Log.getInstance().log(Level.SEVERE, tpbfe.getMessage()); } catch (ClassCastException cce) { Log.getInstance().log(Level.SEVERE, cce.getMessage()); } catch (JAXBException jaxbee) { Log.getInstance().log(Level.SEVERE, "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema."); } catch (ClassNotFoundException cnfe) { //Probably won't happen unless the library deleted from the .jar Log.getInstance().log(Level.SEVERE, cnfe.getMessage()); //cnfe.printStackTrace(); } catch (SQLException sqle) { Log.getInstance().log(Level.SEVERE, "A database communication error occurred with the following message:\n" + sqle.getMessage()); //sqle.printStackTrace(); if (sqle.getMessage().contains("Access denied for user")) { Log.getInstance().log(Level.SEVERE, "Please use standard database login: " + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password); } } catch (Exception e) { Log.getInstance().log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException sqle) { Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle); } } Log.getInstance().log(Level.FINE, "Task done, exiting..."); } }
From source file:de.uniko.west.winter.test.basics.JenaTests.java
public static void main(String[] args) { Model newModel = ModelFactory.createDefaultModel(); // /* w w w. j a v a2s .c om*/ Model newModel2 = ModelFactory.createModelForGraph(ModelFactory.createMemModelMaker().getGraphMaker() .createGraph("http://www.defaultgraph.de/graph1")); StringBuilder updateString = new StringBuilder(); updateString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); updateString.append("PREFIX xsd: <http://bla.org/dc/elements/1.1/>"); updateString.append("INSERT { "); updateString.append( "<http://example/egbook1> dc:title <http://example/egbook1/#Title1>, <http://example/egbook1/#Title2>. "); //updateString.append("<http://example/egbook1> dc:title \"Title1.1\". "); //updateString.append("<http://example/egbook1> dc:title \"Title1.2\". "); updateString.append("<http://example/egbook21> dc:title \"Title2\"; "); updateString.append("dc:title \"2.0\"^^xsd:double. "); updateString.append("<http://example/egbook3> dc:title \"Title3\". "); updateString.append("<http://example/egbook4> dc:title \"Title4\". "); updateString.append("<http://example/egbook5> dc:title \"Title5\". "); updateString.append("<http://example/egbook6> dc:title \"Title6\" "); updateString.append("}"); UpdateRequest update = UpdateFactory.create(updateString.toString()); UpdateAction.execute(update, newModel); StmtIterator iter = newModel.listStatements(); System.out.println("After add"); while (iter.hasNext()) { System.out.println(iter.next().toString()); } StringBuilder constructQueryString = new StringBuilder(); constructQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); constructQueryString.append("CONSTRUCT {?sub dc:title <http://example/egbook1/#Title1>}"); constructQueryString.append("WHERE {"); constructQueryString.append("?sub dc:title <http://example/egbook1/#Title1>"); constructQueryString.append("}"); StringBuilder askQueryString = new StringBuilder(); askQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); askQueryString.append("ASK {"); askQueryString.append("?sub dc:title <http://example/egbook1/#Title1>"); askQueryString.append("}"); StringBuilder selectQueryString = new StringBuilder(); selectQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); selectQueryString.append("SELECT * "); selectQueryString.append("WHERE {"); selectQueryString.append("?sub ?pred ?obj"); selectQueryString.append("}"); Query cquery = QueryFactory.create(constructQueryString.toString()); System.out.println(cquery.getQueryType()); Query aquery = QueryFactory.create(askQueryString.toString()); System.out.println(aquery.getQueryType()); Query query = QueryFactory.create(selectQueryString.toString()); System.out.println(query.getQueryType()); QueryExecution queryExecution = QueryExecutionFactory.create(query, newModel); ByteArrayOutputStream baos = new ByteArrayOutputStream(); URI test = null; try { test = new URI("http://bla.org/dc/elements/1.1/double"); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1)); System.out.println("java.lang." + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(0, 1) .toUpperCase() + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(1)); String typ = "java.lang.Boolean"; String val = "true"; try { Object typedLiteral = Class.forName(typ, true, ClassLoader.getSystemClassLoader()) .getConstructor(String.class).newInstance(val); System.out.println("Type: " + typedLiteral.getClass().getName() + " Value: " + typedLiteral); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { System.out.println("Query..."); com.hp.hpl.jena.query.ResultSet results = queryExecution.execSelect(); System.out.println("RESULT:"); ResultSetFormatter.output(System.out, results, ResultSetFormat.syntaxJSON); // // // ResultSetFormatter.outputAsJSON(baos, results); // System.out.println(baos.toString()); // System.out.println("JsonTest: "); // JSONObject result = new JSONObject(baos.toString("ISO-8859-1")); // for (Iterator key = result.keys(); result.keys().hasNext(); ){ // System.out.println(key.next()); // // for (Iterator key2 = ((JSONObject)result.getJSONObject("head")).keys(); key2.hasNext(); ){ // System.out.println(key2.next()); // } // } // Model results = queryExecution.execConstruct(); // results.write(System.out, "TURTLE"); // for ( ; results.hasNext() ; ){ // QuerySolution soln = results.nextSolution() ; // RDFNode x = soln.get("sub") ; // System.out.println("result: "+soln.get("sub")+" hasTitle "+soln.get("obj")); // Resource r = soln.getResource("VarR") ; // Literal l = soln.getLiteral("VarL") ; // // } } catch (Exception e) { // TODO: handle exception } // StringBuilder updateString2 = new StringBuilder(); // updateString2.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); // updateString2.append("DELETE DATA { "); // updateString2.append("<http://example/egbook3> dc:title \"Title3\" "); // updateString2.append("}"); // // UpdateAction.parseExecute(updateString2.toString(), newModel); // // iter = newModel.listStatements(); // System.out.println("After delete"); // while (iter.hasNext()) { // System.out.println(iter.next().toString()); // // } // // StringBuilder updateString3 = new StringBuilder(); // updateString3.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); // updateString3.append("DELETE DATA { "); // updateString3.append("<http://example/egbook6> dc:title \"Title6\" "); // updateString3.append("}"); // updateString3.append("INSERT { "); // updateString3.append("<http://example/egbook6> dc:title \"New Title6\" "); // updateString3.append("}"); // // UpdateAction.parseExecute(updateString3.toString(), newModel); // UpdateAction.parseExecute( "prefix exp: <http://www.example.de>"+ // "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+ // "INSERT { graph <http://www.defaultgraph.de/graph1> {"+ // " <http://www.test.de#substructure1> <exp:has_relation3> <http://www.test.de#substructure2> ."+ // " <http://www.test.de#substructure1> <rdf:type> <http://www.test.de#substructuretype1> ."+ // " <http://www.test.de#substructure2> <rdf:type> <http://www.test.de#substructuretype2> ."+ // "}}", newModel2); // // iter = newModel.listStatements(); // System.out.println("After update"); // while (iter.hasNext()) { // System.out.println(iter.next().toString()); // // } }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();// ww w. j av a2s .c om //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:com.zimbra.common.calendar.ZoneInfo2iCalendar.java
public static void main(String[] args) throws Exception { // command line handling CommandLine cl = null;/*from w ww. j ava 2s . co m*/ Params params = null; try { cl = parseArgs(args); if (cl.hasOption(OPT_HELP)) { usage(null); System.exit(0); } params = initParams(cl); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } // parse tzdata source ZoneInfoParser parser = new ZoneInfoParser(); for (File tzdataFile : params.tzdataFiles) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(tzdataFile), "UTF-8"); parser.readTzdata(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + tzdataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } parser.analyze(); // read extra data file containing primary TZ list and zone match scores if (params.extraDataFile != null) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(params.extraDataFile), "UTF-8"); readExtraData(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + params.extraDataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } Writer out; if (params.outputFile != null) { out = new PrintWriter(params.outputFile, "UTF-8"); } else { out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } try { StringBuilder hdr = new StringBuilder("BEGIN:VCALENDAR"); hdr.append(CRLF); hdr.append("PRODID:Zimbra-Calendar-Provider").append(CRLF); hdr.append("VERSION:2.0").append(CRLF); hdr.append("METHOD:PUBLISH").append(CRLF); out.write(hdr.toString()); Map<String, VTimeZone> oldTimeZones = makeOldTimeZonesMap(params); Set<Zone> zones = new TreeSet<Zone>(new ZoneComparatorByGmtOffset()); zones.addAll(parser.getZones()); Set<String> zoneIDs = new TreeSet<String>(); for (Zone zone : zones) { zoneIDs.add(zone.getName()); } for (Zone zone : zones) { out.write(getTimeZoneForZone(zone, params, zoneIDs, oldTimeZones)); } StringBuilder footer = new StringBuilder("END:VCALENDAR"); footer.append(CRLF); out.write(footer.toString()); } finally { out.close(); } }
From source file:com.berrysys.ussdgw.Starter.java
/** * The main method./* www .j a v a 2 s. c o m*/ * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { StringBuilder banner = new StringBuilder(); banner.append("\n").append(" ____ ____ \n") .append(" | __ ) ___ _ __ _ __ _ _/ ___| _ _ ___ \n") .append(" | _ \\ / _ \\ '__| '__| | | \\___ \\| | | / __|\n") .append(" | |_) | __/ | | | | |_| |___) | |_| \\__ \\\n") .append(" |____/ \\___|_| _|_| \\__, |____/ \\__, |___/\n") .append(" / ___|(_) __ _| |_ _ _|___/_ _ __ |___/ \n") .append(" \\___ \\| |/ _` | __| '__/ _` | '_ \\ \n") .append(" ___) | | (_| | |_| | | (_| | | | | \n") .append(" |____/|_|\\__, |\\__|_| \\__,_|_| |_| \n") .append(" _ _ __|___/__ ____ \n") .append(" | | | / ___/ ___|| _ \\ \n") .append(" | | | \\___ \\___ \\| | | | \n") .append(" | |_| |___) |__) | |_| | \n") .append(" \\___/|____/____/|____/ \n") .append(" / ___| __ _| |_ _____ ____ _ _ _ \n") .append(" | | _ / _` | __/ _ \\ \\ /\\ / / _` | | | | \n") .append(" | |_| | (_| | || __/\\ V V / (_| | |_| | \n") .append(" \\____|\\__,_|\\__\\___| \\_/\\_/ \\__,_|\\__, |\n") .append(" |___/ \n"); String berrysysUssdGW = banner.toString(); log.info(berrysysUssdGW); ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/app-context.xml"); List<DialogListener> serverList = (List<DialogListener>) applicationContext.getBean("sctpServerList"); Iterator<DialogListener> i = serverList.iterator(); while (i.hasNext()) { final DialogListener dialogListenerItem = i.next(); DialogListenerThread dialogListenerThread = new DialogListenerThread(); dialogListenerThread.setDialogListener(dialogListenerItem); dialogListenerThread.start(); ThreadHolder.getInstance().getDialogListenerThreadList().add(dialogListenerThread); } Iterator<DialogListenerThread> j = ThreadHolder.getInstance().getDialogListenerThreadList().iterator(); while (j.hasNext()) { try { j.next().join(); } catch (InterruptedException e) { log.catching(e); } } }
From source file:com.mijecu25.sqlplus.SQLPlus.java
public static void main(String[] args) throws IOException { // Create and load the properties from the application properties file Properties properties = new Properties(); properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE)); SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); // Check if the user is using a valid console (i.e. not from Eclipse) if (System.console() == null) { // The Console object for the JVM could not be found. Alert the user SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running " + SQLPlus.PROGRAM_NAME + "from the command line"); System.out.println(/*w w w. j a va2s .co m*/ Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. " + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line."); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME)); return; } // UI intro System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME + "! This program has a DSL to add alerts to various SQL DML events."); System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line."); System.out.println(); // Get the version System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); System.out.println(); // Read the license file BufferedReader bufferedReader; bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE)); // Read a line String line = bufferedReader.readLine(); // While the line is not null while (line != null) { System.out.println(line); // Read a new lines line = bufferedReader.readLine(); } // Close the buffer bufferedReader.close(); System.out.println(); // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions // from the user SQLPlus.console = new ConsoleReader(); SQLPlus.console.setHandleUserInterrupt(true); try { // Get credentials from the user SQLPlus.logger.info("Create SQLPlusConnection"); SQLPlus.createSQLPlusConnection(); } catch (NullPointerException | SQLException | IllegalArgumentException e) { // NPE: This exception can occur if the user is running the program where the JVM Console // object cannot be found. // SQLE: TODO should I add here the error code? // This exception can occur when trying to establish a connection // IAE: This exception can occur when trying to establish a connection SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName())); System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); return; } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); return; } System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND); System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application "); try { // Execute the input scanner while (true) { // Get a line from the user until the hit enter (carriage return, line feed/ new line). System.out.print(SQLPlus.PROMPT); try { line = SQLPlus.console.readLine().trim(); } catch (NullPointerException npe) { // TODO test this behavior // If this exception is catch, it is very likely that the user entered the end of line command. // This means that the program should quit. SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that" + "the user entered the end of line command and they want to quit."); SQLPlus.exitSQLPlus(); return; } // If the user did not enter anything if (line.isEmpty()) { // Continue to the next iteration continue; } if (line.equals(".")) { line = "use courses;"; } if (line.equals("-")) { line = "select created_at from classes;"; } if (line.equals("--")) { line = "select name, year from classes;"; } if (line.equals("*")) { line = "select * from classes;"; } if (line.equals("x")) { line = "select name from classes, classes;"; } if (line.equals("e")) { line = "select * feom classes;"; } // Logic to quit if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) { SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME); SQLPlus.exitSQLPlus(); break; } // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each // time jline reads a new line, the variable is empty StringBuilder query = new StringBuilder(); query.append(line); // While the user does not finish the command with the SQLPlus.END_OF_COMMAND while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) { // Print the wait for command prompt and get the next line for the user System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND); query.append(" "); line = StringUtils.stripEnd(SQLPlus.console.readLine(), null); query.append(line); } SQLPlus.logger.info("Raw input from the user: " + query); try { Statement statement; try { // Execute the antlr code to parse the user input SQLPlus.logger.info("Will parse the user input to determine what to execute"); ANTLRStringStream input = new ANTLRStringStream(query.toString()); SQLPlusLex lexer = new SQLPlusLex(input); CommonTokenStream tokens = new CommonTokenStream(lexer); SQLPlusParser parser = new SQLPlusParser(tokens); statement = parser.sqlplus(); } catch (RecognitionException re) { // TODO move this to somehwere else // String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual" // + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase() // + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax"; // SQLPlus.logger.warn(message); // System.out.println(message); statement = new StatementDefault(); } statement.setStatement(query.toString()); SQLPlus.sqlPlusConnection.execute(statement); } catch (UnsupportedOperationException uoe) { // This exception can occur when the user entered a command allowed by the parsers, but not currently // supported by SQLPlus. This can occur because the parser is written in such a way that supports // the addition of features. SQLPlus.logger.warn(Messages.WARNING + uoe); System.out.println( Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported."); } } } catch (IllegalArgumentException iae) { // This exception can occur when a command is executed but it had illegal arguments. Most likely // it is a programmer's error and should be addressed by the developer. SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName())); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); } }