List of usage examples for java.lang StringBuilder StringBuilder
public StringBuilder(CharSequence seq)
From source file:net.modelbased.proasense.storage.registry.StorageRegistrySensorDataTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistrySensorDataTestClient client = new StorageRegistrySensorDataTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;/* w w w . ja v a 2s . c om*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for sensor list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/list"); try { HttpGet query21 = new HttpGet(requestUrl.toString()); query21.setHeader("Content-type", "application/json"); response = client.execute(query21); // 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("SENSOR LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", "visualInspection")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // 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("SENSOR PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:net.modelbased.proasense.storage.registry.StorageRegistryScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistryScrapRateTestClient client = new StorageRegistryScrapRateTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;/*from w w w .j a va2 s . co m*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for machine list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); 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("MACHINE LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for machine properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("machineId", "IMM1")); 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); // 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("MACHINE PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/list"); try { HttpGet query21 = new HttpGet(requestUrl.toString()); query21.setHeader("Content-type", "application/json"); response = client.execute(query21); // 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("SENSOR LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", "dustParticleSensor")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // 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("SENSOR PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/list"); try { HttpGet query31 = new HttpGet(requestUrl.toString()); query31.setHeader("Content-type", "application/json"); response = client.execute(query31); // 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("PRODUCT LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // 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("PRODUCT PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/mould/list"); try { HttpGet query41 = new HttpGet(requestUrl.toString()); query41.setHeader("Content-type", "application/json"); response = client.execute(query41); // 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("MOULD LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query42 = new HttpGet(requestUrl.toString()); query42.setHeader("Content-type", "application/json"); response = client.execute(query42); // 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("MOULD PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
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;//w w w.j av a 2 s . 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:com.genentech.struchk.sdfNormalizer.java
public static void main(String[] args) { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);/*from w w w .ja v a 2 s . c o m*/ options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC"); opt.setRequired(false); options.addOption(opt); opt = new Option("shortMessage", false, "Limit message to first 80 characters to conform with sdf file specs."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithHelp(options, e.getMessage()); throw new Error(e); // avoid compiler errors } args = cmd.getArgs(); if (args.length != 0) { System.err.print("Unknown options: " + args + "\n\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdfNormalizer", options); System.exit(1); } String molOpt = cmd.getOptionValue("mol"); OUTMolFormat outMol = OUTMolFormat.ORIGINAL; if (molOpt == null || "original".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.ORIGINAL; else if ("NORMALIZED".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.NORMALIZED; else if ("TAUTOMERIC".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.TAUTOMERIC; else { System.err.printf("Unkown option for -mol: %s\n", molOpt); System.exit(1); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); boolean limitMessage = cmd.hasOption("shortMessage"); try { oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml"); // create OEStruchk from config file OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false); OEGraphMol mol = new OEGraphMol(); StringBuilder sb = new StringBuilder(2000); while (oechem.OEReadMolecule(ifs, mol)) { if (!strchk.applyRules(mol, null)) nErrors++; switch (outMol) { case NORMALIZED: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol("parent")); break; case TAUTOMERIC: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol(null)); break; case ORIGINAL: break; } oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null)); oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null)); oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent")); oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName()); List<Message> msgs = strchk.getStructureMessages(null); nMessages += msgs.size(); for (Message msg : msgs) sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText())); if (limitMessage) sb.setLength(Math.min(sb.length(), 80)); oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString()); oechem.OEWriteMolecule(ofs, mol); sb.setLength(0); nStruct++; } strchk.delete(); mol.delete(); ifs.close(); ifs.delete(); ofs.close(); ofs.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); } }
From source file:org.eclipse.swt.snippets.Snippet338.java
public static void main(String[] args) { Display display = new Display(); Shell parentShell = new Shell(display); parentShell.setText("Snippet 338"); parentShell.setBounds(10, 10, 100, 100); parentShell.open();/*ww w . ja v a 2 s . c om*/ Shell childShell = new Shell(parentShell); childShell.setLayout(new GridLayout()); TabFolder folder = new TabFolder(childShell, SWT.NONE); folder.setLayout(new FillLayout()); TabItem tab1 = new TabItem(folder, SWT.NONE); tab1.setText("Tab &1"); new TabItem(folder, SWT.NONE).setText("Tab &2"); Composite composite = new Composite(folder, SWT.NONE); composite.setLayout(new GridLayout()); tab1.setControl(composite); Text text1 = new Text(composite, SWT.SINGLE); /* canvas represents a custom control */ final Canvas canvas = new Canvas(composite, SWT.BORDER); canvas.setLayoutData(new GridData(300, 200)); canvas.addListener(SWT.Paint, event -> { if (canvas.isFocusControl()) { event.gc.drawText( "focus is here, custom traverse keys:\n\tN: Tab next\n\tP: Tab previous\n\tR: Return\n\tE: Esc\n\tT: Tab Folder next page", 0, 0); } else { event.gc.drawString("focus is not in this control", 0, 0); } }); canvas.addListener(SWT.KeyDown, event -> { int traversal = SWT.NONE; switch (event.keyCode) { case 'n': traversal = SWT.TRAVERSE_TAB_NEXT; break; case 'p': traversal = SWT.TRAVERSE_TAB_PREVIOUS; break; case 'r': traversal = SWT.TRAVERSE_RETURN; break; case 'e': traversal = SWT.TRAVERSE_ESCAPE; break; case 't': traversal = SWT.TRAVERSE_PAGE_NEXT; break; } if (traversal != SWT.NONE) { event.doit = true; /* this will be the Traverse event's initial doit value */ canvas.traverse(traversal, event); } }); canvas.addFocusListener(focusLostAdapter(e -> canvas.redraw())); canvas.addFocusListener(focusGainedAdapter(e -> canvas.redraw())); Text text2 = new Text(composite, SWT.SINGLE); Button button = new Button(childShell, SWT.PUSH); button.setText("Default &Button"); button.addListener(SWT.Selection, event -> System.out.println("Default button selected")); childShell.setDefaultButton(button); Listener printTraverseListener = event -> { StringBuilder buffer = new StringBuilder("Traverse "); buffer.append(event.widget); buffer.append(" type="); switch (event.detail) { case SWT.TRAVERSE_ARROW_NEXT: buffer.append("TRAVERSE_ARROW_NEXT"); break; case SWT.TRAVERSE_ARROW_PREVIOUS: buffer.append("TRAVERSE_ARROW_NEXT"); break; case SWT.TRAVERSE_ESCAPE: buffer.append("TRAVERSE_ESCAPE"); break; case SWT.TRAVERSE_MNEMONIC: buffer.append("TRAVERSE_MNEMONIC"); break; case SWT.TRAVERSE_PAGE_NEXT: buffer.append("TRAVERSE_PAGE_NEXT"); break; case SWT.TRAVERSE_PAGE_PREVIOUS: buffer.append("TRAVERSE_PAGE_PREVIOUS"); break; case SWT.TRAVERSE_RETURN: buffer.append("TRAVERSE_RETURN"); break; case SWT.TRAVERSE_TAB_NEXT: buffer.append("TRAVERSE_TAB_NEXT"); break; case SWT.TRAVERSE_TAB_PREVIOUS: buffer.append("TRAVERSE_TAB_PREVIOUS"); break; } buffer.append(" doit=" + event.doit); buffer.append(" keycode=" + event.keyCode); buffer.append(" char=" + event.character); buffer.append(" stateMask=" + event.stateMask); System.out.println(buffer.toString()); }; childShell.addListener(SWT.Traverse, printTraverseListener); folder.addListener(SWT.Traverse, printTraverseListener); composite.addListener(SWT.Traverse, printTraverseListener); canvas.addListener(SWT.Traverse, printTraverseListener); button.addListener(SWT.Traverse, printTraverseListener); text1.addListener(SWT.Traverse, printTraverseListener); text2.addListener(SWT.Traverse, printTraverseListener); childShell.pack(); childShell.open(); text1.setFocus(); while (!parentShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:com.genentech.retrival.tabExport.TABExporter.java
public static void main(String[] args) throws ParseException, JDOMException, IOException { long start = System.currentTimeMillis(); int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("sqlFile", true, "sql-xml file"); opt.setRequired(true);//from w w w . j av a 2 s . c om options.addOption(opt); opt = new Option("sqlName", true, "name of SQL element in xml file"); opt.setRequired(true); options.addOption(opt); opt = new Option("o", true, "output file"); opt.setRequired(false); options.addOption(opt); opt = new Option("newLineReplacement", true, "If given newlines in fields will be replaced by this string."); options.addOption(opt); opt = new Option("noHeader", false, "Do not output header line"); options.addOption(opt); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); String outFile = cmd.getOptionValue("o"); String sqlFile = cmd.getOptionValue("sqlFile"); String sqlName = cmd.getOptionValue("sqlName"); String newLineReplacement = cmd.getOptionValue("newLineReplacement"); args = cmd.getArgs(); try { PrintStream out = System.out; if (outFile != null) out = new PrintStream(outFile); SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName); Object[] sqlArgs = args; if (stmt.getParamTypes().length != args.length) { System.err.printf( "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n", stmt.getParamTypes().length, args.length); sqlArgs = new Object[stmt.getParamTypes().length]; System.arraycopy(args, 0, sqlArgs, 0, args.length); } Selecter sel = Selecter.factory(stmt); if (!sel.select(sqlArgs)) { System.err.println("No rows returned!"); System.exit(0); } String[] fieldNames = sel.getFieldNames(); if (fieldNames.length == 0) { System.err.println("Query did not return any columns"); exitWithHelp(options); } if (!cmd.hasOption("noHeader")) { StringBuilder sb = new StringBuilder(200); for (String f : fieldNames) sb.append(f).append('\t'); if (sb.length() > 1) sb.setLength(sb.length() - 1); // chop last \t String header = sb.toString(); out.println(header); } StringBuilder sb = new StringBuilder(200); while (sel.hasNext()) { Record sqlRec = sel.next(); sb.setLength(0); for (int i = 0; i < fieldNames.length; i++) { String fld = sqlRec.getStrg(i); if (newLineReplacement != null) fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement); sb.append(fld).append('\t'); } if (sb.length() > 1) sb.setLength(sb.length() - 1); // chop last \t String row = sb.toString(); out.println(row); nStruct++; } } catch (Exception e) { throw new Error(e); } finally { System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct, (System.currentTimeMillis() - start) / 1000); } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java
/** * Run the program./*from w ww . ja va2 s.c o m*/ * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody bin = new FileBody(uploadFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder("Response data received:"); while ((output = in.readLine()) != null) { sb.append(System.getProperty("line.separator")); sb.append(output); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }
From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java
/** * @param args//from www . ja va 2s . c om * @throws Exception */ public static void main(String[] args) throws Exception { String command = null; if (args.length == 0) { command = COMMAND_STARTUP; } else if (args[0].equals(COMMAND_STARTUP)) { command = COMMAND_STARTUP; } else if (args[0].equals(COMMAND_SHUTDOWN)) { command = COMMAND_SHUTDOWN; } if (command == null) { throw new IllegalArgumentException(); } String propertyFile = DEFAULT_PROPERTY_FILE_NAME; // default if (args.length == 2) { propertyFile = args[1]; } final Properties properties = new Properties(); FileInputStream inputStream = new FileInputStream(propertyFile); try { properties.load(inputStream); } finally { inputStream.close(); } if (command.equals(COMMAND_STARTUP)) { new Thread(new Runnable() { public void run() { try { AutoExecServer autoExecServer = new AutoExecServer(); autoExecServer.startup(properties); autoExecServer.runningLoop(); autoExecServer.destroy(); } catch (Exception e) { log.error("Error", e); e.printStackTrace(); } finally { System.exit(0); } } }).start(); } else { StringBuilder commandURL = new StringBuilder("http://localhost:"); commandURL.append( PropertiesUtils.getInt(properties, "port", RemoteControlConfiguration.getDefaultPort())); commandURL.append(CONTEXT_PATH_COMMAND); RemoteControlClient client = new RemoteControlClient(commandURL.toString()); client.stopServer(); } }
From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java
/** * Main function for running on the command line * @param args//from www. j a v a 2 s . c o m */ public static void main(String... args) throws IOException { // Get the available options from the programs Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields(); Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents(); // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); StringBuilder programOptions = new StringBuilder("Program to use for minimization. Choices are\n"); for (String program : allowedProgramsAndForceFields.keySet()) { programOptions.append("\n*** -program " + program + " ***\n"); String forcefields = ""; for (String option : allowedProgramsAndForceFields.get(program)) { forcefields += option + " "; } programOptions.append("-forcefield " + forcefields + "\n"); String solvents = ""; for (String option : allowedProgramsAndSolvents.get(program)) { solvents += option + " "; } programOptions.append("-solvent " + solvents + "\n"); } opt = new Option(OPT_PROGRAM, true, programOptions.toString()); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_FORCEFIELD, true, "Forcefield options. See -program for choices"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_SOLVENT, true, "Solvent options. See -program for choices"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_FIX_TORSION, true, "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (args.length != 0) { System.err.println("Unknown arguments" + args); exitWithHelp(options); } if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); String fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG); boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true")); String programName = cmd.getOptionValue(OPT_PROGRAM); String forcefield = cmd.getOptionValue(OPT_FORCEFIELD); String solvent = cmd.getOptionValue(OPT_SOLVENT); String workDir = cmd.getOptionValue(OPT_WORKING_DIR); if (workDir == null || workDir.trim().length() == 0) workDir = "."; // Create a minimizer SDFMMMinimize minimizer = new SDFMMMinimize(); minimizer.setMethod(programName, forcefield, solvent); minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir); minimizer.close(); System.err.println("Minimization complete."); }
From source file:com.mgmtp.perfload.perfalyzer.PerfAlyzer.java
public static void main(final String[] args) { JCommander jCmd = null;/*from w w w.j a va2 s. c o m*/ try { Stopwatch stopwatch = Stopwatch.createStarted(); LOG.info("Starting perfAlyzer..."); LOG.info("Arguments:"); for (String arg : args) { LOG.info(arg); } PerfAlyzerArgs perfAlyzerArgs = new PerfAlyzerArgs(); jCmd = new JCommander(perfAlyzerArgs); jCmd.parse(args); Injector injector = Guice.createInjector(new PerfAlyzerModule(perfAlyzerArgs)); PerfAlyzer perfAlyzer = injector.getInstance(PerfAlyzer.class); perfAlyzer.runPerfAlyzer(); ExecutorService executorService = injector.getInstance(ExecutorService.class); executorService.shutdownNow(); stopwatch.stop(); LOG.info("Done."); LOG.info("Total execution time: {}", stopwatch); } catch (ParameterException ex) { LOG.error(ex.getMessage()); StringBuilder sb = new StringBuilder(200); jCmd.usage(sb); LOG.info(sb.toString()); System.exit(1); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); System.exit(1); } }