List of usage examples for java.util Scanner close
public void close()
From source file:com.std.Index.java
public void find_historical_data(int month, int day, int year) { try {/* w w w. j av a 2s . c o m*/ String url = "http://real-chart.finance.yahoo.com/table.csv?s=" + this.ticker + "&d=" + month + "&e=" + day + "&f=" + year + "&g=d&a=0&b=1&c=1970&ignore=.csv"; InputStream input; input = new URL(url).openStream(); Scanner s = new Scanner(input); s.useDelimiter("\\A"); String csv = s.hasNext() ? s.next() : ""; s.close(); input.close(); csv = csv.replace("\"", ""); historical_data = new ArrayList<String>(Arrays.asList(csv.split("\n"))); } catch (Exception ex) { System.out.println("Could not retrieve historical data"); System.out.println("Error with connection"); } }
From source file:io.mindmaps.graql.GraqlShell.java
private void printLicense() { StringBuilder result = new StringBuilder(""); //Get file from resources folder ClassLoader classloader = Thread.currentThread().getContextClassLoader(); InputStream is = classloader.getResourceAsStream(LICENSE_LOCATION); Scanner scanner = new Scanner(is); while (scanner.hasNextLine()) { String line = scanner.nextLine(); result.append(line).append("\n"); }//from ww w .j a v a2 s . c o m result.append("\n"); scanner.close(); this.print(result.toString()); }
From source file:com.shoddytcg.server.GameServer.java
/** * Load pre-existing settings if any//ww w . j a v a 2 s . c o m * NOTE: It loads the database password if available. * Password is line after serverName */ private void loadSettings() { File foo = new File("res/settings.txt"); if (foo.exists()) { try { Scanner s = new Scanner(foo); m_dbServer = s.nextLine(); m_dbName = s.nextLine(); m_dbUsername = s.nextLine(); m_serverName = s.nextLine(); m_dbPassword = s.nextLine(); s.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.vmware.identity.ssoconfig.OidcClientCommand.java
private void registerOIDCClient() throws Exception { IdmClient client = SSOConfigurationUtils.getIdmClient(); Scanner scanner = new Scanner(new File(metadataFile)); try {/* www .ja v a2 s . c o m*/ OIDCClientDTO clientDTO = client.oidcClient().register(tenant, getOIDCClientMetadataDTO(scanner.useDelimiter("\\Z").next())); logger.info(String.format("Successfully registered OIDC Client [%s] for tenant %s", clientDTO.getClientId(), tenant)); } finally { scanner.close(); } }
From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit.java
@Test public void testVideoXmlUnitStandardOutput_AVC() throws Exception { // First generate the FITS output File input = new File("testfiles/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1.mp4"); Fits fits = new Fits(); FitsOutput fitsOut = fits.examine(input); // Output stream for FITS to write to ByteArrayOutputStream out = new ByteArrayOutputStream(); // Create standard output in the stream passed in Fits.outputStandardSchemaXml(fitsOut, out); // Turn output stream into a String HtmlUnit can use String actualXmlStr = new String(out.toByteArray(), "UTF-8"); // Read in the expected XML file Scanner scan = new Scanner( new File("testfiles/output/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1_mp4_FITS_Standard.xml")); String expectedXmlStr = scan.useDelimiter("\\Z").next(); scan.close(); // Set up XMLUnit XMLUnit.setIgnoreWhitespace(true);/*from ww w. j av a2 s . co m*/ XMLUnit.setNormalizeWhitespace(true); Diff diff = new Diff(expectedXmlStr, actualXmlStr); // Initialize attributes or elements to ignore for difference checking diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion", "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime", "executionTime", // Not in Standard Output //"filepath", //"location", "ebucore:locator")); DetailedDiff detailedDiff = new DetailedDiff(diff); // Display any Differences List<Difference> diffs = detailedDiff.getAllDifferences(); if (!diff.identical()) { StringBuffer differenceDescription = new StringBuffer(); differenceDescription.append(diffs.size()).append(" differences"); System.out.println(differenceDescription.toString()); for (Difference difference : diffs) { System.out.println(difference.toString()); } } assertTrue("Differences in XML", diff.identical()); }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadThemes(ServletContext servletContext) throws Exception { // assume no themes int themeCount = 0; // create a list for our themes List<Theme> themes = new ArrayList<Theme>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/themes/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".theme.xml"); }/* www .j a v a 2 s. c o m*/ }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/theme.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // get a scanner to read the file Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A"); // read the xml into a string String xml = fileScanner.next(); // close the scanner (and file) fileScanner.close(); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // create a theme object from the xml Theme theme = new Theme(xml); // add it to our collection themes.add(theme); // inc the template count themeCount++; } // sort the list of templates by name Collections.sort(themes, new Comparator<Theme>() { @Override public int compare(Theme t1, Theme t2) { return Comparators.AsciiCompare(t1.getName(), t2.getName(), false); } }); // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet) servletContext.setAttribute("themes", themes); _logger.info(themeCount + " templates loaded in .template.xml files"); return themeCount; }
From source file:com.maxl.java.aips2xml.Aips2Xml.java
static String convertHtmlToXml(String med_title, String html_str, String regnr_str) { Document mDoc = Jsoup.parse(html_str); mDoc.outputSettings().escapeMode(EscapeMode.xhtml); mDoc.outputSettings().prettyPrint(true); mDoc.outputSettings().indentAmount(4); // <div id="monographie"> -> <fi> mDoc.select("div[id=monographie]").tagName("fi").removeAttr("id"); // <div class="MonTitle"> -> <title> mDoc.select("div[class=MonTitle]").tagName("title").removeAttr("class").removeAttr("id"); // Beautify the title to the best of my possibilities ... still not good enough! String title_str = mDoc.select("title").text().trim().replaceAll("<br />", "").replaceAll("(\\t|\\r?\\n)+", "");/*from w ww . j av a 2 s. c om*/ if (!title_str.equals(med_title)) if (SHOW_ERRORS) System.err.println(med_title + " differs from " + title_str); // Fallback solution: use title from the header AIPS.xml file - the titles look all pretty good! mDoc.select("title").first().text(med_title); // <div class="ownerCompany"> -> <owner> Element owner_elem = mDoc.select("div[class=ownerCompany]").first(); if (owner_elem != null) { owner_elem.tagName("owner").removeAttr("class"); String owner_str = mDoc.select("owner").text(); mDoc.select("owner").first().text(owner_str); } else { mDoc.select("title").after("<owner></owner>"); if (DB_LANGUAGE.equals("de")) mDoc.select("owner").first().text("k.A."); else if (DB_LANGUAGE.equals("fr")) mDoc.select("owner").first().text("n.s."); } // <div class="paragraph"> -> <paragraph> mDoc.select("div[class=paragraph]").tagName("paragraph").removeAttr("class").removeAttr("id"); // <div class="absTitle"> -> <paragraphTitle> mDoc.select("div[class=absTitle]").tagName("paragraphtitle").removeAttr("class"); // <div class="untertitle1"> -> <paragraphSubTitle> mDoc.select("div[class=untertitle1]").tagName("paragraphsubtitle").removeAttr("class"); // <div class="untertitle"> -> <paragraphSubTitle> mDoc.select("div[class=untertitle]").tagName("paragraphsubtitle").removeAttr("class"); // <div class="shortCharacteristic"> -> <characteristic> mDoc.select("div[class=shortCharacteristic]").tagName("characteristic").removeAttr("class"); // <div class="image"> mDoc.select("div[class=image]").tagName("image").removeAttr("class"); // <p class="spacing1"> -> <p> / <p class="noSpacing"> -> <p> mDoc.select("p[class]").tagName("p").removeAttr("class"); // <span style="font-style:italic"> -> <i> mDoc.select("span").tagName("i").removeAttr("style"); // <i class="indention1"> -> <i> / <i class="indention2"> -> <b-i> mDoc.select("i[class=indention1]").tagName("i").removeAttr("class"); mDoc.select("i[class=indention2]").tagName("i").removeAttr("class"); // mDoc.select("p").select("i").tagName("i"); // mDoc.select("paragraphtitle").select("i").tagName("para-i"); // mDoc.select("paragraphsubtitle").select("i").tagName("parasub-i"); Elements elems = mDoc.select("paragraphtitle"); for (Element e : elems) { if (!e.text().isEmpty()) e.text(e.text()); } elems = mDoc.select("paragraphsubtitle"); for (Element e : elems) { if (!e.text().isEmpty()) e.text(e.text()); } // Here we take care of tables // <table class="s21"> -> <table> mDoc.select("table[class]").removeAttr("class"); mDoc.select("table").removeAttr("cellspacing").removeAttr("cellpadding").removeAttr("border"); mDoc.select("colgroup").remove(); mDoc.select("td").removeAttr("class").removeAttr("colspan").removeAttr("rowspan"); mDoc.select("tr").removeAttr("class"); elems = mDoc.select("div[class]"); for (Element e : elems) { if (e.text().isEmpty()) e.remove(); } mDoc.select("tbody").unwrap(); // Remove nested table (a nasty table-in-a-table Elements nested_table = mDoc.select("table").select("tr").select("td").select("table"); if (!nested_table.isEmpty()) { nested_table.select("table").unwrap(); } // Here we take care of the images mDoc.select("img").removeAttr("style").removeAttr("align").removeAttr("border"); // Subs and sups mDoc.select("sub[class]").tagName("sub").removeAttr("class"); mDoc.select("sup[class]").tagName("sup").removeAttr("class"); mDoc.select("td").select("sub").tagName("td-sub"); mDoc.select("td").select("sup").tagName("td-sup"); // Remove floating <td-sup> tags mDoc.select("p").select("td-sup").tagName("sup"); mDoc.select("p").select("td-sub").tagName("sub"); // Box mDoc.select("div[class=box]").tagName("box").removeAttr("class"); // Insert swissmedicno5 after <owner> tag mDoc.select("owner").after("<swissmedicno5></swissmedicno5"); mDoc.select("swissmedicno5").first().text(regnr_str); // Remove html, head and body tags String xml_str = mDoc.select("body").first().html(); //xml_str = xml_str.replaceAll("<tbody>", "").replaceAll("</tbody>", ""); xml_str = xml_str.replaceAll("<sup> </sup>", ""); xml_str = xml_str.replaceAll("<sub> </sub>", ""); xml_str = xml_str.replaceAll("<p> <i>", "<p><i>"); xml_str = xml_str.replaceAll("</p> </td>", "</p></td>"); xml_str = xml_str.replaceAll("<p> </p>", "<p></p>"); // MUST be improved, the space is not a real space!! xml_str = xml_str.replaceAll("", "- "); xml_str = xml_str.replaceAll("<br />", ""); xml_str = xml_str.replaceAll("(?m)^[ \t]*\r?\n", ""); // Remove multiple instances of <p></p> Scanner scanner = new Scanner(xml_str); String new_xml_str = ""; int counter = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.trim().equals("<p></p>")) { counter++; } else counter = 0; if (counter < 3) new_xml_str += line; } scanner.close(); return new_xml_str; }
From source file:com.joliciel.jochre.search.JochreQueryImpl.java
public JochreQueryImpl(Map<String, String> argMap) { try {/*from www . j a va 2s . c o m*/ for (Entry<String, String> argEntry : argMap.entrySet()) { String argName = argEntry.getKey(); String argValue = argEntry.getValue(); if (argName.equalsIgnoreCase("query")) { this.setQueryString(argValue); } else if (argName.equalsIgnoreCase("queryFile")) { File queryFile = new File(argValue); Scanner scanner = new Scanner( new BufferedReader(new InputStreamReader(new FileInputStream(queryFile), "UTF-8"))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); this.setQueryString(line); break; } scanner.close(); } else if (argName.equalsIgnoreCase("maxDocs")) { int maxDocs = Integer.parseInt(argValue); this.setMaxDocs(maxDocs); } else if (argName.equalsIgnoreCase("decimalPlaces")) { int decimalPlaces = Integer.parseInt(argValue); this.setDecimalPlaces(decimalPlaces); } else if (argName.equalsIgnoreCase("lang")) { this.setLanguage(argValue); } else if (argName.equalsIgnoreCase("filter")) { if (argValue.length() > 0) { String[] idArray = argValue.split(","); this.setDocFilter(idArray); } } else if (argName.equalsIgnoreCase("filterField")) { if (argValue.length() > 0) this.setFilterField(argValue); } else { LOG.trace("JochreQuery unknown option: " + argName); } } } catch (IOException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:com.threewks.thundr.configuration.PropertiesLoader.java
private Map<String, String> readProperties(String resourceAsString) { Map<String, String> properties = new LinkedHashMap<String, String>(); Scanner scanner = new Scanner(resourceAsString); try {//from w w w.jav a 2s . c o m while (scanner.hasNextLine()) { String line = scanner.nextLine(); line = StringUtils.substringBefore(line, "#"); line = StringUtils.trimToNull(line); String key = StringUtils.substringBefore(line, "="); String value = StringUtils.substringAfter(line, "="); if (key != null) { properties.put(key, value); } } } finally { scanner.close(); } return properties; }
From source file:fr.vdl.android.holocolors.HoloColorsDialog.java
private void checkLicence() { try {//from w ww .ja va 2s . c om String userHome = System.getProperty("user.home"); File holoColorsFolder = new File(userHome + File.separator + ".holocolors"); File licenceFile = new File(holoColorsFolder, ".licence"); File noDonationFile = new File(holoColorsFolder, ".nodonation"); if (noDonationFile.exists()) { return; } int usage = 1; boolean showPopup = false; if (!holoColorsFolder.exists()) { holoColorsFolder.mkdir(); showPopup = true; licenceFile.createNewFile(); } else { Scanner in = new Scanner(new FileReader(licenceFile)); if (in.hasNextInt()) { usage = in.nextInt() + 1; } in.close(); } if (usage > 10) { usage = 1; showPopup = true; } Writer out = new BufferedWriter(new FileWriter(licenceFile)); out.write(String.valueOf(usage)); out.close(); if (showPopup) { Object[] donationOption = { "Make a donation", "Maybe later", "No Never" }; int option = JOptionPane.showOptionDialog(ahcPanel, "Thanks for using Android Holo Colors!\n\nAndroid Holo Colors (website and plugin) is free to use.\nIf you save time and money with it, please make a donation.", "Support Android Holo Colors", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/icons/H64.png")), donationOption, donationOption[0]); if (option == 0) { openWebpage( "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XQSBX55A2Z46U"); } if (option == 2) { noDonationFile.createNewFile(); } } } catch (Exception e) { // no matter, nothing to do e.printStackTrace(); } }