List of usage examples for java.util Scanner next
public String next()
From source file:org.apache.tomcat.vault.VaultTool.java
public static void main(String[] args) { VaultTool tool = null;/*from www . j a v a 2 s. c om*/ if (args != null && args.length > 0) { int returnVal = 0; try { tool = new VaultTool(args); returnVal = tool.execute(); if (!skipSummary) { tool.summary(); } } catch (Exception e) { System.err.println("Problem occured:"); System.err.println(e.getMessage()); System.exit(1); } System.exit(returnVal); } else { tool = new VaultTool(); Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } Scanner in = new Scanner(System.in); while (true) { String commandStr = "Please enter a Digit:: 0: Start Interactive Session " + " 1: Remove Interactive Session " + " Other: Exit"; System.out.println(commandStr); int choice = -1; try { choice = in.nextInt(); } catch (InputMismatchException e) { System.err.println("'" + in.next() + "' is not a digit. Restart and enter a digit."); System.exit(3); } switch (choice) { case 0: System.out.println("Starting an interactive session"); VaultInteractiveSession vsession = new VaultInteractiveSession(); tool.setSession(vsession); vsession.start(); break; case 1: System.out.println("Removing the current interactive session"); tool.setSession(null); break; default: System.exit(0); } } } }
From source file:Clima.Clima.java
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Scanner lea = new Scanner(System.in); int op;/*w ww .j a v a 2 s .c o m*/ do { System.out.println("----------\nMENU\n-----------"); System.out.println("1- Ver todos los datos clima"); System.out.println("2- Ver longuitud y Latitud"); System.out.println("3- Temperatura minima y maxima"); System.out.println("4- Humedad y Velocidad"); System.out.println("Escoja Opcion: "); op = lea.nextInt(); System.out.println("------------------------------------"); System.out.println("Ingrase la ciudad que decea ver clima"); System.out.println("-------------------------------------"); String cuida = lea.next(); System.out.println("--------------------------------------"); switch (op) { case 1: try { String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55"); JSONObject obj = new JSONObject(respuesta); double temp = obj.getJSONObject("main").getDouble("temp") - 273.15; double lon = obj.getJSONObject("coord").getDouble("lon"); double lat = obj.getJSONObject("coord").getDouble("lat"); double pressure = obj.getJSONObject("main").getDouble("pressure"); double humidity = obj.getJSONObject("main").getDouble("humidity"); double temp_min = obj.getJSONObject("main").getDouble("temp_min") - 273.15; double temp_max = obj.getJSONObject("main").getDouble("temp_max") - 273.15; double speed = obj.getJSONObject("wind").getDouble("speed"); System.out.println("Los datos optenidos de " + cuida); System.out.println("***************************************1"); System.out.println("La temperatura es: " + temp + " Celsius"); System.out.println("longuitud es: " + lon); System.out.println("Latitud es: " + lat); System.out.println("La presurisacion es: " + pressure); System.out.println("La humedad es: " + humidity); System.out.println("La temperatura minima es: " + temp_min + " Celsius"); System.out.println("La temperatura maxima es: " + temp_max + " Celsius"); System.out.println("La velocidad es: " + speed); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Clima.main(null); break; case 2: try { String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55"); JSONObject obj = new JSONObject(respuesta); double lon = obj.getJSONObject("coord").getDouble("lon"); double lat = obj.getJSONObject("coord").getDouble("lat"); System.out.println("Los datos optenidos de" + cuida + "son:"); System.out.print("longuitud es: " + lon); System.out.print("Latitud es: " + lat); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Clima.main(null); break; case 3: try { String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55"); JSONObject obj = new JSONObject(respuesta); double temp_min = obj.getJSONObject("main").getDouble("temp_min") - 273.15; double temp_max = obj.getJSONObject("main").getDouble("temp_max") - 273.15; System.out.println("Los datos optenidos de" + cuida + "son:"); System.out.print("La temperatura minima es: " + temp_min + " Celsius"); System.out.print("La temperatura maxima es: " + temp_max + " Celsius"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Clima.main(null); break; case 4: try { String respuesta = getHTML("http://api.openweathermap.org/data/2.5/weather?q=" + cuida + ",uk&appid=edf6a6fe68ae2a1259efacb437914a55"); JSONObject obj = new JSONObject(respuesta); double humidity = obj.getJSONObject("main").getDouble("humidity"); double speed = obj.getJSONObject("wind").getDouble("speed"); System.out.println("Los datos optenidos de" + cuida + "son:"); System.out.print("La humedad es: " + humidity); System.out.print("La velocidad es: " + speed); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Clima.main(null); break; } } while (op != 8); }
From source file:org.scify.NewSumServer.Server.Utils.Main.java
public static void main(String[] args) throws FeedParserException, NetworkException, IOException { //initialize logger Handler h;//from w w w .jav a 2 s. c o m try { h = new FileHandler(sLogFile); SimpleFormatter f = new SimpleFormatter(); h.setFormatter(f); LOGGER.addHandler(h); LOGGER.setLevel(Level.FINE); } catch (IOException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } catch (SecurityException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } //program info System.out.print("NewSumServer Switches:\n\n" + "-BaseDir: The full path to the folder where the storage module stores data\n" + "-PathToSources: The file named RSSSources.txt with it's full path\n" + "\t(e.g. /home/pathtosources/RSSSources.txt)\n" + "-indexPath: The full path to the folder where the Indexer Class stores data\n" + "-SummaryPath: The full path to the folder where the Summarisation package stores data\n" + "-ArticlePath: The full path to the folder where the " + "Summarisation package stores the Clustered Articles\n" + "-ToolPath: The full path to the folder for misc Tools\n" + "-iOutputSize: The max number of Sentences the Summariser prints\n" + "-ArticleMaxDays: The Number of Max Days to Accept an article (until now)\n" + "-useInputDirData: true or false, defaults to false\n" + "-DebugRun: true if you want to run with category switching (for quicker runs)\n\n" + "Example Usage: java -jar NewSumServer.jar -BaseDir=./data/Dir -iOutputSize=50\n\n"); //Parse and check Command Line arguments parseCommandLine(args); //Write Configuration file so that NewSumFreeService reads statics writeConfigFile(); // check if splitterTraining file was changed since the previous run if (SplitterTrainingFileChanged()) { // if so, delete the Model file, in order to get recreated with the new data File sDat = new File(sToolPath + "splitModel.dat"); try { sDat.delete(); LOGGER.log(Level.INFO, "deleted {0} cause splitterTrainer was updated", sDat.toString()); } catch (Exception ex) { LOGGER.log(Level.WARNING, "Could not delete {0}, although file Was Changed. " + "Please do it manually", sDat.toString()); } } //init data storage IDataStorage ids = new InsectFileIO(sBaseDir); // justWaitABit(50000); //init rssSources RSSSources r = new RSSSources(sPathToSources); // initialize sources: read the sources file r.initialize(ids); //get the sources HashMap<String, String> Sources = r.getRssLinks();//link,category //get categories Collection<String> sCategories = r.getCategories(); // TODO: Ignore UNCLASSIFIED CATEGORY ArrayList<String> lCategories = new ArrayList<String>(sCategories); //init rssparser ISourceParser isp = new RssParser(ids, iArticleDays); //DEBUG LINES //get user input List al = new ArrayList(sCategories); ArrayList<String> subSources = null; ArrayList<Article> Articles = new ArrayList<Article>(); String sCurCateg = "0"; if (bDebugRun) { // if only one category needed (quick run) System.out.println("Choose Category by number: \nIf -1, all categories are loaded"); for (int i = 0; i < lCategories.size(); i++) { System.out.println(String.valueOf(i) + ": " + lCategories.get(i)); } Scanner user_input = new Scanner(System.in); sCurCateg = user_input.next(); ///////////// if (Integer.valueOf(sCurCateg) != -1) { subSources = new ArrayList<String>((HashSet<String>) Utilities.getKeysByValue(Sources, (String) al.get(Integer.valueOf(sCurCateg)))); //accept all articles from each category Articles = (ArrayList<Article>) isp.getAllNewsByCategory(subSources, (String) al.get(Integer.valueOf(sCurCateg))); } else if (Integer.valueOf(sCurCateg) == -1) { //get all articles Articles = (ArrayList<Article>) isp.getAllArticles(Sources); } } else { //if all categories by default (no user choosing - normal mode) Articles = (ArrayList<Article>) isp.getAllArticles(Sources); } // check for spam sentences Utilities.checkForPossibleSpam(Articles); //Save Article List to Drive, so that the clusterer loads it isp.saveAllArticles(); //Name: "AllArticles", Category: "feeds" // ArticleClusterer ac = new ArticleClusterer(subArticles, ids, sArticlePath); //get least occurencies of articles // threshold = Utilities.getLeastOccurencies(Articles); // //Train Classification Module // clm = new classificationModule(); // // // //initialize Distribution category set // Distribution<String> dArticleCategory = new Distribution<String>(); // // for (int i = 0; i < Articles.size(); i++) { // if (Articles.get(i).getToWrap()) { // boolean mergeGraph = true; // //increase Distribution set 1.0 // dArticleCategory.increaseValue(Articles.get(i).getCategory(), 1.0); // //check threshold // double dInstanceCount = dArticleCategory.getValue(Articles.get(i).getCategory()); // if (dInstanceCount < threshold) { // // //check mergeGraph threshold --> threshold/2 turn mergeGraph from true to false // if (dInstanceCount > (threshold / 2)) { // mergeGraph = false; // } // clm.feedClassifier(Articles.get(i).getCategory(), Articles.get(i).getText(), mergeGraph); // } // // } // } // Initialize Clusterer ArticleClusterer ac; ac = new ArticleClusterer((ArrayList<Article>) ids.loadObject("AllArticles", "feeds"), ids, sArticlePath); // Perform clustering calculations ac.calculateClusters(NVSThreshold, SSThreshold); //specify the locale for the indexer Locale loc = sPathToSources.endsWith("GR.txt") ? new Locale("el") : new Locale("en"); // Create a new indexer Indexer ind = new Indexer(sArticlePath, sindexPath, loc); // Create the Index try { ind.createIndex(); } catch (CorruptIndexException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } catch (LockObtainFailedException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } catch (IOException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } // Init the summarizer and obtain summaries INSECTDB idb = new INSECTFileDB("", sSummaryPath); Summariser sum = new Summariser(new HashSet<Topic>(ac.getArticlesPerCluster().values()), idb); // Perform summarization for all clusters Map<String, List<Sentence>> AllSummaries; AllSummaries = sum.getSummaries(); // DEBUG // store summaries // for (Map.Entry mp : AllSummaries.entrySet()) { // String sUID = (String) mp.getKey(); // List<Sentence> lsSen = (List<Sentence>) mp.getValue(); // if (getNumberOfSources(lsSen) > 1) { // writeSummaryToFile(lsSen, sUID, ac.getArticlesPerCluster()); // } // } // DEBUG // if (bDebugRun) { // DEBUG LINES // Delete files in "data/txtSummaries" and write all the summaries extracted File f = new File(sTxtSumPath); if (f.exists()) { for (File k : f.listFiles()) { k.delete(); } } for (Map.Entry mp : AllSummaries.entrySet()) { String sUID = (String) mp.getKey(); List<Sentence> lsSen = (List<Sentence>) mp.getValue(); if (getNumberOfSources(lsSen) > 1) { writeSummaryToFile(lsSen, sUID, ac.getArticlesPerCluster()); } } // debug communicator Communicator cm = new Communicator(ids, ac, sum, ind); int bb = Integer.valueOf(sCurCateg); if (bb == -1) { bb = 0; } // print summary from communicator int iSummarizedClusterCnt = 0; for (Topic tTopic : ac.getArticlesPerCluster().values()) { if (tTopic.size() > 1) { System.out.println("Printing summary for topic: " + tTopic.getTitle()); String[] eachSnippet = cm.getSummary(tTopic.getID(), "All").split(cm.getFirstLevelSeparator()); int iAllTmpSourcesCount = eachSnippet[0].split(cm.getSecondLevelSeparator()).length; System.out.println("With Summary Sources: " + iAllTmpSourcesCount); for (int i = 1; i < eachSnippet.length; i++) { String[] eachSent = eachSnippet[i].split(cm.getSecondLevelSeparator()); System.out.println(eachSent[0]); System.out.println("-----------------------------------"); iSummarizedClusterCnt++; } System.out.println("==========================="); } } } //DEBUG LINES //get user input // System.out.println("Enter Search String\n"); // Scanner imp = new Scanner(System.in); // String term = imp.next(); // // String sTop = cm.getTopicIDsByKeyword(ind, term, "All"); // System.out.println(sTop); // System.out.println(cm.getTopicTitlesByIDs(sTop)); // last debug // String sUserSources = "http://rss.in.gr/feed/news/culture/" + // "http://www.tovima.gr/feed/culture/" + // "http://www.naftemporiki.gr/rssFeed?mode=section&id=6&atype=story"; // System.out.println(cm.getTopics(sUserSources, (String) al.get(bb))); // System.out.println(cm.getTopics("All", (String) al.get(bb))); // last debug // System.out.println("Found a total of " + iSummarizedClusterCnt + " summaries" // + " from more than one texts."); // System.out.println(cm.getTopicIDs("All", (String) al.get(bb))); // System.out.println("===============printing topic titles"); // System.out.println(cm.getTopicTitles("All", (String) al.get(bb))); // System.out.println("===============ending printing topic titles"); // String sUserSources = "http://rss.in.gr/feed/news/world/;;;" // + "http://www.naftemporiki.gr/news/static/rss/news_pol_pol-world.xml;;;" // + "http://ws.kathimerini.gr/xml_files/worldnews.xml;;;" // + "http://feeds.feedburner.com/skai/aqOL?format=xml"; // System.out.println(cm.getTopicIDs(sUserSources, (String) al.get(bb))); // System.out.println(cm.getTopicTitles(sUserSources, (String) al.get(bb))); // int counter = 0; // for (Topic tTopic : ac.getArticlesPerCluster().values()) { // System.out.println("===================="); // System.out.println(cm.getSummary(tTopic.getID(), sUserSources)); // counter ++; // if (counter == 3) { // break; // } // } }
From source file:org.b3log.latke.client.LatkeClient.java
/** * Main entry./* w w w . j a v a2s . co m*/ * * @param args the specified command line arguments * @throws Exception exception */ public static void main(String[] args) throws Exception { // Backup Test: // args = new String[] { // "-h", "-backup", "-repository_names", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir", // "C:/b3log_backup", "-w", "true"}; // args = new String[] { // "-h", "-restore", "-create_tables", "-verbose", "-s", "localhost:8080", "-u", "xxx", "-p", "xxx", "-backup_dir", // "C:/b3log_backup"}; final Options options = getOptions(); final CommandLineParser parser = new PosixParser(); try { final CommandLine cmd = parser.parse(options, args); serverAddress = cmd.getOptionValue("s"); backupDir = new File(cmd.getOptionValue("backup_dir")); if (!backupDir.exists()) { backupDir.mkdir(); } userName = cmd.getOptionValue("u"); if (cmd.hasOption("verbose")) { verbose = true; } password = cmd.getOptionValue("p"); if (verbose) { System.out.println("Requesting server[" + serverAddress + "]"); } final HttpClient httpClient = new DefaultHttpClient(); if (cmd.hasOption("repository_names")) { getRepositoryNames(); } if (cmd.hasOption("create_tables")) { final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName", userName)); qparams.add(new BasicNameValuePair("password", password)); final URI uri = URIUtils.createURI("http", serverAddress, -1, CREATE_TABLES, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpPut request = new HttpPut(); request.setURI(uri); if (verbose) { System.out.println("Starting create tables"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } } if (cmd.hasOption("w")) { final String writable = cmd.getOptionValue("w"); final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName", userName)); qparams.add(new BasicNameValuePair("password", password)); qparams.add(new BasicNameValuePair("writable", writable)); final URI uri = URIUtils.createURI("http", serverAddress, -1, SET_REPOSITORIES_WRITABLE, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpPut request = new HttpPut(); request.setURI(uri); if (verbose) { System.out.println("Setting repository writable[" + writable + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } } if (cmd.hasOption("backup")) { System.out.println("Make sure you have disabled repository writes with [-w false], continue? (y)"); final Scanner scanner = new Scanner(System.in); final String input = scanner.next(); scanner.close(); if (!"y".equals(input)) { return; } if (verbose) { System.out.println("Starting backup data"); } final Set<String> repositoryNames = getRepositoryNames(); for (final String repositoryName : repositoryNames) { // You could specify repository manually // if (!"archiveDate_article".equals(repositoryName)) { // continue; // } int requestPageNum = 1; // Backup interrupt recovery final List<File> backupFiles = getBackupFiles(repositoryName); if (!backupFiles.isEmpty()) { final File latestBackup = backupFiles.get(backupFiles.size() - 1); final String latestPageSize = getBackupFileNameField(latestBackup.getName(), "${pageSize}"); if (!PAGE_SIZE.equals(latestPageSize)) { // The 'latestPageSize' should be less or equal to 'PAGE_SIZE', if they are not the same that indicates // the latest backup file is the last of this repository, the repository backup had completed if (verbose) { System.out.println("Repository [" + repositoryName + "] backup have completed"); } continue; } final String latestPageNum = getBackupFileNameField(latestBackup.getName(), "${pageNum}"); // Prepare for the next page to request requestPageNum = Integer.parseInt(latestPageNum) + 1; if (verbose) { System.out.println( "Start tot backup interrupt recovery [pageNum=" + requestPageNum + "]"); } } int totalPageCount = requestPageNum + 1; for (; requestPageNum <= totalPageCount; requestPageNum++) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userName", userName)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("repositoryName", repositoryName)); params.add(new BasicNameValuePair("pageNum", String.valueOf(requestPageNum))); params.add(new BasicNameValuePair("pageSize", PAGE_SIZE)); final URI uri = URIUtils.createURI("http", serverAddress, -1, GET_DATA, URLEncodedUtils.format(params, "UTF-8"), null); final HttpGet request = new HttpGet(uri); if (verbose) { System.out.println("Getting data from repository [" + repositoryName + "] with pagination [pageNum=" + requestPageNum + ", pageSize=" + PAGE_SIZE + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream, "UTF-8").trim(); contentStream.close(); if (verbose) { printResponse(content); } final JSONObject resp = new JSONObject(content); final JSONObject pagination = resp.getJSONObject("pagination"); totalPageCount = pagination.getInt("paginationPageCount"); final JSONArray results = resp.getJSONArray("rslts"); final String backupPath = backupDir.getPath() + File.separatorChar + repositoryName + File.separatorChar + requestPageNum + '_' + results.length() + '_' + System.currentTimeMillis() + ".json"; final File backup = new File(backupPath); final FileWriter fileWriter = new FileWriter(backup); IOUtils.write(results.toString(), fileWriter); fileWriter.close(); if (verbose) { System.out.println("Backup file[path=" + backupPath + "]"); } } } } if (cmd.hasOption("restore")) { System.out.println("Make sure you have enabled repository writes with [-w true], continue? (y)"); final Scanner scanner = new Scanner(System.in); final String input = scanner.next(); scanner.close(); if (!"y".equals(input)) { return; } if (verbose) { System.out.println("Starting restore data"); } final Set<String> repositoryNames = getRepositoryNamesFromBackupDir(); for (final String repositoryName : repositoryNames) { // You could specify repository manually // if (!"archiveDate_article".equals(repositoryName)) { // continue; // } final List<File> backupFiles = getBackupFiles(repositoryName); if (verbose) { System.out.println("Restoring repository[" + repositoryName + ']'); } for (final File backupFile : backupFiles) { final FileReader backupFileReader = new FileReader(backupFile); final String dataContent = IOUtils.toString(backupFileReader); backupFileReader.close(); final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("userName", userName)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("repositoryName", repositoryName)); final URI uri = URIUtils.createURI("http", serverAddress, -1, PUT_DATA, URLEncodedUtils.format(params, "UTF-8"), null); final HttpPost request = new HttpPost(uri); final List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("data", dataContent)); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8"); request.setEntity(entity); if (verbose) { System.out.println("Data[" + dataContent + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream, "UTF-8").trim(); contentStream.close(); if (verbose) { printResponse(content); } final String pageNum = getBackupFileNameField(backupFile.getName(), "${pageNum}"); final String pageSize = getBackupFileNameField(backupFile.getName(), "${pageSize}"); final String backupTime = getBackupFileNameField(backupFile.getName(), "${backupTime}"); final String restoredPath = backupDir.getPath() + File.separatorChar + repositoryName + File.separatorChar + pageNum + '_' + pageSize + '_' + backupTime + '_' + System.currentTimeMillis() + ".json"; final File restoredFile = new File(restoredPath); backupFile.renameTo(restoredFile); if (verbose) { System.out.println("Backup file[path=" + restoredPath + "]"); } } } } if (cmd.hasOption("v")) { System.out.println(VERSION); } if (cmd.hasOption("h")) { printHelp(options); } // final File backup = new File(backupDir.getPath() + File.separatorChar + repositoryName + pageNum + '_' + pageSize + '_' // + System.currentTimeMillis() + ".json"); // final FileEntity fileEntity = new FileEntity(backup, "application/json; charset=\"UTF-8\""); } catch (final ParseException e) { System.err.println("Parsing args failed, caused by: " + e.getMessage()); printHelp(options); } catch (final ConnectException e) { System.err.println("Connection refused"); } }
From source file:view.CLVideoPublisher.java
/** * Launch the application./*from w ww. j a v a2 s .com*/ * @throws DecoderException * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException */ public static void main(String[] args) throws DecoderException, NoSuchAlgorithmException, UnsupportedEncodingException { CLVideoPublisher pub = new CLVideoPublisher(); // Implement the command line interface. while (true) { // print out commands System.err.println(pub.commandList()); // wait for input Scanner sc = new Scanner(System.in); int i = sc.nextInt(); // deal with input switch (i) { case 1: // Print the list // refresh the list. pub.populatePublishList(); System.err.println("\n\n----------Publications----------"); System.err.println(pub.getList()); break; case 2: // Add a publication System.err.println("\nEnter location of publication in folder (" + ProjectPropertiesSingleton.getInstance().getProperty("DefaultMovieFolder") + ")"); String pubPath = ProjectPropertiesSingleton.getInstance().getProperty("DefaultMovieFolder") + sc.next(); // Check the file exists. File file = new File(pubPath); if (!file.exists()) { System.err.println("File does not exist. Returning..."); break; } // publish the event. Under root for now... String newPubIDString = pub.rootGenerator.getNextID(pubPath, IDStrategy.RANDOM); pub.videoPublisher.publishVideo(newPubIDString, pubPath); pub.populatePublishList(); System.err.println("done..."); break; case 3: // Remove a publication // refresh the list. pub.populatePublishList(); System.err.println("\n\n----------Publications----------"); System.err.println(pub.getList()); System.err.println("Enter the number of the publication to remove..."); // check something has been selected int selected = sc.nextInt(); String selectedS = pub.listMappings.get(selected); if (selectedS == null) { System.err.println("Not a valid selection. Returning..."); break; } System.err.println("You have selected " + selectedS + " for removal. Continue... (Y or N)"); String response = sc.next(); if (response.equalsIgnoreCase("n")) { System.err.println("Returning..."); break; } else if (response.equalsIgnoreCase("y")) { // unpublish the item. String rid = pub.ridMappings.get(selectedS); try { pub.videoPublisher.unpublishVideo(rid); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("Did not understand. Returning..."); break; } break; case 4: // Exit System.err.println("Exiting..."); pub.getClient().disconnect(); System.exit(0); break; } } }
From source file:gash.router.app.DemoApp.java
/** * sample application (client) use of our messaging service * * @param args//from ww w . j a va 2 s . c o m */ public static void main(String[] args) { if (args.length == 0) { System.out.println("usage: <ip address> <port no>"); System.exit(1); } String ipAddress = args[0]; int port = Integer.parseInt(args[1]); Scanner s = new Scanner(System.in); boolean isExit = false; try { MessageClient mc = new MessageClient(ipAddress, port); DemoApp da = new DemoApp(mc); int choice = 0; while (true) { System.out.println( "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit"); choice = s.nextInt(); switch (choice) { case 1: { System.out.println("Enter the full pathname of the file to be written "); String currFileName = s.next(); File file = new File(currFileName); if (file.exists()) { ArrayList<ByteString> chunkedFile = da.divideFileChunks(file); String name = file.getName(); int i = 0; String requestId = SupportMessageGenerator.generateRequestID(); for (ByteString string : chunkedFile) { mc.saveFile(name, string, chunkedFile.size(), i++, requestId); } } else { throw new FileNotFoundException("File does not exist in this path "); } } break; case 2: { System.out.println("Enter the file name to be read : "); String currFileName = s.next(); da.sendReadTasks(currFileName); //Thread.sleep(1000 * 100); } break; case 3: { System.out.println("Enter the full pathname of the file to be updated"); String currFileName = s.next(); File file = new File(currFileName); if (file.exists()) { ArrayList<ByteString> chunkedFile = da.divideFileChunks(file); String name = file.getName(); int i = 0; String requestId = SupportMessageGenerator.generateRequestID(); for (ByteString string : chunkedFile) { mc.updateFile(name, string, chunkedFile.size(), i++, requestId); } //Thread.sleep(10 * 1000); } else { throw new FileNotFoundException("File does not exist in this path "); } } break; case 4: System.out.println("Enter the file name to be deleted : "); String currFileName = s.next(); mc.deleteFile(currFileName); //Thread.sleep(1000 * 100); break; case 5: da.ping(1); break; case 6: isExit = true; break; default: break; } if (isExit) break; } } catch (Exception e) { e.printStackTrace(); } finally { CommConnection.getInstance().release(); if (s != null) s.close(); } }
From source file:aula1.Aula1.java
/** * @param args the command line arguments *//*www . j ava 2 s . co m*/ public static void main(String[] args) { Scanner dados = new Scanner(System.in); int escolha; double ini; double fim; String exp; String info; int sens = 0; boolean valida = true; do { System.out.println( "Decida a operao: 0 para montar grfico, 1 para calcular limite, 2 para calcular qualquer expresso"); escolha = dados.nextInt(); switch (escolha) { case 0: System.out.println("Informe o inicio do dominio"); ini = dados.nextDouble(); System.out.println("Informe o fim do dominio"); fim = dados.nextDouble(); System.out.println("Informe a quantidade de casas decimais desejadas: "); sens = dados.nextInt(); System.out.println("Informe a expresso: "); exp = dados.next(); double[] x = montaDominio(ini, fim, sens); calcula(x, exp); valida = false; break; case 1: System.out.println("Informe a expresso: "); exp = dados.next(); System.out.println("Informe o ponto limite: "); info = dados.next(); try { calculaLimite(exp, info); } catch (Exception ex) { System.out .println("Erro: " + ex.getMessage() + "Tentativade aplcao do teorema do confronto"); } valida = false; break; case 2: System.out.println("Informe a expresso:"); info = dados.next(); try { System.out.println(conversor(info, "0")); } catch (Exception ex) { System.out.println("Erro: " + ex.getMessage()); } valida = false; break; default: System.out.println("Escolha invlida!"); break; } } while (valida); // Double[] vet = new Double[3]; // vet = lerDados(); // montaDominio(vet[0], vet[1], vet[2].intValue()); // calculaLimite(3); }
From source file:com.sds.acube.ndisc.xadmin.XNDiscAdminUtil.java
public static void main(String args[]) { if (args.length == 0) { XNDiscAdminUtil.printAdminUsage(null, null); // System.exit(0); }//from w w w.jav a 2s . c om XNDiscAdminFile file = new XNDiscAdminFile(printlog, out, logger); XNDiscAdminMedia media = new XNDiscAdminMedia(printlog, out, logger); XNDiscAdminVolume volume = new XNDiscAdminVolume(printlog, out, logger); XNDiscAdminEnDecrypt endecrypt = new XNDiscAdminEnDecrypt(printlog, out, logger); Scanner in = new Scanner(System.in); String input = ""; List<String> options = null; Scanner part = null; do { input = in.nextLine(); part = new Scanner(input).useDelimiter(" "); options = new ArrayList<String>(); while (part.hasNext()) { String val = part.next().trim(); if (StringUtils.isEmpty(val)) { continue; } options.add(val); } if (options.size() < 2 || input.equalsIgnoreCase("q")) { if (input != null && input.trim().equalsIgnoreCase("q")) { System.out.println(LINE_SEPERATOR + "XNDiscAdminUtil quit!!!" + LINE_SEPERATOR); } else { System.out .println(LINE_SEPERATOR + "XNDiscAdminUtil are invalid parameters!!!" + LINE_SEPERATOR); } System.exit(0); } String main_op = (StringUtils.isEmpty(options.get(0))) ? "" : options.get(0); String process_op = (StringUtils.isEmpty(options.get(1))) ? "" : options.get(1); if (main_op.equals("clear")) { if (process_op.equals("screen")) { clearConsoleOutput(); } } else if (main_op.equals("file")) { if (process_op.equals("ls")) { String fileid = ""; if (options.size() > 2) { fileid = options.get(2); } if (StringUtils.isEmpty(fileid)) { file.selectFileList(); } else { file.selectFileById(fileid); } } else if (process_op.equals("reg")) { String host = ""; int port = -1; String filepath = ""; int vol = -1; if (options.size() == 4) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); filepath = options.get(2); if (isInteger(options.get(3))) { vol = Integer.parseInt(options.get(3)); } } else if (options.size() > 5) { host = options.get(2); port = Integer.parseInt(options.get(3)); filepath = options.get(4); if (isInteger(options.get(5))) { vol = Integer.parseInt(options.get(5)); } } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(filepath) && port > 0 && vol > 0) { file.regFile(host, port, filepath, vol, "0"); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("get")) { String host = ""; int port = -1; String fileid = ""; String filepath = ""; if (options.size() == 4) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); fileid = options.get(2); filepath = options.get(3); } else if (options.size() > 5) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } fileid = options.get(4); filepath = options.get(5); } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && !StringUtils.isEmpty(filepath) && port > 0) { file.getFile(host, port, fileid, filepath); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("wh")) { String fileid = ""; if (options.size() > 2) { fileid = options.get(2); } if (!StringUtils.isEmpty(fileid)) { file.getFilePathByFileId(fileid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("rm")) { String host = ""; int port = -1; String fileid = ""; if (options.size() == 3) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); fileid = options.get(2); } else if (options.size() > 4) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } fileid = options.get(4); } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && port > 0) { file.removeFile(host, port, fileid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("media")) { if (process_op.equals("mk")) { String host = ""; int port = -1; String name = ""; int type = 0; String path = ""; String desc = " "; int maxsize = -1; int vol = -1; if (options.size() == 7) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); name = options.get(2); if (isInteger(options.get(3))) { type = Integer.parseInt(options.get(3)); } path = options.get(4); if (isInteger(options.get(5))) { maxsize = Integer.parseInt(options.get(5)); } if (isInteger(options.get(6))) { vol = Integer.parseInt(options.get(6)); } } else if (options.size() == 8) { host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST); port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT); name = options.get(2); if (isInteger(options.get(3))) { type = Integer.parseInt(options.get(3)); } path = options.get(4); desc = options.get(5) + " "; if (isInteger(options.get(6))) { maxsize = Integer.parseInt(options.get(6)); } if (isInteger(options.get(7))) { vol = Integer.parseInt(options.get(7)); } } else if (options.size() == 9) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } name = options.get(4); if (isInteger(options.get(5))) { type = Integer.parseInt(options.get(5)); } path = options.get(6); if (isInteger(options.get(7))) { maxsize = Integer.parseInt(options.get(7)); } if (isInteger(options.get(8))) { vol = Integer.parseInt(options.get(8)); } } else if (options.size() > 9) { host = options.get(2); if (isInteger(options.get(3))) { port = Integer.parseInt(options.get(3)); } name = options.get(4); if (isInteger(options.get(5))) { type = Integer.parseInt(options.get(5)); } path = options.get(6); desc = options.get(7) + " "; if (isInteger(options.get(8))) { maxsize = Integer.parseInt(options.get(8)); } if (isInteger(options.get(9))) { vol = Integer.parseInt(options.get(9)); } } if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && port > 0 && vol > 0 && maxsize > 0) { media.makeMedia(host, port, name, type, path, desc, maxsize, vol); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ls")) { String mediaid = "-1"; if (options.size() > 2) { mediaid = options.get(2); } if (StringUtils.isEmpty(mediaid) || mediaid.equals("-1")) { media.selectMediaList(); } else { int id = -1; if (isInteger(mediaid)) { id = Integer.parseInt(mediaid); } if (id > 0) { media.selectMediaById(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("rm")) { String mediaid = "-1"; if (options.size() > 2) { mediaid = options.get(2); } if (!StringUtils.isEmpty(mediaid)) { int id = -1; if (isInteger(mediaid)) { id = Integer.parseInt(options.get(2)); } if (id > 0) { media.removeMedia(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("ch")) { int mediaid = -1; String name = ""; int type = 0; String path = ""; String desc = ""; int maxsize = -1; int vol = -1; if (options.size() == 8) { if (isInteger(options.get(2))) { mediaid = Integer.parseInt(options.get(2)); } name = options.get(3); if (isInteger(options.get(4))) { type = Integer.parseInt(options.get(4)); } path = options.get(5); if (isInteger(options.get(6))) { maxsize = Integer.parseInt(options.get(6)); } if (isInteger(options.get(7))) { vol = Integer.parseInt(options.get(7)); } } else if (options.size() > 8) { if (isInteger(options.get(2))) { mediaid = Integer.parseInt(options.get(2)); } name = options.get(3); if (isInteger(options.get(4))) { type = Integer.parseInt(options.get(4)); } path = options.get(5); desc = options.get(6); if (isInteger(options.get(7))) { maxsize = Integer.parseInt(options.get(7)); } if (isInteger(options.get(8))) { vol = Integer.parseInt(options.get(8)); } } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && mediaid > 0 && maxsize > 0 && vol > 0) { media.changeMedia(mediaid, name, type, path, desc, maxsize, vol); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("vol")) { if (process_op.equals("mk")) { String name = ""; String access = ""; String desc = " "; if (options.size() == 4) { name = options.get(2); access = options.get(3); } else if (options.size() > 4) { name = options.get(2); access = options.get(3); desc = options.get(4) + " "; } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access)) { volume.makeVolume(name, access, desc); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ls")) { String volid = "-1"; if (options.size() > 2) { volid = options.get(2); } if (StringUtils.isEmpty(volid) || volid.equals("-1")) { volume.selectVolumeList(); } else { int volumeid = -1; if (isInteger(volid)) { volumeid = Integer.parseInt(volid); } if (volumeid > 0) { volume.selectVolumeById(volumeid); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (process_op.equals("rm")) { String volid = "-1"; if (options.size() > 2) { volid = options.get(2); } if (!StringUtils.isEmpty(volid)) { int volumeid = -1; if (isInteger(volid)) { volumeid = Integer.parseInt(volid); } if (volumeid > 0) { volume.removeVolume(volumeid); } } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("ch")) { int volumeid = -1; String name = ""; String access = ""; String desc = ""; if (options.size() == 5) { if (isInteger(options.get(2))) { volumeid = Integer.parseInt(options.get(2)); } name = options.get(3); access = options.get(4); } else if (options.size() > 5) { if (isInteger(options.get(2))) { volumeid = Integer.parseInt(options.get(2)); } name = options.get(3); access = options.get(4); desc = options.get(5) + " "; } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access) && volumeid > 0) { volume.changeVolume(volumeid, name, access, desc); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } else if (main_op.equals("id")) { String id = ""; if (options.size() > 2) { id = options.get(2); } if (process_op.equals("enc")) { if (!StringUtils.isEmpty(id)) { endecrypt.encrypt(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } else if (process_op.equals("dec")) { if (!StringUtils.isEmpty(id)) { endecrypt.decrypt(id); } else { XNDiscAdminUtil.printAdminUsage(main_op, process_op); } } } part.close(); } while (!input.equalsIgnoreCase("q")); in.close(); }
From source file:driver.ieSystem2.java
public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); boolean login = false; int check = 0; int id = 0;/*from ww w.j ava 2s. co m*/ String user = ""; String pass = ""; Person person = null; Date day = null; JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project", JOptionPane.INFORMATION_MESSAGE); do { System.out.println("What do you want?"); System.out.println("press 1 : Login"); System.out.println("press 2 : Create New User"); System.out.println("Press 3 : Exit "); System.out.println(""); do { try { System.out.print("Enter: "); check = sc.nextInt(); } catch (InputMismatchException e) { JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE); sc.next(); } } while (check <= 1 && check >= 3); // EXIT if (check == 3) { System.out.println("Close Application"); System.exit(0); } // CREATE USER if (check == 2) { System.out.println("-----------------------------------------"); System.out.println("Create New User"); System.out.println("-----------------------------------------"); System.out.print("Account ID: "); id = sc.nextInt(); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); try { Person.createUser(id, user, pass, 0, 0, 0, 0, 0); System.out.println("-----------------------------------------"); System.out.println("Create Complete"); System.out.println("-----------------------------------------"); } catch (Exception e) { System.out.println("-----------------------------------------"); System.out.println("Error, Try again"); System.out.println("-----------------------------------------"); } } else if (check == 1) { // LOGIN do { System.out.println("-----------------------------------------"); System.out.println("LOGIN "); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); if (Person.checkUser(user, pass)) { System.out.println("-----------------------------------------"); System.out.println("Login Complete"); } else { System.out.println("-----------------------------------------"); System.out.println("Invalid Username / Password"); } } while (!Person.checkUser(user, pass)); } } while (check != 1); login = true; person = new Person(user); do { System.out.println("-----------------------------------------"); System.out.println("Hi " + person.getPerName()); System.out.println("Press 1 : Add Income"); System.out.println("Press 2 : Add Expense"); System.out.println("Press 3 : Add Save"); System.out.println("Press 4 : History"); System.out.println("Press 5 : Search"); System.out.println("Press 6 : Analytics"); System.out.println("Press 7 : Total"); System.out.println("Press 8 : All Summary"); System.out.println("Press 9 : Sign Out"); do { try { System.out.print("Enter : "); check = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid Input"); sc.next(); } } while (check <= 1 && check >= 5); // Add Income if (check == 1) { double Income; String catalog = ""; double IncomeTotal = 0; catalog = JOptionPane.showInputDialog("What is your income : "); Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addIncome(person.getPerId(), day, catalog, Income); person.update(); } //Add Expense else if (check == 2) { double Expense; String catalog = ""; catalog = JOptionPane.showInputDialog("What is your expense :"); Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addExpense(person.getPerId(), day, catalog, Expense); person.update(); } //Add Save else if (check == 3) { double Saving; double SavingTotal = 0; String catalog = ""; Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); SavingTotal += Saving; person.addSave(person.getPerId(), day, catalog, Saving); person.update(); } //History else if (check == 4) { String x; do { System.out.println("-----------------------------------------"); System.out.println("YOUR HISTORY"); System.out.println("Date Type Amount"); System.out.println("-----------------------------------------"); List<History> history = person.getHistory(); if (history != null) { int count = 1; for (History h : history) { if (count++ <= 1) { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } else { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } } } System.out.println("-----------------------------------------"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //Searh else if (check == 5) { try { Connection conn = ConnectionDB.getConnection(); long a = person.getPerId(); String NAME = "Salary"; PreparedStatement ps = conn.prepareStatement( "SELECT * FROM INCOME WHERE PERID = " + a + " and CATALOG LIKE '%" + NAME + "%' "); ResultSet rec = ps.executeQuery(); while ((rec != null) && (rec.next())) { System.out.print(rec.getDate("Days")); System.out.print(" - "); System.out.print(rec.getString("CATALOG")); System.out.print(" - "); System.out.print(rec.getDouble("AMOUNT")); System.out.print(" - "); } ps.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Analy else if (check == 6) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); System.out.println("-----------------------------------------"); System.out.println("Income : " + df.format((in / sum) * 100) + "%"); System.out.println("Expense : " + df.format((ex / sum) * 100) + "%"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //TOTAL else if (check == 7) { String x; do { System.out.println("-----------------------------------------"); System.out.println("TOTALSAVE TOTAL"); System.out.println( person.getTotalSave() + " Baht" + " " + person.getTotal() + " Baht"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //ALL Summy else if (check == 8) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); double a = ((in / sum) * 100); double b = ((ex / sum) * 100); System.out.println("-----------------------------------------"); System.out.println("ALL SUMMARY"); System.out.println("Account: " + person.getPerName()); System.out.println(""); System.out.println("Total Save ------------- Total"); System.out .println(person.getTotalSave() + " Baht " + person.getTotal() + " Baht"); System.out.println(""); System.out.println("INCOME --------------- EXPENSE"); System.out.println(df.format(a) + "%" + " " + df.format(b) + "%"); System.out.println("-----------------------------------------"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //LOG OUT else { System.out.println("See ya.\n"); login = false; break; } } while (true); }
From source file:gis.proj.drivers.Snyder.java
public static void main(String... args) { Snyder snyder = new Snyder(); JCommander jc = new JCommander(snyder); try {//from ww w . j av a2 s . c om jc.parse(args); } catch (Exception e) { jc.usage(); System.exit(-10); } String fFormat = "(forward) X: %18.9f, Y: %18.9f%n"; String iFormat = "(inverse) Lon: %18.9f, Lat: %18.9f%n%n"; double[][] xy, ll = null; java.util.regex.Pattern pq = java.util.regex.Pattern.compile("quit", java.util.regex.Pattern.CASE_INSENSITIVE); java.util.Scanner s = new java.util.Scanner(System.in); Projection proj = null; printLicenseInformation("Snyder"); try { System.out.println("Loading projection: " + snyder.projStr); Class<?> cls = Class.forName(snyder.projStr); proj = (Projection) cls.newInstance(); } catch (Exception ex) { ex.printStackTrace(); } double lon = 0.0, lat = 0.0, x = 0.0, y = 0.0; Datum d = new Datum(); Ellipsoid e = EllipsoidFactory.getInstance().getEllipsoid(snyder.ellpStr); System.out.println("\nEllipsoid: " + snyder.ellpStr + ", " + e.getName() + ", " + e.getId() + ", " + e.getDescription()); for (String prop : e.getPropertyNames()) { System.out.println("\t" + prop + "\t" + e.getProperty(prop)); } String cmdEntryLine = (snyder.inverse ? "\nx y " : "\nlon lat") + ": "; for (String dProp : proj.getDatumProperties()) { d.setUserOverrideProperty(dProp, 0.0); } System.out.print(cmdEntryLine); while (s.hasNext(pq) == false) { if (snyder.inverse == false) { lon = parseDatumVal(s.next()); lat = parseDatumVal(s.next()); } else { x = parseDatumVal(s.next()); y = parseDatumVal(s.next()); } for (String dp : d.getPropertyNames()) { System.out.print(dp + ": "); d.setUserOverrideProperty(dp, parseDatumVal(s.next())); } System.out.println(); if (snyder.inverse == false) { xy = proj.forward(new double[] { lon }, new double[] { lat }, e, d); System.out.printf(fFormat, xy[0][0], xy[1][0]); ll = proj.inverse(new double[] { xy[0][0] }, new double[] { xy[1][0] }, e, d); System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0])); } else { ll = proj.inverse(new double[] { x }, new double[] { y }, e, d); System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0])); xy = proj.forward(new double[] { ll[0][0] }, new double[] { ll[1][0] }, e, d); System.out.printf(fFormat, xy[0][0], xy[1][0]); } System.out.print(cmdEntryLine); } s.close(); }