List of usage examples for java.lang StringBuffer append
@Override public synchronized StringBuffer append(double d)
From source file:com.archivas.clienttools.arcmover.cli.ManagedCLIJob.java
@SuppressWarnings({ "UseOfSystemOutOrSystemErr" }) public static void main(String args[]) { if (LOG.isLoggable(Level.FINE)) { StringBuffer sb = new StringBuffer(); sb.append("Program Arguments").append(NEWLINE); for (int i = 0; i < args.length; i++) { sb.append(" ").append(i).append(": ").append(args[i]); sb.append(NEWLINE);/* w ww. j av a2s. c om*/ } LOG.log(Level.FINE, sb.toString()); } ConfigurationHelper.validateLaunchOK(); ManagedCLIJob arcCmd = null; try { if (args[0].equals("copy")) { arcCmd = new ArcCopy(args, 2); } else if (args[0].equals("delete")) { arcCmd = new ArcDelete(args, 2); } else if (args[0].equals("metadata")) { arcCmd = new ArcMetadata(args, 2); } else { throw new RuntimeException("Unsupported operation: " + args[0]); } arcCmd.parseArgs(); if (arcCmd.shouldPrintHelp()) { System.out.println(arcCmd.helpScreen()); } else { arcCmd.execute(new PrintWriter(System.out), new PrintWriter(System.err)); } } catch (ParseException e) { System.out.println("Error: " + e.getMessage()); System.out.println(); System.out.println(arcCmd.helpScreen()); arcCmd.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage(), e); System.out.println(); System.err.println("Job failed. " + e.getMessage()); if (arcCmd != null) { arcCmd.setExitCode(EXIT_CODE_DM_ERROR); } } finally { if (arcCmd != null) { arcCmd.exit(); } } }
From source file:com.mycompany.myelasticsearch.MainClass.java
/** * @param args the command line arguments *//*from w w w .ja v a 2s .c o m*/ public static void main(String[] args) { // TODO code application logic here Tika tika = new Tika(); String fileEntry = "C:\\Contract\\Contract1.pdf"; String filetype = tika.detect(fileEntry); System.out.println("FileType " + filetype); BodyContentHandler handler = new BodyContentHandler(-1); String text = ""; Metadata metadata = new Metadata(); FileInputStream inputstream = null; try { inputstream = new FileInputStream(fileEntry); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(inputstream, handler, metadata, pcontext); } catch (IOException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (TikaException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } String docText = ""; String outputArray[]; String out[]; //getting the content of the document docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", ""); // PhraseDetection.getPhrases(docText); try { Node node = nodeBuilder().node(); Client client = node.client(); DocumentReader.parseString(docText, client); //"Borrowing should be replaced by the user input key" Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing"); node.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } Stanford.getSentence(docText); int definedTermsEnd = docText.indexOf("SCHEDULES"); String toc = docText.substring(0, definedTermsEnd); String c = docText.substring(definedTermsEnd); System.out.println("Table of content" + toc); System.out.println("--------------------------------"); System.out.println("content" + c); out = toc.split("Article|article|ARTICLE"); int count = 0; String outputArrayString = ""; int s = 0; StringBuffer tocOutput = new StringBuffer(); for (String o : out) { if (count != 0) { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { tocOutput.append(o); tocOutput.append("JigarAnkitNeeraj"); System.out.println(s); } } outputArrayString += "Count" + count + o; count++; System.out.println(); } System.out.println("---------------------------------------------------Content---------"); count = 1; StringBuffer contentOutput = new StringBuffer(); String splitContent[] = c.split("ARTICLE|Article"); Node node = nodeBuilder().node(); Client client = node.client(); for (String o : splitContent) { o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", ""); o = o.replaceAll("\n", " "); char input = o.charAt(1); if (input >= '0' && input <= '9') { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { //System.out.println(s); JSONObject articleJSONObject = new JSONObject(); contentOutput.append(" \n MyArticlesSeparated \n "); articleJSONObject.put("Article" + count, o.toString()); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "article", String.valueOf(count)) .setSource(articleJSONObject.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); count++; } //outputArrayString += "Count" + count + o; contentOutput.append(o); } } Elastic.getDocument(client, "contract", "article", "1"); Elastic.searchDocument(client, "contract", "article", "Lenders"); Elastic.searchDocument(client, "contract", "article", "Negative Covenants"); Elastic.searchDocument(client, "contract", "article", "Change in Law"); String tableOfContent[]; tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj"); String splitContectsAccordingToArticles[]; splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated"); int numberOfArticle = splitContectsAccordingToArticles.length; int countArticle = 1; Double toBeTruncated = new Double("" + countArticle + ".00"); String section = "Section"; toBeTruncated += 0.01; System.out.println(toBeTruncated); String sectionEnd; StringBuffer sectionOutput = new StringBuffer(); int skipFirstArtcile = 0; JSONObject obj = new JSONObject(); for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "section", String.valueOf(count)) .setSource(obj.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); } catch (Exception e) { //What if Article has No Sections String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1); String sectionArticle = "ARTICLE " + numberOnly; sectionOutput.append(" \n Value:" + article); obj.put(sectionArticle, article); System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); System.out.println(sectionOutput); String patternStr = "\\n\\n+[(]"; String paragraphSubstringArray[] = article.substring(start, end).split(patternStr); JSONObject paragraphObject = new JSONObject(); int counter = 0; for (String paragraphSubstring : paragraphSubstringArray) { counter++; paragraphObject.put("Paragraph " + counter, paragraphSubstring); } obj.put(sectionStart, paragraphObject); } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end)); PhraseDetection.getPhrases(docText); } catch (Exception e) { //What if Article has No Sections String sectionArticle = "ARTICLE"; System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } Elastic.getDocument(client, "contract", "section", "1"); Elastic.searchDocument(client, "contract", "section", "Lenders"); Elastic.searchDocument(client, "contract", "section", "Negative Covenants"); try { FileWriter file = new FileWriter("TableOfIndex.txt"); file.write(tocOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract3_JSONFile.txt"); file.write(obj.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract1_KeyValueSections.txt"); file.write(sectionOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java
public static void main(String[] args) { boolean isTTY = (System.console() != null); long startTime = System.currentTimeMillis(); try {/*from w w w. ja v a 2 s .c om*/ SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser theParser = parserFactory.newSAXParser(); TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler(); processArgs(xmlHandler, args); TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName()); logger = TrackingLogger.getInstance(simConfig.build()); if (logger.isSet(OpLevel.TRACE)) traceLevel = OpLevel.TRACE; else if (logger.isSet(OpLevel.DEBUG)) traceLevel = OpLevel.DEBUG; if (runType == SimulatorRunType.RUN_SIM) { if (StringUtils.isEmpty(simFileName)) { simFileName = "tnt4j-sim.xml"; String fileName = readFromConsole("Simulation file [" + simFileName + "]: "); if (!StringUtils.isEmpty(fileName)) simFileName = fileName; } StringBuffer simDef = new StringBuffer(); BufferedReader simLoader = new BufferedReader(new FileReader(simFileName)); String line; while ((line = simLoader.readLine()) != null) simDef.append(line).append("\n"); simLoader.close(); info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations + ", ttl.sec=" + ttl); startTime = System.currentTimeMillis(); if (isTTY && numIterations > 1) System.out.print("Iteration: "); int itTrcWidth = 0; for (iteration = 1; iteration <= numIterations; iteration++) { itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth); theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler); if (!Utils.isEmpty(jkFileName)) { PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true)); gwFile.println(""); gwFile.close(); } } if (numIterations > 1) System.out.println(""); info("jKool Activity Simulator Run finished, elapsed time = " + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime)); printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics"); } else if (runType == SimulatorRunType.REPLAY_SIM) { info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations=" + numIterations); connect(); startTime = System.currentTimeMillis(); // Determine number of lines in file BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName)); for (numIterations = 0; gwFile.readLine() != null; numIterations++) ; gwFile.close(); // Reopen the file and gwFile = new BufferedReader(new java.io.FileReader(jkFileName)); if (isTTY && numIterations > 1) System.out.print("Processing Line: "); int itTrcWidth = 0; String gwMsg; iteration = 0; while ((gwMsg = gwFile.readLine()) != null) { iteration++; if (isTTY) itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth); gwConn.write(gwMsg); } if (isTTY && numIterations > 1) System.out.println(""); long endTime = System.currentTimeMillis(); info("jKool Activity Simulator Replay finished, elasped.time = " + DurationFormatUtils.formatDurationHMS(endTime - startTime)); } } catch (Exception e) { if (e instanceof SAXParseException) { SAXParseException spe = (SAXParseException) e; error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e); } else { error("Error running simulator", e); } } finally { try { Thread.sleep(1000L); } catch (Exception e) { } TNT4JSimulator.disconnect(); } System.exit(0); }
From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java
public static void main(String[] argv) { // Parse command line arguments CommandLine args = null;/*from w ww .ja v a2 s .com*/ try { Parser p = new BasicParser(); args = p.parse(cliOpts, argv); } catch (ParseException e) { log.error(e.getMessage(), e); } // Check for help if (args.hasOption('?')) { printUsage(); return; } // Runtime properties Properties props = System.getProperties(); // Check for ~/.rabbitmqrc File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc"); if (userSettings.exists()) { try { props.load(new FileInputStream(userSettings)); } catch (IOException e) { log.error(e.getMessage(), e); } } // Load Groovy builder file StringBuffer script = new StringBuffer(); BufferedInputStream in = null; String filename = "<STDIN>"; if (args.hasOption("f")) { filename = args.getOptionValue("f"); try { in = new BufferedInputStream(new FileInputStream(filename)); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } else { in = new BufferedInputStream(System.in); } // Read script if (null != in) { byte[] buff = new byte[4096]; try { for (int read = in.read(buff); read > -1;) { script.append(new String(buff, 0, read)); read = in.read(buff); } } catch (IOException e) { log.error(e.getMessage(), e); } } else { System.err.println("No script file to evaluate..."); } PrintStream stdout = System.out; PrintStream out = null; if (args.hasOption("o")) { try { out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true); System.setOut(out); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE") ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar)) : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" }); try { // Setup RabbitMQ String username = (args.hasOption("U") ? args.getOptionValue("U") : props.getProperty("mq.user", "guest")); String password = (args.hasOption("P") ? args.getOptionValue("P") : props.getProperty("mq.password", "guest")); String virtualHost = (args.hasOption("v") ? args.getOptionValue("v") : props.getProperty("mq.virtualhost", "/")); String host = (args.hasOption("h") ? args.getOptionValue("h") : props.getProperty("mq.host", "localhost")); int port = Integer.parseInt( args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672")); CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host); connectionFactory.setPort(port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); if (null != virtualHost) { connectionFactory.setVirtualHost(virtualHost); } // The DSL builder RabbitMQBuilder builder = new RabbitMQBuilder(); builder.setConnectionFactory(connectionFactory); // Our execution environment Binding binding = new Binding(args.getArgs()); binding.setVariable("mq", builder); String fileBaseName = filename.replaceAll("\\.groovy$", ""); binding.setVariable("log", LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1))); if (null != out) { binding.setVariable("out", out); } // Include helper files GroovyShell shell = new GroovyShell(binding); for (String inc : includes) { File f = new File(inc); if (f.isDirectory()) { File[] files = f.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String s) { return s.endsWith(".groovy"); } }); for (File incFile : files) { run(incFile, shell, binding); } } else { run(f, shell, binding); } } run(script.toString(), shell, binding); while (builder.isActive()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } if (null != out) { out.close(); System.setOut(stdout); } } finally { System.exit(0); } }
From source file:com.servoy.extensions.plugins.http.HttpProvider.java
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$ System.out.println(//from w w w. j ava 2 s . c o m "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$ System.out.println( "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$ } else { String url = args[1]; String destdir = args[2]; List parts = new ArrayList(); int dir_from = 0; int dir_to = 0; int dir_fill = 0; int from = 0; int to = 0; int fill = 0; StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$ boolean hasDir = (tk.countTokens() > 5); boolean inDir = hasDir; System.out.println("hasDir " + hasDir); //$NON-NLS-1$ boolean inTag = false; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("[")) //$NON-NLS-1$ { inTag = true; continue; } if (token.equals("]")) //$NON-NLS-1$ { inTag = false; if (inDir) inDir = false; continue; } if (inTag) { int idx = token.indexOf('-'); String s_from = token.substring(0, idx); int a_from = new Integer(s_from).intValue(); int a_fill = s_from.length(); int a_to = new Integer(token.substring(idx + 1)).intValue(); if (inDir) { dir_from = a_from; dir_to = a_to; dir_fill = a_fill; } else { from = a_from; to = a_to; fill = a_fill; } } else { parts.add(token); } } DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpGet main = new HttpGet(args[0]); HttpResponse res = client.execute(main); ; int main_rs = res.getStatusLine().getStatusCode(); if (main_rs != 200) { System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$ return; } for (int d = dir_from; d <= dir_to; d++) { String dir_number = "" + d; //$NON-NLS-1$ if (dir_fill > 1) { dir_number = "000000" + d; //$NON-NLS-1$ int dir_digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$ dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits), dir_number.length()); } for (int i = from; i <= to; i++) { try { String number = "" + i; //$NON-NLS-1$ if (fill > 1) { number = "000000" + i; //$NON-NLS-1$ int digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("digits " + digits); //$NON-NLS-1$ number = number.substring(number.length() - (fill - digits), number.length()); } int part = 0; StringBuffer surl = new StringBuffer((String) parts.get(part++)); if (hasDir) { surl.append(dir_number); surl.append(parts.get(part++)); } surl.append(number); surl.append(parts.get(part++)); System.out.println("reading url " + surl); //$NON-NLS-1$ int indx = surl.toString().lastIndexOf('/'); StringBuffer sfile = new StringBuffer(destdir); sfile.append("\\"); //$NON-NLS-1$ if (hasDir) { sfile.append("dir_"); //$NON-NLS-1$ sfile.append(dir_number); sfile.append("_"); //$NON-NLS-1$ } sfile.append(surl.toString().substring(indx + 1)); File file = new File(sfile.toString()); if (file.exists()) { file = new File("" + System.currentTimeMillis() + sfile.toString()); } System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$ // URL iurl = createURLFromString(surl.toString()); HttpGet get = new HttpGet(surl.toString()); HttpResponse response = client.execute(get); int result = response.getStatusLine().getStatusCode(); System.out.println("page http result " + result); //$NON-NLS-1$ if (result == 200) { InputStream is = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(file); Utils.streamCopy(is, fos); fos.close(); } } catch (Exception e) { System.err.println(e); } } } } }
From source file:com.bright.json.JSonRequestor.java
public static void main(String[] args) { String fileBasename = null;/*from w ww .j av a 2s. c o m*/ String[] zipArgs = null; JFileChooser chooser = new JFileChooser("/Users/panos/STR_GRID"); try { chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle("Select the input directory"); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); zipArgs = new String[] { chooser.getSelectedFile().toString(), chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".zip" }; com.bright.utils.ZipFile.main(zipArgs); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } JTextField uiHost = new JTextField("ucs-head.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("hadoop.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("nexus"); // TextPrompt puiUser = new TextPrompt("nexus", uiUser); JTextField uiPass = new JPasswordField("system"); // TextPrompt puiPass = new TextPrompt("", uiPass); JTextField uiWdir = new JTextField("/home/nexus/pp1234"); // TextPrompt puiWdir = new TextPrompt("/home/nexus/nexus_workdir", // uiWdir); JTextField uiOut = new JTextField("foo"); // TextPrompt puiOut = new TextPrompt("foobar123", uiOut); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); myPanel.add(new JLabel("Working Directory:")); myPanel.add(uiWdir); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Output Study Name ( -s ):")); myPanel.add(uiOut); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rfile = uiWdir.getText(); String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String nexusOut = uiOut.getText(); String[] myarg = new String[] { zipArgs[1], ruser + "@" + rhost + ":" + rfile, nexusOut, fileBasename }; com.bright.utils.ScpTo.main(myarg); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); jobSubmit myjob = new jobSubmit(); jobSubmit.jobObject myjobObj = new jobSubmit.jobObject(); myjob.setService("cmjob"); myjob.setCall("submitJob"); myjobObj.setQueue("defq"); myjobObj.setJobname("myNexusJob"); myjobObj.setAccount(ruser); myjobObj.setRundirectory(rfile); myjobObj.setUsername(ruser); myjobObj.setGroupname("cmsupport"); myjobObj.setPriority("1"); myjobObj.setStdinfile(rfile + "/stdin-mpi"); myjobObj.setStdoutfile(rfile + "/stdout-mpi"); myjobObj.setStderrfile(rfile + "/stderr-mpi"); myjobObj.setResourceList(Arrays.asList("")); myjobObj.setDependencies(Arrays.asList("")); myjobObj.setMailNotify(false); myjobObj.setMailOptions("ALL"); myjobObj.setMaxWallClock("00:10:00"); myjobObj.setNumberOfProcesses(1); myjobObj.setNumberOfNodes(1); myjobObj.setNodes(Arrays.asList("")); myjobObj.setCommandLineInterpreter("/bin/bash"); myjobObj.setUserdefined(Arrays.asList("cd " + rfile, "date", "pwd")); myjobObj.setExecutable("mpirun"); myjobObj.setArguments("-env I_MPI_FABRICS shm:tcp " + Constants.NEXUSSIM_EXEC + " -mpi -c " + rfile + "/" + fileBasename + "/" + fileBasename + " -s " + rfile + "/" + fileBasename + "/" + nexusOut); myjobObj.setModules(Arrays.asList("shared", "nexus", "intel-mpi/64")); myjobObj.setDebug(false); myjobObj.setBaseType("Job"); myjobObj.setIsSlurm(true); myjobObj.setUniqueKey(0); myjobObj.setModified(false); myjobObj.setToBeRemoved(false); myjobObj.setChildType("SlurmJob"); myjobObj.setJobID("Nexus test"); // Map<String,jobSubmit.jobObject > mymap= new HashMap<String, // jobSubmit.jobObject>(); // mymap.put("Slurm",myjobObj); ArrayList<Object> mylist = new ArrayList<Object>(); mylist.add("slurm"); mylist.add(myjobObj); myjob.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(myjob); // To be used from a real console and not Eclipse Delete.main(zipArgs[1]); String message = JSonRequestor.doRequest(json2, cmURL, cookies); @SuppressWarnings("resource") Scanner resInt = new Scanner(message).useDelimiter("[^0-9]+"); int jobID = resInt.nextInt(); System.out.println("Job ID: " + jobID); JOptionPane optionPane = new JOptionPane(message); JDialog myDialog = optionPane.createDialog(null, "CMDaemon response: "); myDialog.setModal(false); myDialog.setVisible(true); ArrayList<Object> mylist2 = new ArrayList<Object>(); mylist2.add("slurm"); String JobID = Integer.toString(jobID); mylist2.add(JobID); myjob.setArgs(mylist2); myjob.setService("cmjob"); myjob.setCall("getJob"); String json3 = g.toJson(myjob); System.out.println("JSON Request No. 4 " + json3); cmReadFile readfile = new cmReadFile(); readfile.setService("cmmain"); readfile.setCall("readFile"); readfile.setUserName(ruser); int fileByteIdx = 1; readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx); String json4 = g.toJson(readfile); String monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", ""); if (monFile.startsWith("Unable")) { monFile = ""; } else { fileByteIdx += countLines(monFile, "\\\\n"); System.out.println(""); } StringBuffer output = new StringBuffer(); // Get the correct Line Separator for the OS (CRLF or LF) String nl = System.getProperty("line.separator"); String filename = chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".sum.txt"; System.out.println("Local monitoring file: " + filename); output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator"))); String getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies); jobGet getJobObj = new Gson().fromJson(getJobJSON, jobGet.class); System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString()); while (getJobObj.getStatus().toString().equals("RUNNING") || getJobObj.getStatus().toString().equals("COMPLETING")) { try { getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies); getJobObj = new Gson().fromJson(getJobJSON, jobGet.class); System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString()); readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx); json4 = g.toJson(readfile); monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", ""); if (monFile.startsWith("Unable")) { monFile = ""; } else { output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator"))); System.out.println("FILE INDEX:" + fileByteIdx); fileByteIdx += countLines(monFile, "\\\\n"); } Thread.sleep(Constants.STATUS_CHECK_INTERVAL); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } Gson gson_nice = new GsonBuilder().setPrettyPrinting().create(); String json_out = gson_nice.toJson(getJobJSON); System.out.println(json_out); System.out.println("JSON Request No. 5 " + json4); readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx); json4 = g.toJson(readfile); monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", ""); if (monFile.startsWith("Unable")) { monFile = ""; } else { output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator"))); fileByteIdx += countLines(monFile, "\\\\n"); } System.out.println("FILE INDEX:" + fileByteIdx); /* * System.out.print("Monitoring file: " + monFile.replaceAll("\\n", * System.getProperty("line.separator"))); try { * FileUtils.writeStringToFile( new * File(chooser.getCurrentDirectory().toString() + File.separator + * fileBasename + ".sum.txt"), monFile.replaceAll("\\n", * System.getProperty("line.separator"))); } catch (IOException e) { * * e.printStackTrace(); } */ if (getJobObj.getStatus().toString().equals("COMPLETED")) { String[] zipArgs_from = new String[] { chooser.getSelectedFile().toString(), chooser.getCurrentDirectory().toString() + File.separator + fileBasename + "_out.zip" }; String[] myarg_from = new String[] { ruser + "@" + rhost + ":" + rfile + "/" + fileBasename + "_out.zip", zipArgs_from[1], rfile, fileBasename }; com.bright.utils.ScpFrom.main(myarg_from); JOptionPane optionPaneS = new JOptionPane("Job execution completed without errors!"); JDialog myDialogS = optionPaneS.createDialog(null, "Job status: "); myDialogS.setModal(false); myDialogS.setVisible(true); } else { JOptionPane optionPaneF = new JOptionPane("Job execution FAILED!"); JDialog myDialogF = optionPaneF.createDialog(null, "Job status: "); myDialogF.setModal(false); myDialogF.setVisible(true); } try { System.out.println("Local monitoring file: " + filename); BufferedWriter out = new BufferedWriter(new FileWriter(filename)); String outText = output.toString(); String newString = outText.replace("\\\\n", nl); System.out.println("Text: " + outText); out.write(newString); out.close(); rmDuplicateLines.main(filename); } catch (IOException e) { e.printStackTrace(); } doLogout(cmURL, cookies); System.exit(0); }
From source file:com.metadave.kash.KashConsole.java
public static void main(String[] args) throws IOException { CommandLine commandLine = processArgs(args); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false);/*from w ww . j a v a2 s .co m*/ reader.setExpandEvents(false); // TODO: look into this // TODO: Pasting in text with tabs prints out a ton of completions //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords)); String line; PrintWriter out = new PrintWriter(System.out); KashRuntimeContext ctx = new KashRuntimeContext(); if (!commandLine.hasOption("nosignals")) { ConsoleSignalHander.install("INT", ctx); } boolean nextLinePrompt = false; ANSIBuffer buf = new ANSIBuffer(); buf.setAnsiEnabled(!commandLine.hasOption("nocolor")); buf.blue("Welcome to Kash\n"); buf.blue("(c) 2015 Dave Parfitt\n"); System.out.println(buf.toString()); if (!commandLine.hasOption("noconfig")) { String config = null; try { config = readConfig(); } catch (Exception e) { e.printStackTrace(); } if (config != null && !config.trim().isEmpty()) { processInput(config, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); } } // if (commandLine.hasOption("infile")) { // String filename = commandLine.getOptionValue("infile"); // readInputFile(filename, ctx); // ctx.getActionListener().term(); // System.exit(0); // } StringBuffer lines = new StringBuffer(); ANSIBuffer ansiprompt = new ANSIBuffer(); ansiprompt.setAnsiEnabled(true); ansiprompt.green("> "); String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor")); boolean inHereDoc = false; while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) { out.flush(); String chunks[] = line.split(" "); String consoleCommandCheck = chunks[0].toLowerCase().trim(); if (consoleOnlyCommands.containsKey(consoleCommandCheck)) { consoleOnlyCommands.get(consoleCommandCheck).run(line, reader); continue; } if (line.contains("~%~") && !line.contains("\\~%~")) { inHereDoc = !inHereDoc; } if (!line.trim().endsWith(";")) { nextLinePrompt = true; lines.append(line); lines.append("\n"); } else if (line.trim().endsWith(";") && !inHereDoc) { lines.append(line); String input = lines.toString(); nextLinePrompt = false; processInput(input, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); lines = new StringBuffer(); } else if (inHereDoc) { lines.append(line); lines.append("\n"); } } }
From source file:com.metadave.eql.EQLConsole.java
public static void main(String[] args) throws IOException { CommandLine commandLine = processArgs(args); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false);//from www .ja v a 2 s . c om reader.setExpandEvents(false); // TODO: look into this // TODO: Pasting in text with tabs prints out a ton of completions //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords)); String line; PrintWriter out = new PrintWriter(System.out); RuntimeContext ctx = new RuntimeContext(); if (!commandLine.hasOption("nosignals")) { ConsoleSignalHander.install("INT", ctx); } boolean nextLinePrompt = false; ANSIBuffer buf = new ANSIBuffer(); buf.setAnsiEnabled(!commandLine.hasOption("nocolor")); buf.blue("Welcome to EQL\n"); buf.blue("(c) 2015 Dave Parfitt\n"); System.out.println(buf.toString()); if (!commandLine.hasOption("noconfig")) { String config = null; try { config = readConfig(); } catch (Exception e) { e.printStackTrace(); } if (config != null && !config.trim().isEmpty()) { processInput(config, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); } } // if (commandLine.hasOption("infile")) { // String filename = commandLine.getOptionValue("infile"); // readInputFile(filename, ctx); // ctx.getActionListener().term(); // System.exit(0); // } StringBuffer lines = new StringBuffer(); ANSIBuffer ansiprompt = new ANSIBuffer(); ansiprompt.setAnsiEnabled(true); ansiprompt.green("> "); String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor")); boolean inHereDoc = false; while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) { out.flush(); String chunks[] = line.split(" "); String consoleCommandCheck = chunks[0].toLowerCase().trim(); if (consoleOnlyCommands.containsKey(consoleCommandCheck)) { consoleOnlyCommands.get(consoleCommandCheck).run(line, reader); continue; } if (line.contains("~%~") && !line.contains("\\~%~")) { inHereDoc = !inHereDoc; } if (!line.trim().endsWith(";")) { nextLinePrompt = true; lines.append(line); lines.append("\n"); } else if (line.trim().endsWith(";") && !inHereDoc) { lines.append(line); String input = lines.toString(); nextLinePrompt = false; processInput(input, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); lines = new StringBuffer(); } else if (inHereDoc) { lines.append(line); lines.append("\n"); } } }
From source file:com.basho.contact.ContactConsole.java
public static void main(String[] args) throws IOException { CommandLine commandLine = processArgs(args); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false);// w w w. j a va2 s. co m reader.setExpandEvents(false); // TODO: look into this // TODO: Pasting in text with tabs prints out a ton of completions //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords)); String line; PrintWriter out = new PrintWriter(System.out); DefaultConnectionProvider connections = new DefaultConnectionProvider(); RuntimeContext ctx = new RuntimeContext(connections, System.out, System.err); if (!commandLine.hasOption("nosignals")) { ConsoleSignalHander.install("INT", ctx); } ContactWalker walker = new ContactWalker(ctx); ContactAdminWalker adminWalker = new ContactAdminWalker(ctx); List<ContactBaseListener> walkers = new ArrayList<ContactBaseListener>(); walkers.add(walker); walkers.add(adminWalker); boolean nextLinePrompt = false; ANSIBuffer buf = new ANSIBuffer(); buf.setAnsiEnabled(!commandLine.hasOption("nocolor")); buf.blue("Welcome to Riak Contact\n"); buf.blue("(c) 2013 Dave Parfitt\n"); System.out.println(buf.toString()); if (!commandLine.hasOption("noconfig")) { String config = null; try { config = readConfig(); } catch (Exception e) { e.printStackTrace(); } if (config != null && !config.trim().isEmpty()) { processInput(config, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); } } if (commandLine.hasOption("infile")) { String filename = commandLine.getOptionValue("infile"); readInputFile(filename, walkers, ctx); ctx.getActionListener().term(); System.exit(0); } StringBuffer lines = new StringBuffer(); ANSIBuffer ansiprompt = new ANSIBuffer(); ansiprompt.setAnsiEnabled(true); ansiprompt.green("> "); String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor")); boolean inHereDoc = false; while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) { out.flush(); String chunks[] = line.split(" "); String consoleCommandCheck = chunks[0].toLowerCase().trim(); if (consoleOnlyCommands.containsKey(consoleCommandCheck)) { consoleOnlyCommands.get(consoleCommandCheck).run(line, reader); continue; } if (line.contains("~%~") && !line.contains("\\~%~")) { inHereDoc = !inHereDoc; } if (!line.trim().endsWith(";")) { nextLinePrompt = true; lines.append(line); lines.append("\n"); } else if (line.trim().endsWith(";") && !inHereDoc) { lines.append(line); String input = lines.toString(); nextLinePrompt = false; processInput(input, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); lines = new StringBuffer(); } else if (inHereDoc) { lines.append(line); lines.append("\n"); } } ctx.getActionListener().term(); }
From source file:Gen.java
public static void main(String[] args) throws Exception { try {// w w w . j a v a2 s . co m File[] files = null; if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) { files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".XML"); }; }); } else { String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("") ? System.getProperty("file") : "rjmap.xml"; files = new File[] { new File(fileName) }; } log.info("files : " + Arrays.toString(files)); if (files == null || files.length == 0) { log.info("no files to parse"); System.exit(0); } boolean formatsource = true; if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("") && System.getProperty("formatsource").equalsIgnoreCase("false")) { formatsource = false; } GEN_ROOT = System.getProperty("outputdir"); if (GEN_ROOT == null || GEN_ROOT.equals("")) { GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib"; } GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/'); if (GEN_ROOT.endsWith("/")) GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1); System.out.println("GEN ROOT:" + GEN_ROOT); MAPPING_JAR_NAME = System.getProperty("mappingjar") != null && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar") : "mapping.jar"; if (!MAPPING_JAR_NAME.endsWith(".jar")) MAPPING_JAR_NAME += ".jar"; GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src"; GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + ""; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); domFactory.setValidating(false); DocumentBuilder documentBuilder = domFactory.newDocumentBuilder(); for (int f = 0; f < files.length; ++f) { log.info("parsing file : " + files[f]); Document document = documentBuilder.parse(files[f]); Vector<Node> initNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript", initNodes); for (int i = 0; i < initNodes.size(); ++i) { NamedNodeMap attrs = initNodes.elementAt(i).getAttributes(); boolean embed = attrs.getNamedItem("embed") != null && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true"); StringBuffer vbuffer = new StringBuffer(); if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue()); vbuffer.append('\n'); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } vbuffer.append(Utils.getFileAsStringBuffer(fname)); } initScriptBuffer.append(vbuffer); if (embed) embedScriptBuffer.append(vbuffer); } Vector<Node> packageInitNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript", packageInitNodes); for (int i = 0; i < packageInitNodes.size(); ++i) { NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes(); String packageName = attrs.getNamedItem("package").getNodeValue(); if (packageName.equals("")) packageName = "rGlobalEnv"; if (!packageName.endsWith("Function")) packageName += "Function"; if (packageEmbedScriptHashMap.get(packageName) == null) { packageEmbedScriptHashMap.put(packageName, new StringBuffer()); } StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName); // if (!packageName.equals("rGlobalEnvFunction")) { // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n"); // } if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname); vbuffer.append(fileBuffer); initScriptBuffer.append(fileBuffer); } } Vector<Node> functionsNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function", functionsNodes); for (int i = 0; i < functionsNodes.size(); ++i) { NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes(); String functionName = attrs.getNamedItem("name").getNodeValue(); boolean forWeb = attrs.getNamedItem("forWeb") != null && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true"); String signature = (attrs.getNamedItem("signature") == null ? "" : attrs.getNamedItem("signature").getNodeValue() + ","); String renameTo = (attrs.getNamedItem("renameTo") == null ? null : attrs.getNamedItem("renameTo").getNodeValue()); HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName); if (sigMap == null) { sigMap = new HashMap<String, FAttributes>(); Globals._functionsToPublish.put(functionName, sigMap); if (attrs.getNamedItem("returnType") == null) { _functionsVector.add(new String[] { functionName }); } else { _functionsVector.add( new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() }); } } sigMap.put(signature, new FAttributes(renameTo, forWeb)); if (forWeb) _webPublishingEnabled = true; } if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("") && System.getProperty("targetjdk").compareTo("1.5") < 0) { if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) { log.info("be careful, web publishing disabled beacuse target JDK<1.5"); } _webPublishingEnabled = false; } else { if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("") || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) { _webPublishingEnabled = true; } if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) { log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use"); _webPublishingEnabled = false; } } Vector<Node> s4Nodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes); if (s4Nodes.size() > 0) { String formalArgs = ""; String signature = ""; for (int i = 0; i < s4Nodes.size(); ++i) { NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes(); String s4Name = attrs.getNamedItem("name").getNodeValue(); formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ","); signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ","); } String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER + "', signature(" + signature + ") , function(" + formalArgs + ") { })"; initScriptBuffer.append(genBeansScriptlet); _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" }); } } if (!new File(GEN_ROOT_LIB).exists()) regenerateDir(GEN_ROOT_LIB); else { clean(GEN_ROOT_LIB, true); } for (int i = 0; i < rwebservicesScripts.length; ++i) DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]); String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() { public void run(Rengine e) { DirectJNI.getInstance().toggleMarker(); DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString()); log.info(" init script status : " + DirectJNI.getInstance().cutStatusSinceMarker()); for (int i = 0; i < _functionsVector.size(); ++i) { String[] functionPair = _functionsVector.elementAt(i); log.info("dealing with : " + functionPair[0]); regenerateDir(GEN_ROOT_SRC); String createMapStr = "createMap("; boolean isGeneric = e.rniGetBoolArrayI( e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1; log.info("is Generic : " + isGeneric); if (isGeneric) { createMapStr += functionPair[0]; } else { createMapStr += "\"" + functionPair[0] + "\""; } createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\""; createMapStr += ", typeMode=\"robject\""; createMapStr += (functionPair.length == 1 || functionPair[1] == null || functionPair[1].trim().equals("") ? "" : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1] + "\")"); createMapStr += ")"; log.info("------------------------------------------"); log.info("-- createMapStr=" + createMapStr); DirectJNI.getInstance().toggleMarker(); e.rniEval(e.rniParse(createMapStr, 1), 0); String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker(); log.info(" createMap status : " + createMapStatus); log.info("------------------------------------------"); deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms"); compile(GEN_ROOT_SRC); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null); URL url = null; try { url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar") .replace('\\', '/') + "!/"); } catch (Exception ex) { ex.printStackTrace(); } DirectJNI.generateMaps(url, true); } } }); log.info(lastStatus); log.info(DirectJNI._rPackageInterfacesHash); regenerateDir(GEN_ROOT_SRC); for (int i = 0; i < _functionsVector.size(); ++i) { unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC); } regenerateRPackageClass(true); generateS4BeanRef(); if (formatsource) applyJalopy(GEN_ROOT_SRC); compile(GEN_ROOT_SRC); for (String k : DirectJNI._rPackageInterfacesHash.keySet()) { Rmic rmicTask = new Rmic(); rmicTask.setProject(_project); rmicTask.setTaskName("rmic_packages"); rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC)); rmicTask.setBase(new File(GEN_ROOT_SRC)); rmicTask.setClassname(k + "ImplRemote"); rmicTask.init(); rmicTask.execute(); } // DirectJNI._rPackageInterfacesHash=new HashMap<String, // Vector<Class<?>>>(); // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new // Vector<Class<?>>()); if (_webPublishingEnabled) { jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null); URL url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/"); ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader()); for (String className : DirectJNI._rPackageInterfacesHash.keySet()) { if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0) continue; log.info("######## " + className); WsGen wsgenTask = new WsGen(); wsgenTask.setProject(_project); wsgenTask.setTaskName("wsgen"); FileSet rjb_fileSet = new FileSet(); rjb_fileSet.setProject(_project); rjb_fileSet.setDir(new File(".")); rjb_fileSet.setIncludes("RJB.jar"); DirSet src_dirSet = new DirSet(); src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); Path classPath = new Path(_project); classPath.addFileset(rjb_fileSet); classPath.addDirset(src_dirSet); wsgenTask.setClasspath(classPath); wsgenTask.setKeep(true); wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setSei(className + "Web"); wsgenTask.init(); wsgenTask.execute(); } new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete(); } embedRScripts(); HashMap<String, String> marker = new HashMap<String, String>(); marker.put("RJBMAPPINGJAR", "TRUE"); Properties props = new Properties(); props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames)); props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping)); props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert)); props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping)); props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash)); props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash)); props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories)); new File(GEN_ROOT_SRC + "/" + "maps").mkdirs(); FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml"); props.storeToXML(fos, null); fos.close(); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker); if (_webPublishingEnabled) genWeb(); DirectJNI._mappingClassLoader = null; } finally { System.exit(0); } }