List of usage examples for java.util Scanner next
public String next()
From source file:de.ingrid.interfaces.csw.server.cswt.impl.GenericServerCSWT.java
/** * Get a Document from a class path location. The actual name of the file is * retrieved from the config.properties file. * * With variant a specific variant (like a localization) can be retrieved. * The file name is extended by the variant in the form * [name]_[variant].[extension]./*from www .j a v a2 s . c om*/ * * If the variant could not be retrieved, the base file is returned as a * fall back. * * The content is cached. The cache can be controlled by the * config.properties entry 'cache.enable'. * * @param key * One of the keys config.properties, defining the actual * filename to be retrieved. * @param variant * The variant of the file. * @return The Document instance */ protected Document getDocument(String key, String variant) { // fetch the document from the file system if it is not cached String filename = ApplicationProperties.getMandatory(key); String filenameVariant = filename; if (variant != null && variant.length() > 0) { if (filename.contains(FilenameUtils.EXTENSION_SEPARATOR_STR)) { filenameVariant = FilenameUtils.getBaseName(filename) + "_" + variant + FilenameUtils.EXTENSION_SEPARATOR_STR + FilenameUtils.getExtension(filename); } else { filenameVariant = FilenameUtils.getBaseName(filename) + "_" + variant; } } Document doc = null; Scanner scanner = null; try { URL resource = this.getClass().getClassLoader().getResource(filenameVariant); if (resource == null) { log.warn("Document '" + filenameVariant + "' could not be found in class path."); resource = this.getClass().getClassLoader().getResource(filename); } String path = resource.getPath().replaceAll("%20", " "); File file = new File(path); scanner = new Scanner(file); scanner.useDelimiter("\\A"); String content = scanner.next(); scanner.close(); doc = StringUtils.stringToDocument(content); } catch (Exception e) { log.error("Error reading document configured in configuration key '" + key + "': " + filename + ", " + variant, e); throw new RuntimeException("Error reading document configured in configuration key '" + key + "': " + filename + ", " + variant, e); } finally { if (scanner != null) { scanner.close(); } } return doc; }
From source file:com.java2s.intents4.IntentsDemo4Activity.java
private IntentFilter createFilterFromEditTextFields() { IntentFilter filter = new IntentFilter(); if (filterActionsLayout != null) { int count = filterActionsLayout.getChildCount(); for (int i = 0; i < count; i++) { String action = ((EditText) ((ViewGroup) filterActionsLayout.getChildAt(i)).getChildAt(1)).getText() .toString().trim();/*from w w w.j av a2s. com*/ if (action.length() != 0) { filter.addAction(action); } } } if (filterSchemeLayout != null) { int count = filterSchemeLayout.getChildCount(); for (int i = 0; i < count; i++) { String scheme = ((EditText) ((ViewGroup) filterSchemeLayout.getChildAt(i)).getChildAt(1)).getText() .toString().trim(); if (scheme.length() != 0) { filter.addDataScheme(scheme); } } } if (filterAuthLayout != null) { int count = filterAuthLayout.getChildCount(); for (int i = 0; i < count; i++) { String auth = ((EditText) ((ViewGroup) filterAuthLayout.getChildAt(i)).getChildAt(1)).getText() .toString().trim(); if (auth.length() != 0) { Scanner scanner = new Scanner(auth); scanner.useDelimiter(":"); String host = null; String port = null; if (scanner.hasNext()) { host = scanner.next(); } if (scanner.hasNext()) { port = scanner.next(); } filter.addDataAuthority(host, port); } } } if (filterPathLayout != null) { int count = filterPathLayout.getChildCount(); for (int i = 0; i < count; i++) { ViewGroup group = (ViewGroup) filterPathLayout.getChildAt(i); String path = ((EditText) group.getChildAt(1)).getText().toString().trim(); String pattern = ((TextView) ((ViewGroup) group.getChildAt(2)).getChildAt(0)).getText().toString() .trim(); // ((TextView) int patternInt = 0; if (pattern.equals(pathPatterns[0])) { patternInt = PatternMatcher.PATTERN_LITERAL; } if (pattern.equals(pathPatterns[1])) { patternInt = PatternMatcher.PATTERN_PREFIX; } if (pattern.equals(pathPatterns[2])) { patternInt = PatternMatcher.PATTERN_SIMPLE_GLOB; } if (path.length() != 0) { filter.addDataPath(path, patternInt); } } } if (filterTypeLayout != null) { int count = filterTypeLayout.getChildCount(); for (int i = 0; i < count; i++) { String aType = ((EditText) ((ViewGroup) filterTypeLayout.getChildAt(i)).getChildAt(1)).getText() .toString().trim(); if (aType.length() != 0) { try { filter.addDataType(aType); } catch (MalformedMimeTypeException e) { e.printStackTrace(); } } } } if (filterCategoriesLayout != null) { int count = filterCategoriesLayout.getChildCount(); for (int i = 0; i < count; i++) { String cat = ((EditText) ((ViewGroup) filterCategoriesLayout.getChildAt(i)).getChildAt(1)).getText() .toString().trim(); if (cat.length() != 0) { filter.addCategory(cat); } } } return filter; }
From source file:com.groupon.odo.proxylib.BackupService.java
/** * Restore configuration from backup data * * @param streamData InputStream for configuration to restore * @return true if succeeded, false if operation failed *//*from w w w .ja va 2 s. co m*/ public boolean restoreBackupData(InputStream streamData) { // convert stream to string java.util.Scanner s = new java.util.Scanner(streamData).useDelimiter("\\A"); String data = s.hasNext() ? s.next() : ""; // parse JSON ObjectMapper mapper = new ObjectMapper(); Backup backupData = null; try { backupData = mapper.readValue(data, Backup.class); } catch (Exception e) { logger.error("Could not parse input data: {}, {}", e.getClass(), e.getMessage()); return false; } // TODO: validate json against a schema for safety // GROUPS try { logger.info("Number of groups: {}", backupData.getGroups().size()); for (Group group : backupData.getGroups()) { // determine if group already exists.. if not then add it Integer groupId = PathOverrideService.getInstance().getGroupIdFromName(group.getName()); if (groupId == null) { groupId = PathOverrideService.getInstance().addGroup(group.getName()); } // get all methods from the group.. we are going to remove ones that don't exist in the new configuration List<Method> originalMethods = EditService.getInstance().getMethodsFromGroupId(groupId, null); for (Method originalMethod : originalMethods) { Boolean matchInImportGroup = false; int importCount = 0; for (Method importMethod : group.getMethods()) { if (originalMethod.getClassName().equals(importMethod.getClassName()) && originalMethod.getMethodName().equals(importMethod.getMethodName())) { matchInImportGroup = true; break; } importCount++; } if (!matchInImportGroup) { // remove it from current database since it is a delta to the current import PathOverrideService.getInstance().removeOverride(originalMethod.getId()); } else { // remove from import list since it already exists group.getMethods().remove(importCount); } } // add methods to groups for (Method method : group.getMethods()) { PathOverrideService.getInstance().createOverride(groupId, method.getMethodName(), method.getClassName()); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // PROFILES try { logger.info("Number of profiles: {}", backupData.getProfiles().size()); // remove all servers // don't care about deltas here.. we'll just recreate them all // removed default servers (belong to group id=0) ServerRedirectService.getInstance().deleteServerGroup(0); for (com.groupon.odo.proxylib.models.backup.Profile profile : backupData.getProfiles()) { // see if a profile with this name already exists Integer profileId = ProfileService.getInstance().getIdFromName(profile.getName()); com.groupon.odo.proxylib.models.Profile newProfile; if (profileId == null) { // create new profile newProfile = ProfileService.getInstance().add(profile.getName()); } else { // get the existing profile newProfile = ProfileService.getInstance().findProfile(profileId); } // add new servers if (profile.getServers() != null) { for (ServerRedirect server : profile.getServers()) { ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), 0); } } // remove all server groups for (ServerGroup group : ServerRedirectService.getInstance() .tableServerGroups(newProfile.getId())) { ServerRedirectService.getInstance().deleteServerGroup(group.getId()); } // add new server groups if (profile.getServerGroups() != null) { for (ServerGroup group : profile.getServerGroups()) { int groupId = ServerRedirectService.getInstance().addServerGroup(group.getName(), newProfile.getId()); for (ServerRedirect server : group.getServers()) { ServerRedirectService.getInstance().addServerRedirect(server.getRegion(), server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(), groupId); } } } // remove all paths // don't care about deltas here.. we'll just recreate them all for (EndpointOverride path : PathOverrideService.getInstance().getPaths(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, null)) { PathOverrideService.getInstance().removePath(path.getPathId()); } // add new paths if (profile.getPaths() != null) { for (EndpointOverride path : profile.getPaths()) { int pathId = PathOverrideService.getInstance().addPathnameToProfile(newProfile.getId(), path.getPathName(), path.getPath()); PathOverrideService.getInstance().setContentType(pathId, path.getContentType()); PathOverrideService.getInstance().setRequestType(pathId, path.getRequestType()); PathOverrideService.getInstance().setGlobal(pathId, path.getGlobal()); // add groups to path for (String groupName : path.getGroupNames()) { int groupId = PathOverrideService.getInstance().getGroupIdFromName(groupName); PathOverrideService.getInstance().AddGroupByNumber(newProfile.getId(), pathId, groupId); } } } // set active ClientService.getInstance().updateActive(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID, profile.getActive()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // SCRIPTS try { // delete all scripts for (Script script : ScriptService.getInstance().getScripts()) { ScriptService.getInstance().removeScript(script.getId()); } // add scripts for (Script script : backupData.getScripts()) { ScriptService.getInstance().addScript(script.getName(), script.getScript()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // tell http/https proxies to reload plugins try { org.apache.http.conn.ssl.SSLSocketFactory sslsf = new org.apache.http.conn.ssl.SSLSocketFactory( new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException { // ignore SSL cert issues return true; } }); HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); for (String connectstring : getConnectorStrings("https_proxy")) { HttpGet request = new HttpGet(connectstring + "/proxy/reload"); HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient(); String[] parts = connectstring.split(":"); httpClient.getConnectionManager().getSchemeRegistry() .register(new org.apache.http.conn.scheme.Scheme("https", Integer.parseInt(parts[parts.length - 1]), sslsf)); HttpResponse response = httpClient.execute(request); } } catch (Exception e) { e.printStackTrace(); logger.info("Exception caught during proxy reload. Things may be in an inconsistent state."); } // restart plugin service for this process PluginManager.destroy(); return true; }
From source file:Balo.MainFram.java
public void getDataFileToJTable() { String fileNameDefined = "src/Balo/Data_3.csv"; File file = new File(fileNameDefined); int i = 0;// w ww .j a v a 2 s . c o m dvDynamic[0] = new Dovat(); //Get value from csv file try { Scanner inputStream = new Scanner(file); inputStream.useDelimiter(","); while (inputStream.hasNext()) { dvDynamic[i + 1] = dvGreedy[i] = new Dovat(); dvDynamic[i + 1].ten = dvGreedy[i].ten = inputStream.next().trim(); dvDynamic[i + 1].soluong = dvGreedy[i].soluong = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].giatri = dvGreedy[i].giatri = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].trongluong = dvGreedy[i].trongluong = Integer.valueOf(inputStream.next().trim()); i++; } //Set number of Items numOfItem = i; //Get weight bag weightBag = Integer.parseInt(TextW.getText()); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } //Set value for JTable for (int item = 0; item < numOfItem; item++) { Object[] row = new Object[4]; row[0] = dvGreedy[item].ten; row[1] = dvGreedy[item].soluong; row[2] = dvGreedy[item].giatri; row[3] = dvGreedy[item].trongluong; model.addRow(row); } }
From source file:files.populate.java
void populate_business(Connection connection, String filename) { String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_business.json"; Path path = Paths.get(fileName); Scanner scanner = null; try {//from www . ja v a2 s . c om scanner = new Scanner(path); } catch (IOException e) { e.printStackTrace(); } //read file line by line scanner.useDelimiter("\n"); int i = 0; while (scanner.hasNext()) { if (i < 500) { JSONParser parser = new JSONParser(); String s = (String) scanner.next(); s = s.replace("'", "''"); JSONObject obj; try { obj = (JSONObject) parser.parse(s); String add = (String) obj.get("full_address"); add = add.replace("\n", ""); //insertion into business table String query = "insert into yelp_business values ('" + obj.get("business_id") + "','" + add + "','" + obj.get("open") + "','" + obj.get("city") + "','" + obj.get("state") + "','" + obj.get("latitude") + "','" + obj.get("longitude") + "','" + obj.get("review_count") + "','" + obj.get("name") + "','" + obj.get("stars") + "','" + obj.get("type") + "')"; Statement statement = connection.createStatement(); System.out.println(query); statement.executeUpdate(query); //end //inserting into hours table Map hours = (Map) obj.get("hours"); Set keys = hours.keySet(); Object[] days = keys.toArray(); for (int j = 0; j < days.length; ++j) { // String thiskey = days[j].toString(); Map timings = (Map) hours.get(thiskey); // String q3 = "insert into business_hours values ('" + obj.get("business_id") + "','" + thiskey + "','" + timings.get("close") + "','" + timings.get("open") + "')"; // statement.executeUpdate(q3); } //end //insertion into cat table // System.out.println(s); String[] mainCategories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes", "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores", "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical", "Home Services", "Home & Garden", "Hospitals", "Hotels & Travel", "Hardware Stores", "Grocery", "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping", "Transportation" }; List<String> mainCategories1 = Arrays.asList(mainCategories); ArrayList<String> categories = (ArrayList<String>) obj.get("categories"); for (int j = 0; j < categories.size(); ++j) { String q; if (mainCategories1.contains(categories.get(j))) { q = "insert into business_cat values ('" + obj.get("business_id") + "','" + categories.get(j) + "','main')"; } else { q = "insert into business_cat values ('" + obj.get("business_id") + "','" + categories.get(j) + "','sub')"; } // System.out.println(q); statement.executeUpdate(q); } //end //insertion into neighborhood table ArrayList<String> hood = (ArrayList<String>) obj.get("neighborhoods"); for (int j = 0; j < hood.size(); ++j) { String q = "insert into business_hood values ('" + obj.get("business_id") + "','" + hood.get(j) + "')"; // System.out.println(q); statement.executeUpdate(q); } //end //insertion into attributes and ambience table Map<String, ?> att = (Map<String, ?>) obj.get("attributes"); System.out.println(att + "\n\n"); Set keys1 = att.keySet(); Object[] attname = keys1.toArray(); for (int j = 0; j < attname.length; ++j) { // String thiskey = attname[j].toString(); String att_query = new String(); if (att.get(thiskey) instanceof JSONObject) { Map<String, ?> subatt = (Map<String, ?>) att.get(thiskey); Set keys2 = subatt.keySet(); Object[] attname2 = keys2.toArray(); for (int k = 0; k < attname2.length; ++k) { String thiskey2 = attname2[k].toString(); String subcat_value = (String) String.valueOf(subatt.get(thiskey2)); att_query = "insert into business_attributes values ('" + obj.get("business_id") + "','" + thiskey + "','" + thiskey2 + "','" + subcat_value + "')"; // System.out.println("subkey="+thiskey2 + "value = "+subcat_value); // System.out.println(att_query); statement.executeUpdate(att_query); } } else { String attvalues = (String) String.valueOf(att.get(thiskey)); att_query = "insert into business_attributes values ('" + obj.get("business_id") + "','n/a','" + thiskey + "','" + attvalues + "')"; // System.out.println("key="+thiskey + "value = "+attvalues); statement.executeUpdate(att_query); } // String q3 = "insert into business_hours values ('"+obj.get("business_id")+"','"+thiskey+"','"+timings.get("close")+"','"+timings.get("open")+"')"; // System.out.println(q3); // statement.executeUpdate(q3); } statement.close(); // } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } i++; } else { break; } } }
From source file:org.apache.hadoop.hdfs.server.balancer.LatencyBalancer.java
void getLatencies(String path) { Scanner sc; try {/* ww w .j av a 2 s . c om*/ sc = new Scanner(new File(path)); while (sc.hasNext()) { latencies.put(sc.next(), Double.parseDouble(sc.next())); } for (String lt : latencies.keySet()) { System.out.println(lt + " " + latencies.get(lt)); } } catch (IOException e) { System.err.println(e); } }
From source file:com.rockhoppertech.music.scale.Scale.java
/** * @param name//from w w w .j a v a2 s . c o m * the name to set */ public void setName(final String name) { if (name.contains(",")) { Scanner s = new Scanner(name); s.useDelimiter(","); this.name = s.next(); while (s.hasNext()) { aliases.add(s.next()); } s.close(); } else { this.name = name; } }
From source file:net.billylieurance.azuresearch.AbstractAzureSearchQuery.java
/** * * @param is An InputStream holding some XML that needs parsing * @return a parsed Document from the XML in the stream *///from ww w . j a v a2 s . c om public Document loadXMLFromStream(InputStream is) { DocumentBuilderFactory factory; DocumentBuilder builder; BOMInputStream bis; String dumpable = ""; try { factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); bis = new BOMInputStream(is); if (_debug) { java.util.Scanner s = new java.util.Scanner(bis).useDelimiter("\\A"); dumpable = s.hasNext() ? s.next() : ""; // convert String into InputStream InputStream istwo = new java.io.ByteArrayInputStream(dumpable.getBytes()); return builder.parse(istwo); } else { return builder.parse(bis); } } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { if (e instanceof SAXParseException) { SAXParseException ex = (SAXParseException) e; System.out.println("Line: " + ex.getLineNumber()); System.out.println("Col: " + ex.getColumnNumber()); System.out.println("Data: " + dumpable); } e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return null; }
From source file:org.de.jmg.jmgphotouploader._MainActivity.java
private void AcceptLicenseAndPP(SharedPreferences prefs) throws Throwable { boolean blnLicenseAccepted = prefs.getBoolean("LicenseAccepted", false); if (!blnLicenseAccepted) { InputStream is = this.getAssets().open("LICENSE"); java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); String strLicense = s.hasNext() ? s.next() : ""; s.close();/*from w ww . ja v a2 s . c o m*/ is.close(); lib.yesnoundefined res = (lib.ShowMessageYesNo(this, strLicense, getString(R.string.license), true)); lib.yesnoundefined res2 = lib.yesnoundefined.undefined; if (res == lib.yesnoundefined.yes) { res2 = lib.AcceptPrivacyPolicy(this, Locale.getDefault()); } if (res == lib.yesnoundefined.yes && res2 == lib.yesnoundefined.yes) { prefs.edit().putBoolean("LicenseAccepted", true).commit(); } else { prefs.edit().putBoolean("LicenseAccepted", false).commit(); finish(); } } }
From source file:com.netcrest.pado.tools.pado.command.temporal.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void runHistory(ITemporalBiz temporalBiz, String commandLineArg) throws Exception { Scanner scanner = new Scanner(commandLineArg); if (scanner.hasNext()) { identityKeyStr = scanner.next(); } else {//w w w .j a v a2s. co m PadoShell.printlnError(this, "history: IdentityKey not specified."); return; } if (objectPattern.matcher(identityKeyStr).matches()) { identityKey = generateObject(identityKeyStr); } else { PadoShell.printlnError(this, "history: IdentityKey is not specified in proper format."); return; } identityKey = generateObject(identityKeyStr); TemporalDataList tdl = temporalBiz.getTemporalAdminBiz().getTemporalDataList(identityKey); if (tdl == null) { PadoShell.printlnError(this, "history: Identity key not found."); return; } TemporalPrintUtil.dump(tdl, rawFormat); }