List of usage examples for java.lang String startsWith
public boolean startsWith(String prefix)
From source file:TypeInfoWriter.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();//from ww w . java 2s . c o m System.exit(1); } // variables XMLReader parser = null; Vector schemas = null; Vector instances = null; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); e.printStackTrace(System.err); System.exit(1); } } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); e.printStackTrace(System.err); System.exit(1); } } try { // Create writer TypeInfoWriter writer = new TypeInfoWriter(); writer.setOutput(System.out, "UTF8"); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(writer); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and parser ValidatorHandler validator = schema.newValidatorHandler(); parser.setContentHandler(validator); if (validator instanceof DTDHandler) { parser.setDTDHandler((DTDHandler) validator); } parser.setErrorHandler(writer); validator.setContentHandler(writer); validator.setErrorHandler(writer); writer.setTypeInfoProvider(validator.getTypeInfoProvider()); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents and print type information if (instances != null && instances.size() > 0) { final int length = instances.size(); for (int j = 0; j < length; ++j) { parser.parse((String) instances.elementAt(j)); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } }
From source file:com.bright.json.JSonRequestor.java
public static void main(String[] args) { String fileBasename = null;//from www . j a v 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:net.sf.firemox.Magic.java
/** * @param args/* w w w.j a v a 2 s. c o m*/ * the command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { Log.init(); Log.debug("MP v" + IdConst.VERSION + ", jre:" + System.getProperty("java.runtime.version") + ", jvm:" + System.getProperty("java.vm.version") + ",os:" + System.getProperty("os.name") + ", res:" + Toolkit.getDefaultToolkit().getScreenSize().width + "x" + Toolkit.getDefaultToolkit().getScreenSize().height + ", root:" + MToolKit.getRootDir()); System.setProperty("swing.aatext", "true"); System.setProperty(SubstanceLookAndFeel.WATERMARK_IMAGE_PROPERTY, MToolKit.getIconPath(Play.ZONE_NAME + "/hardwoodfloor.png")); final File substancelafFile = MToolKit.getFile(FILE_SUBSTANCE_PROPERTIES); if (substancelafFile == null) { Log.warn("Unable to locate '" + FILE_SUBSTANCE_PROPERTIES + "' file, you are using the command line with wrong configuration. See http://www.firemox.org/dev/project.html documentation"); } else { System.getProperties().load(new FileInputStream(substancelafFile)); } MToolKit.defaultFont = new Font("Arial", 0, 11); try { if (args.length > 0) { final String[] args2 = new String[args.length - 1]; System.arraycopy(args, 1, args2, 0, args.length - 1); if ("-rebuild".equals(args[0])) { XmlConfiguration.main(args2); } else if ("-oracle2xml".equals(args[0])) { Oracle2Xml.main(args2); } else if ("-batch".equals(args[0])) { if ("-server".equals(args[1])) { batchMode = BATCH_SERVER; } else if ("-client".equals(args[1])) { batchMode = BATCH_CLIENT; } } else { Log.error("Unknown options '" + Arrays.toString(args) + "'\nUsage : java -jar starter.jar <options>, where options are :\n" + "\t-rebuild -game <tbs name> [-x] [-d] [-v] [-h] [-f] [-n]\n" + "\t-oracle2xml -f <oracle file> -d <output directory> [-v] [-h]"); } System.exit(0); return; } if (batchMode == -1 && !"Mac OS X".equals(System.getProperty("os.name"))) { splash = new SplashScreen(MToolKit.getIconPath("splash.jpg"), null, 2000); } // language settings LanguageManager.initLanguageManager(Configuration.getString("language", "auto")); } catch (Throwable t) { Log.error("START-ERROR : \n\t" + t.getMessage()); System.exit(1); return; } Log.debug("MP Language : " + LanguageManager.getLanguage().getName()); speparateAvatar = Toolkit.getDefaultToolkit().getScreenSize().height > 768; // verify the java version, minimal is 1.5 if (new JavaVersion().compareTo(new JavaVersion(IdConst.MINIMAL_JRE)) == -1) { Log.error(LanguageManager.getString("wrongjava") + IdConst.MINIMAL_JRE); } // load look and feel settings lookAndFeelName = Configuration.getString("preferred", MUIManager.LF_SUBSTANCE_CLASSNAME); // try { // FileInputStream in= new FileInputStream("MAGIC.TTF"); // MToolKit.defaultFont= Font.createFont(Font.TRUETYPE_FONT, in); // in.close(); // MToolKit.defaultFont= MToolKit.defaultFont.deriveFont(Font.BOLD, 11); // } // catch (FileNotFoundException e) { // System.out.println("editorfont.ttf not found, using default."); // } // catch (Exception ex) { // ex.printStackTrace(); // } // Read available L&F final LinkedList<Pair<String, String>> lfList = new LinkedList<Pair<String, String>>(); try { BufferedReader buffReader = new BufferedReader( new InputStreamReader(MToolKit.getResourceAsStream(IdConst.FILE_THEME_SETTINGS))); String line; while ((line = buffReader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { final int index = line.indexOf(';'); if (index != -1) { lfList.add(new Pair<String, String>(line.substring(0, index), line.substring(index + 1))); } } } IOUtils.closeQuietly(buffReader); } catch (Throwable e) { // no place for resolve this problem Log.debug("Error reading L&F properties : " + e.getMessage()); } for (Pair<String, String> pair : lfList) { UIManager.installLookAndFeel(pair.key, pair.value); } // install L&F if (SkinLF.isSkinLF(lookAndFeelName)) { // is a SkinLF Look & Feel /* * Make sure we have a nice window decoration. */ SkinLF.installSkinLF(lookAndFeelName); } else { // is Metal Look & Feel if (!MToolKit.isAvailableLookAndFeel(lookAndFeelName)) { // preferred look&feel is not available JOptionPane.showMessageDialog(magicForm, LanguageManager.getString("preferredlfpb", lookAndFeelName), LanguageManager.getString("error"), JOptionPane.INFORMATION_MESSAGE); setDefaultUI(); } // Install the preferred LookAndFeel newLAF = MToolKit.geLookAndFeel(lookAndFeelName); frameDecorated = newLAF.getSupportsWindowDecorations(); /* * Make sure we have a nice window decoration. */ JFrame.setDefaultLookAndFeelDecorated(frameDecorated); JDialog.setDefaultLookAndFeelDecorated(frameDecorated); UIManager.setLookAndFeel(MToolKit.geLookAndFeel(lookAndFeelName)); } // Start main thread try { new Magic(); SwingUtilities.invokeLater(SkinLF.REFRESH_RUNNER); } catch (Throwable e) { Log.fatal("In main thread, occurred exception : ", e); ConnectionManager.closeConnexions(); return; } }
From source file:InlineSchemaValidator.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();/* w w w. j a v a2s . c o m*/ System.exit(1); } // variables Vector schemas = null; Vector instances = null; HashMap prefixMappings = null; HashMap uriMappings = null; String docURI = argv[argv.length - 1]; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; int repetition = DEFAULT_REPETITION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length - 1; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (arg.equals("-a")) { // process -a: xpath expressions for schemas if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: xpath expressions for instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-nm")) { String prefix; String uri; while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-") && !(uri = argv[i + 2]).startsWith("-")) { if (prefixMappings == null) { prefixMappings = new HashMap(); uriMappings = new HashMap(); } prefixMappings.put(prefix, uri); HashSet prefixes = (HashSet) uriMappings.get(uri); if (prefixes == null) { prefixes = new HashSet(); uriMappings.put(uri, prefixes); } prefixes.add(prefix); i += 2; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } try { // Create new instance of inline schema validator. InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings); // Parse document containing schemas and validation roots DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(inlineSchemaValidator); Document doc = db.parse(docURI); // Create XPath factory for selecting schema and validation roots XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(inlineSchemaValidator); // Select schema roots from the DOM NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0]; for (int i = 0; i < schemaNodes.length; ++i) { XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i)); schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET); } // Select validation roots from the DOM NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0]; for (int i = 0; i < instanceNodes.length; ++i) { XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i)); instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET); } // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(inlineSchemaValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; { DOMSource[] sources; int size = 0; for (int i = 0; i < schemaNodes.length; ++i) { size += schemaNodes[i].getLength(); } sources = new DOMSource[size]; if (size == 0) { schema = factory.newSchema(); } else { int count = 0; for (int i = 0; i < schemaNodes.length; ++i) { NodeList nodeList = schemaNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { sources[count++] = new DOMSource(nodeList.item(j)); } } schema = factory.newSchema(sources); } } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(inlineSchemaValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents for (int i = 0; i < instanceNodes.length; ++i) { NodeList nodeList = instanceNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { DOMSource source = new DOMSource(nodeList.item(j)); source.setSystemId(docURI); inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } }
From source file:Counter.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w w w .ja va 2 s . c o m*/ System.exit(1); } // variables Counter counter = new Counter(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; int repetition = DEFAULT_REPETITION; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; boolean memoryUsage = DEFAULT_MEMORY_USAGE; boolean tagginess = DEFAULT_TAGGINESS; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equalsIgnoreCase("t")) { tagginess = option.equals("t"); continue; } if (option.equals("-rem")) { if (++i == argv.length) { System.err.println("error: Missing argument to -# option."); continue; } System.out.print("# "); System.out.println(argv[i]); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // parse file parser.setContentHandler(counter); parser.setErrorHandler(counter); try { long timeBefore = System.currentTimeMillis(); long memoryBefore = Runtime.getRuntime().freeMemory(); for (int j = 0; j < repetition; j++) { parser.parse(arg); } long memoryAfter = Runtime.getRuntime().freeMemory(); long timeAfter = System.currentTimeMillis(); long time = timeAfter - timeBefore; long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE; counter.printResults(out, arg, time, memory, tagginess, repetition); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } }
From source file:net.sf.joost.Main.java
/** * Entry point//from w w w . j a v a 2s . com * @param args array of strings containing the parameter for Joost and * at least two URLs addressing xml-source and stx-sheet */ public static void main(String[] args) { // input filename String xmlFile = null; // the currently last processor (as XMLFilter) Processor processor = null; // output filename (optional) String outFile = null; // custom message emitter class name (optional) String meClassname = null; // log4j properties filename (optional) String log4jProperties = null; // log4j message level (this is an object of the class Level) Level log4jLevel = null; // set to true if a command line parameter was wrong boolean wrongParameter = false; // set to true if -help was specified on the command line boolean printHelp = false; // set to true if -pdf was specified on the command line boolean doFOP = false; // set to true if -nodecl was specified on the command line boolean nodecl = false; // set to true if -noext was specified on the command line boolean noext = false; // set to true if -doe was specified on the command line boolean doe = false; // debugging boolean dontexit = false; // timings boolean measureTime = false; long timeStart = 0, timeEnd = 0; // needed for evaluating parameter assignments int index; // serializer SAX -> XML text StreamEmitter emitter = null; // filenames for the usage and version info final String USAGE = "usage.txt", VERSION = "version.txt"; try { // parse command line argument list for (int i = 0; i < args.length; i++) { if (args[i].trim().length() == 0) { // empty parameter? ingore } // all options start with a '-', but a single '-' means stdin else if (args[i].charAt(0) == '-' && args[i].length() > 1) { if ("-help".equals(args[i])) { printHelp = true; continue; } else if ("-version".equals(args[i])) { printResource(VERSION); logInfoAndExit(); } else if ("-pdf".equals(args[i])) { doFOP = true; continue; } else if ("-nodecl".equals(args[i])) { nodecl = true; continue; } else if ("-noext".equals(args[i])) { noext = true; continue; } else if ("-doe".equals(args[i])) { doe = true; continue; } else if ("-wait".equals(args[i])) { dontexit = true; // undocumented continue; } else if ("-time".equals(args[i])) { measureTime = true; continue; } else if ("-o".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if (outFile != null) { System.err.println("Option -o already specified with " + outFile); wrongParameter = true; } else outFile = args[i]; continue; } else { if (outFile != null) System.err.println("Option -o already specified with " + outFile); else System.err.println("Option -o requires a filename"); i--; wrongParameter = true; } } else if ("-m".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if (meClassname != null) { System.err.println("Option -m already specified with " + meClassname); wrongParameter = true; } else meClassname = args[i]; continue; } else { if (meClassname != null) System.err.println("Option -m already specified with " + meClassname); else System.err.println("Option -m requires a classname"); i--; wrongParameter = true; } } else if (DEBUG && "-log-properties".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { log4jProperties = args[i]; continue; } else { System.err.println("Option -log-properties requires " + "a filename"); wrongParameter = true; } } else if (DEBUG && "-log-level".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if ("off".equals(args[i])) { log4jLevel = Level.OFF; continue; } else if ("debug".equals(args[i])) { log4jLevel = Level.DEBUG; continue; } else if ("info".equals(args[i])) { log4jLevel = Level.INFO; continue; } else if ("warn".equals(args[i])) { log4jLevel = Level.WARN; continue; } else if ("error".equals(args[i])) { log4jLevel = Level.ERROR; continue; } else if ("fatal".equals(args[i])) { log4jLevel = Level.FATAL; continue; } else if ("all".equals(args[i])) { log4jLevel = Level.ALL; continue; } else { System.err.println("Unknown parameter for -log-level: " + args[i]); wrongParameter = true; continue; } } else { System.err.println("Option -log-level requires a " + "parameter"); wrongParameter = true; } } else { System.err.println("Unknown option " + args[i]); wrongParameter = true; } } // command line argument is not an option with a leading '-' else if ((index = args[i].indexOf('=')) != -1) { // parameter assignment if (processor != null) processor.setParameter(args[i].substring(0, index), args[i].substring(index + 1)); else { System.err.println("Assignment " + args[i] + " must follow an stx-sheet parameter"); wrongParameter = true; } continue; } else if (xmlFile == null) { xmlFile = args[i]; continue; } else { // xmlFile != null, i.e. this is an STX sheet ParseContext pContext = new ParseContext(); pContext.allowExternalFunctions = !noext; if (measureTime) timeStart = System.currentTimeMillis(); Processor proc = new Processor(new InputSource(args[i]), pContext); if (nodecl) proc.outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); if (measureTime) { timeEnd = System.currentTimeMillis(); System.err.println("Parsing " + args[i] + ": " + (timeEnd - timeStart) + " ms"); } if (processor != null) proc.setParent(processor); // XMLFilter chain processor = proc; } } // PDF creation requested if (doFOP && outFile == null) { System.err.println("Option -pdf requires option -o"); wrongParameter = true; } // missing filenames if (!printHelp && processor == null) { if (xmlFile == null) System.err.println("Missing filenames for XML source and " + "STX transformation sheet"); else System.err.println("Missing filename for STX transformation " + "sheet"); wrongParameter = true; } if (meClassname != null && !wrongParameter) { // create object StxEmitter messageEmitter = null; try { messageEmitter = (StxEmitter) Class.forName(meClassname).newInstance(); } catch (ClassNotFoundException ex) { System.err.println("Class not found: " + ex.getMessage()); wrongParameter = true; } catch (InstantiationException ex) { System.err.println("Instantiation failed: " + ex.getMessage()); wrongParameter = true; } catch (IllegalAccessException ex) { System.err.println("Illegal access: " + ex.getMessage()); wrongParameter = true; } catch (ClassCastException ex) { System.err.println( "Wrong message emitter: " + meClassname + " doesn't implement the " + StxEmitter.class); wrongParameter = true; } if (messageEmitter != null) { // i.e. no exception occurred // set message emitter for all processors in the filter chain Processor p = processor; do { p.setMessageEmitter(messageEmitter); Object o = p.getParent(); if (o instanceof Processor) p = (Processor) o; else p = null; } while (p != null); } } if (printHelp) { printResource(VERSION); printResource(USAGE); logInfoAndExit(); } if (wrongParameter) { System.err.println("Specify -help to get a detailed help message"); System.exit(1); } if (DEBUG) { // use specified log4j properties file if (log4jProperties != null) PropertyConfigurator.configure(log4jProperties); // set log level specified on the the command line if (log4jLevel != null) Logger.getRootLogger().setLevel(log4jLevel); } // The first processor re-uses its XMLReader for parsing the input // xmlFile. // For a real XMLFilter usage you have to call // processor.setParent(yourXMLReader) // Connect a SAX consumer if (doFOP) { // pass output events to FOP // // Version 1: use a FOPEmitter object as XMLFilter // processor.setContentHandler( // new FOPEmitter( // new java.io.FileOutputStream(outFile))); // Version 2: use a static method to retrieve FOP's content // handler and use it directly processor.setContentHandler(FOPEmitter.getFOPContentHandler(new java.io.FileOutputStream(outFile))); } else { // Create XML output if (outFile != null) { emitter = StreamEmitter.newEmitter(outFile, processor.outputProperties); emitter.setSystemId(new File(outFile).toURI().toString()); } else emitter = StreamEmitter.newEmitter(System.out, processor.outputProperties); processor.setContentHandler(emitter); processor.setLexicalHandler(emitter); // the previous line is a short-cut for // processor.setProperty( // "http://xml.org/sax/properties/lexical-handler", emitter); emitter.setSupportDisableOutputEscaping(doe); } InputSource is; if (xmlFile.equals("-")) { is = new InputSource(System.in); is.setSystemId("<stdin>"); is.setPublicId(""); } else is = new InputSource(xmlFile); // Ready for take-off if (measureTime) timeStart = System.currentTimeMillis(); processor.parse(is); if (measureTime) { timeEnd = System.currentTimeMillis(); System.err.println("Processing " + xmlFile + ": " + (timeEnd - timeStart) + " ms"); } // // check if the Processor copy constructor works // Processor pr = new Processor(processor); // java.util.Properties props = new java.util.Properties(); // props.put("encoding", "ISO-8859-2"); // StreamEmitter em = // StreamEmitter.newEmitter(System.err, props); // pr.setContentHandler(em); // pr.setLexicalHandler(em); // pr.parse(is); // // end check // this is for debugging with the Java Memory Profiler if (dontexit) { System.err.println("Press Enter to exit"); System.in.read(); } } catch (java.io.IOException ex) { System.err.println(ex.toString()); System.exit(1); } catch (SAXException ex) { if (emitter != null) { try { // flushes the internal BufferedWriter, i.e. outputs // the intermediate result emitter.endDocument(); } catch (SAXException exx) { // ignore } } Exception embedded = ex.getException(); if (embedded != null) { if (embedded instanceof TransformerException) { TransformerException te = (TransformerException) embedded; SourceLocator sl = te.getLocator(); String systemId; // ensure that systemId is not null; is this a bug? if (sl != null && (systemId = sl.getSystemId()) != null) { // remove the "file://" scheme prefix if it is present if (systemId.startsWith("file://")) systemId = systemId.substring(7); else if (systemId.startsWith("file:")) // bug in JDK 1.4 / Crimson? (see rfc1738) systemId = systemId.substring(5); System.err.println(systemId + ":" + sl.getLineNumber() + ":" + sl.getColumnNumber() + ": " + te.getMessage()); } else System.err.println(te.getMessage()); } else { // Fatal: this mustn't happen embedded.printStackTrace(System.err); } } else System.err.println(ex.toString()); System.exit(1); } }
From source file:com.wolfsoftco.httpclient.RestClient.java
@SuppressWarnings("resource") public static void main(String[] args) { CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {/*from w w w . ja v a 2 s . co m*/ HttpEntity entity = null; String responseHtml = null; httpclient = HttpClients.custom().build(); //Based on CURL line: //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar //clientid:secret String clientID = "foo:bar"; HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL)) .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes())) .addParameter("grant_type", "password").addParameter("scope", "read") .addParameter("username", "greg").addParameter("password", "turnquist").build(); response = httpclient.execute(login); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); JsonObject jsonObject = null; String token = null; if (responseHtml.startsWith("{")) { JsonParser parser = new JsonParser(); jsonObject = parser.parse(responseHtml).getAsJsonObject(); token = jsonObject.get("access_token").getAsString(); } if (token != null) { HttpGet request = new HttpGet(URL_FLIGHTS); request.addHeader("Authorization", "Bearer " + token); response = httpclient.execute(request); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); System.out.println(responseHtml); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (httpclient != null) httpclient.close(); if (response != null) response.close(); } catch (IOException e) { } } }
From source file:DIA_Umpire_Quant.DIA_Umpire_ExtLibSearch.java
/** * @param args the command line arguments *///from w ww .ja va 2 s .co m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using external library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_ExtLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_extlibsearch.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String ExternalLibPath = ""; String ExternalLibDecoyTag = "DECOY"; float ExtProbThreshold = 0.99f; float RTWindow_Ext = -1f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "ExternalLibPath": { ExternalLibPath = value; break; } case "ExtProbThreshold": { ExtProbThreshold = Float.parseFloat(value); break; } case "RTWindow_Ext": { RTWindow_Ext = Float.parseFloat(value); break; } case "ExternalLibDecoyTag": { ExternalLibDecoyTag = value; if (ExternalLibDecoyTag.endsWith("_")) { ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0, ExternalLibDecoyTag.length() - 1); } break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library"> //External library search Logger.getRootLogger().info("Targeted extraction using external library"); //Read exteranl library FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, FilenameUtils.getBaseName(ExternalLibPath)); if (ExlibManager == null) { ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath)); //Import traML file ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag); //Check if there are decoy spectra ExlibManager.CheckDecoys(); //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath); ExlibManager.WriteFragmentLibSerialization(WorkFolder); } Logger.getRootLogger() .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size()); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } //Generate RT mapping RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager, diafile.GetParameter()); RTmap.GenerateModel(); RTmap.GenerateMappedPepIon(); diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.GenerateMassCalibrationRTMap(); //Perform targeted re-extraction diafile.TargetedExtractionQuant(false, ExlibManager, ExtProbThreshold, RTWindow_Ext); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); //Remove target IDs below the defined probability threshold diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold); diafile.ExportID(); diafile.ClearStructure(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); }
From source file:DIA_Umpire_Quant.DIA_Umpire_IntLibSearch.java
/** * @param args the command line arguments *//*ww w . j av a 2s.c om*/ public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using internal library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be : java -jar -Xmx10G DIA_Umpire_IntLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_intlibsearch.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String InternalLibID = ""; float ProbThreshold = 0.99f; float RTWindow_Int = -1f; float Freq = 0f; int TopNFrag = 6; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "InternalLibID": { InternalLibID = value; break; } case "RTWindow_Int": { RTWindow_Int = Float.parseFloat(value); break; } case "ProbThreshold": { ProbThreshold = Float.parseFloat(value); break; } case "TopNFrag": { TopNFrag = Integer.parseInt(value); break; } case "Freq": { Freq = Float.parseFloat(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); try { File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library"> Logger.getRootLogger().info( "================================================================================================="); if (FileList.size() > 1) { Logger.getRootLogger().info("Targeted re-extraction using internal library"); FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, InternalLibID); if (libManager == null) { Logger.getRootLogger().info("Building internal spectral library"); libManager = new FragmentLibManager(InternalLibID); ArrayList<LCMSID> LCMSIDList = new ArrayList<>(); for (DIAPack dia : FileList) { LCMSIDList.add(dia.IDsummary); } libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag); libManager.WriteFragmentLibSerialization(WorkFolder); } libManager.ReduceMemoryUsage(); Logger.getRootLogger() .info("Building retention time prediction model and generate candidate peptide list"); for (int i = 0; i < FileList.size(); i++) { FileList.get(i).IDsummary.ClearMappedPep(); } for (int i = 0; i < FileList.size(); i++) { for (int j = i + 1; j < FileList.size(); j++) { RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder, FileList.get(i).GetParameter(), FileList.get(i).IDsummary, FileList.get(j).IDsummary); alignment.GenerateModel(); alignment.GenerateMappedPepIon(); } FileList.get(i).ExportID(); FileList.get(i).IDsummary = null; } Logger.getRootLogger().info("Targeted matching........"); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) { diafile.UseMappedIon = true; diafile.FilterMappedIonByProb = false; diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); diafile.GenerateMassCalibrationRTMap(); diafile.TargetedExtractionQuant(false, libManager, ProbThreshold, RTWindow_Int); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold); diafile.ExportID(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); diafile.ClearStructure(); } diafile.IDsummary = null; System.gc(); } Logger.getRootLogger().info( "================================================================================================="); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:com.entertailion.java.caster.Main.java
/** * @param args/*ww w . j a v a 2 s .c o m*/ */ public static void main(String[] args) { // http://commons.apache.org/proper/commons-cli/usage.html Option help = new Option("h", "help", false, "Print this help message"); Option version = new Option("V", "version", false, "Print version information"); Option list = new Option("l", "list", false, "List ChromeCast devices"); Option verbose = new Option("v", "verbose", false, "Verbose debug logging"); Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required"); Option rest = new Option("r", "rest", false, "REST API server"); Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator() .withDescription("HTTP URL for streaming content; -d also required").create("s"); Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator() .withDescription("ChromeCast device IP address").create("d"); Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator() .withDescription("App ID for whitelisted device").create("id"); Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator() .withDescription("Local media file; -d also required").create("f"); Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg() .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp"); Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator() .withDescription("REST API port; default 8080").create("rp"); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(list); options.addOption(verbose); options.addOption(url); options.addOption(server); options.addOption(id); options.addOption(mediaFile); options.addOption(transcode); options.addOption(transcodingParameters); options.addOption(rest); options.addOption(restPort); // create the command line parser CommandLineParser parser = new PosixParser(); //String[] arguments = new String[] { "-vr" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); Option[] lineOptions = line.getOptions(); if (lineOptions.length == 0) { System.out.println("caster: try 'java -jar caster.jar -h' for more information"); System.exit(0); } Log.setVerbose(line.hasOption("v")); // Custom app-id if (line.hasOption("id")) { Log.d(LOG_TAG, line.getOptionValue("id")); appId = line.getOptionValue("id"); } // Print version if (line.hasOption("V")) { System.out.println("Caster version " + VERSION); } // List ChromeCast devices if (line.hasOption("l")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { System.out.println(dialServer.toString()); // keep system for output } } }); deviceFinder.discoverDevices(); } // Stream media from internet if (line.hasOption("s") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("s")); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(line.getOptionValue("d"))), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); playback.stream(line.getOptionValue("s")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // Play local media file if (line.hasOption("f") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("f")); final String file = line.getOptionValue("f"); String device = line.getOptionValue("d"); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); if (line.hasOption("t") && line.hasOption("tp")) { playback.setTranscodingParameters(line.getOptionValue("tp")); } playback.play(file, line.hasOption("t")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // REST API server if (line.hasOption("r")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { Log.d(LOG_TAG, dialServer.toString()); } } }); deviceFinder.discoverDevices(); int port = 0; if (line.hasOption("rp")) { try { port = Integer.parseInt(line.getOptionValue("rp")); } catch (NumberFormatException e) { Log.e(LOG_TAG, "invalid rest port", e); } } Playback.startWebserver(port, new WebListener() { String[] prefixes = { "/playback", "/devices" }; HashMap<String, Playback> playbackMap = new HashMap<String, Playback>(); HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>(); final class RestPlaybackListener implements PlaybackListener { private String device; private int time; private int duration; private int state; public RestPlaybackListener(String device) { this.device = device; } @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); this.state = state; // Stop the app if the video reaches the end if (this.time > 0 && this.time == this.duration && state == 0) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } } @Override public Response handleRequest(String uri, String method, Properties header, Properties parms) { Log.d(LOG_TAG, "handleRequest: " + uri); if (method.equals("GET")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { RestPlaybackListener playbackListener = playbackListenerMap.get(device); if (playbackListener != null) { // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONObject obj = new JSONObject(); obj.put("time", playbackListener.getTime()); obj.put("duration", playbackListener.getDuration()); switch (playbackListener.getState()) { case 0: obj.put("state", "idle"); break; case 1: obj.put("state", "stopped"); break; case 2: obj.put("state", "playing"); break; default: obj.put("state", "idle"); break; } return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } else { // Nothing is playing JSONObject obj = new JSONObject(); obj.put("time", 0); obj.put("duration", 0); obj.put("state", "stopped"); return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } } } else if (uri.startsWith(prefixes[1])) { // devices // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONArray list = new JSONArray(); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { JSONObject obj = new JSONObject(); obj.put("name", dialServer.getFriendlyName()); obj.put("ip_address", dialServer.getIpAddress().getHostAddress()); list.add(obj); } return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString()); } } else if (method.equals("POST")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { String stream = parms.getProperty("stream"); String file = parms.getProperty("file"); String state = parms.getProperty("state"); String transcode = parms.getProperty("transcode"); String transcodeParameters = parms.getProperty("transcode-parameters"); Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters); if (stream != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { playback.stream(stream); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (file != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (transcodeParameters != null) { playback.setTranscodingParameters(transcodeParameters); } if (playback != null) { playback.play(file, transcode != null); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (state != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { // Handle case where current app wasn't started with caster playback.setDialServer(deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device))); // Change the playback state if (state.equals("play")) { playback.doPlay(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("pause")) { playback.doPause(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("stop")) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else { Log.e(LOG_TAG, "playback invalid state: " + state); } } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } } } } return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request"); } @Override public String[] uriPrefixes() { return prefixes; } }); Log.d(LOG_TAG, "REST server ready"); // Run forever... while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } // Print help if (line.hasOption("h")) { printHelp(options); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.out.println(); printHelp(options); } }