List of usage examples for java.util HashSet contains
public boolean contains(Object o)
From source file:ch.unil.genescore.pathway.GeneSetLibrary.java
License:asdf
/**genesForSimulation */ private void fillUpGenesForSimulationArray(GeneSet geneSet) { //if("KEGG_CITRATE_CYCLE_TCA_CYCLE".equals(geneSet.getId())){ // System.out.println("asfasf"); //}// w w w . ja v a2 s . c om //get all genes contained in meta genes. HashSet<Gene> genesInMetaGenes = new HashSet<Gene>(); if (metaGenes_ != null) { for (MetaGene metaGene : geneSet.getMetaGenes()) { TreeSet<Gene> allGenesInMetaGene = metaGene.getGenes(); for (Gene gene : allGenesInMetaGene) { genesInMetaGenes.add(gene); } } } //add genes not belonging to meta-gene. genesForSimulation_ = new ArrayList<Gene>(); for (Gene gene : genes_) { if (!genesInMetaGenes.contains(gene)) { genesForSimulation_.add(gene); } } //add meta genes. if (geneSet.getMetaGenes() != null) { for (MetaGene metaGene : geneSet.getMetaGenes()) { genesForSimulation_.add(metaGene); } } }
From source file:fr.msch.wissl.server.TestPlaylist.java
public void test() throws Exception { HttpClient client = new HttpClient(); RuntimeStats rt = new RuntimeStats(); rt.songCount.set(15);/*ww w .j a va 2 s. c o m*/ rt.albumCount.set(5); rt.artistCount.set(2); rt.playlistCount.set(0); rt.userCount.set(2); rt.playtime.set(15); rt.downloaded.set(0); this.addMusicFolder(new File("src/test/resources/data").getAbsolutePath(), rt); rt.songCount.set(24); rt.albumCount.set(6); rt.artistCount.set(3); rt.playtime.set(24); this.addMusicFolder(new File("src/test/resources/data2").getAbsolutePath(), rt); // create playlist with no name: 400 PostMethod post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // create playlist 'foo' post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); JSONObject obj = new JSONObject(post.getResponseBodyAsString()); Playlist foo = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("foo", foo.name); assertEquals(0, foo.songs); assertEquals(0, foo.playtime); // create playlist 'foo' again: returns the same playlist post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(foo, new Playlist(obj.getJSONObject("playlist").toString())); // create playlist 'foo' as admin: creates another playlist post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); Playlist pl = new Playlist(obj.getJSONObject("playlist").toString()); assertNotSame(foo, pl); // playlists for user: 'foo' GetMethod get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(1, obj.getJSONArray("playlists").length()); assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString())); // playlists/id for user: 'foo' get = new GetMethod(URL + "playlists/" + user_userId); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(1, obj.getJSONArray("playlists").length()); assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString())); // remove playlist without argument: 400 post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // remove admin 'foo' playlist as user: 403 post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("playlist_ids[]", "" + pl.id); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // remove admin 'foo' post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("playlist_ids[]", "" + pl.id); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // playlists for admin: 'none' get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); // playlists/id for admin: 'none' get = new GetMethod(URL + "playlists/" + admin_userId); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); // playlist/create-add with no name : 400 post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // playlist/create-add 'bar' with no songs post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(0, obj.getInt("added")); Playlist bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(0, bar.playtime); assertEquals(0, bar.songs); int[] song_ids = new int[4]; int album_id; // search for 'o': 4 songs, 1 album with 1 song get = new GetMethod(URL + "search/o"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); JSONArray songs = obj.getJSONArray("songs"); for (int i = 0; i < 4; i++) { song_ids[i] = songs.getJSONObject(i).getInt("id"); } JSONObject ok = obj.getJSONArray("albums").getJSONObject(0); album_id = ok.getInt("id"); // playlist/create-add 'bar' with songs post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[1]); post.addParameter("song_ids[]", "" + song_ids[2]); post.addParameter("song_ids[]", "" + song_ids[3]); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(5, obj.getInt("added")); bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(5, bar.playtime); assertEquals(5, bar.songs); // check song list in 'bar' get = new GetMethod(URL + "playlist/" + bar.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); JSONArray arr = obj.getJSONArray("playlist"); assertEquals(5, arr.length()); for (int i = 0; i < 4; i++) { assertEquals(new Song(songs.getJSONObject(i).toString()), new Song(arr.getJSONObject(i).toString())); } Song s5 = new Song(arr.getJSONObject(4).toString()); assertEquals("Ok", s5.album_name); // playlist/remove song as wrong user post = new PostMethod(URL + "playlist/" + bar.id + "/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("song_ids[]", "" + song_ids[0]); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // playlist/remove 2 songs post = new PostMethod(URL + "playlist/" + bar.id + "/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("song_ids[]", "" + song_ids[1]); post.addParameter("song_ids[]", "" + song_ids[2]); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // check song list get = new GetMethod(URL + "playlist/" + bar.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); arr = obj.getJSONArray("playlist"); assertEquals(3, arr.length()); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString())); assertEquals(new Song(songs.getJSONObject(3).toString()), new Song(arr.getJSONObject(1).toString())); assertEquals(s5, new Song(arr.getJSONObject(2).toString())); // re-check with song/id/pos get = new GetMethod(URL + "playlist/" + bar.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString())); // 2nd song get = new GetMethod(URL + "playlist/" + bar.id + "/song/1"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(3).toString()), new Song(obj.toString())); // 3rd song get = new GetMethod(URL + "playlist/" + bar.id + "/song/2"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(s5, new Song(obj.toString())); // no more song in playlist get = new GetMethod(URL + "playlist/" + bar.id + "/song/3"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(404, get.getStatusCode()); // playlist/create-add 'bar' with other songs and clear post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); post.addParameter("clear", "true"); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(1, obj.getInt("added")); bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(1, bar.playtime); assertEquals(1, bar.songs); // playlist/add as admin: 403 post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids", "" + s5.id); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // playlist/add with duplicate songs: 400 post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(500, post.getStatusCode()); // playlist/add a couple songs w/ clear post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[2]); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(2, obj.getInt("added")); pl = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(2, pl.playtime); assertEquals(2, pl.songs); assertEquals("bar", pl.name); // check song list get = new GetMethod(URL + "playlist/" + pl.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); arr = obj.getJSONArray("playlist"); assertEquals(2, arr.length()); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString())); assertEquals(new Song(songs.getJSONObject(2).toString()), new Song(arr.getJSONObject(1).toString())); // re-check with song/id/pos get = new GetMethod(URL + "playlist/" + pl.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString())); // 2nd song get = new GetMethod(URL + "playlist/" + pl.id + "/song/1"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(2).toString()), new Song(obj.toString())); // no more song in playlist get = new GetMethod(URL + "playlist/" + pl.id + "/song/2"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(404, get.getStatusCode()); // random playlist with no name : 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist with no song number : 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist with too many songs: 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "60"); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist 'toto' post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "15"); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(15, obj.getInt("added")); Playlist rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(15, rand.playtime); assertEquals(15, rand.songs); assertEquals("toto", rand.name); // get first song get = new GetMethod(URL + "playlist/" + rand.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); Song s = new Song(new JSONObject(get.getResponseBodyAsString()).getJSONObject("song").toString()); assertEquals(s.id, obj.getInt("first_song")); // all random songs should fit in this hashset HashSet<Song> randSet = new HashSet<Song>(15); get = new GetMethod(URL + "playlist/" + rand.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("toto", obj.get("name")); arr = obj.getJSONArray("playlist"); assertEquals(15, arr.length()); for (int i = 0; i < arr.length(); i++) { Song ss = new Song(arr.getJSONObject(i).toString()); assertFalse(randSet.contains(ss)); randSet.add(ss); } // there are 24 songs total in library, try to create a 30 songs playlist post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "30"); post.addParameter("name", "titi"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(24, obj.getInt("added")); rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(24, rand.playtime); assertEquals(24, rand.songs); assertEquals("titi", rand.name); // all 24 random songs should fit in this hashset randSet = new HashSet<Song>(24); get = new GetMethod(URL + "playlist/" + rand.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("titi", obj.get("name")); arr = obj.getJSONArray("playlist"); assertEquals(24, arr.length()); for (int i = 0; i < arr.length(); i++) { Song ss = new Song(arr.getJSONObject(i).toString()); assertFalse(randSet.contains(ss)); randSet.add(ss); } // re-create 'titi' with 10 songs post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "10"); post.addParameter("name", "titi"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(10, obj.getInt("added")); rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(10, rand.playtime); assertEquals(10, rand.songs); assertEquals("titi", rand.name); // playlists for user: 'foo', 'bar', 'toto', 'titi' get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(4, obj.getJSONArray("playlists").length()); foo = new Playlist(obj.getJSONArray("playlists").get(0).toString()); bar = new Playlist(obj.getJSONArray("playlists").get(1).toString()); Playlist toto = new Playlist(obj.getJSONArray("playlists").get(2).toString()); Playlist titi = new Playlist(obj.getJSONArray("playlists").get(3).toString()); assertEquals("foo", foo.name); assertEquals(0, foo.songs); assertEquals("bar", bar.name); assertEquals(2, bar.songs); assertEquals("toto", toto.name); assertEquals(15, toto.songs); assertEquals("titi", titi.name); assertEquals(10, titi.songs); // remove all 4 user playlists post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("playlist_ids[]", "" + foo.id); post.addParameter("playlist_ids[]", "" + bar.id); post.addParameter("playlist_ids[]", "" + toto.id); post.addParameter("playlist_ids[]", "" + titi.id); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // check there are no more user playlists get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); }
From source file:org.mozilla.gecko.favicons.LoadFaviconTask.java
private HttpResponse tryDownloadRecurse(URI faviconURI, HashSet<String> visited) throws URISyntaxException, IOException { if (visited.size() == MAX_REDIRECTS_TO_FOLLOW) { return null; }/*from w w w.jav a 2s.c o m*/ HttpGet request = new HttpGet(faviconURI); HttpResponse response = sHttpClient.execute(request); if (response == null) { return null; } if (response.getStatusLine() != null) { // Was the response a failure? int status = response.getStatusLine().getStatusCode(); // Handle HTTP status codes requesting a redirect. if (status >= 300 && status < 400) { Header header = response.getFirstHeader("Location"); // Handle mad webservers. if (header == null) { return null; } String newURI = header.getValue(); if (newURI == null || newURI.equals(faviconURI.toString())) { return null; } if (visited.contains(newURI)) { // Already been redirected here - abort. return null; } visited.add(newURI); // Sometimes newURI is a value like "/fb/images/favicon.ico" (with no host). In which case, ignore... See #231 URI uri = new URI(newURI); if (uri.getHost() != null) { return tryDownloadRecurse(uri, visited); } } if (status >= 400) { return null; } } return response; }
From source file:edu.ku.brc.specify.toycode.RegPivot.java
/** * @param newTblName//from w w w .jav a2s .com * @param tblName * @param keyName */ private void process(final String newTblName, final String tblName, final String keyName, final String defSQL, final String fillSQL, final boolean isRegBuild) { String sql = String.format("SELECT DISTINCT Name FROM %s", tblName); String sql2 = "SELECT MAX(LENGTH(Value)) FROM " + tblName + " WHERE Name = '%s'"; int instCnt = 0; Statement stmt = null; try { stmt = connection.createStatement(); BasicSQLUtils.setDBConnection(connection); boolean doBuild = true; if (doBuild) { StringBuilder tblSQL = new StringBuilder(String .format("CREATE TABLE %s (`%s` INT(11) NOT NULL AUTO_INCREMENT, \n", newTblName, keyName)); Vector<String> dbFieldNames = new Vector<String>(); Vector<Integer> dbFieldTypes = new Vector<Integer>(); if (defSQL != null) { ResultSet rs = stmt.executeQuery(defSQL); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i > 1) tblSQL.append(",\n "); String name = rsmd.getColumnName(i); dbFieldNames.add(rsmd.getColumnName(i)); dbFieldTypes.add(rsmd.getColumnType(i)); switch (rsmd.getColumnType(i)) { case java.sql.Types.INTEGER: tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name)); break; case java.sql.Types.VARCHAR: tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, 64)); break; case java.sql.Types.TIMESTAMP: tblSQL.append(String.format("`%s` DATETIME DEFAULT NULL", name)); break; default: System.err.println(String.format("No case for %s %d", name, rsmd.getColumnType(i))); break; } } rs.close(); } int secInx = dbFieldNames.size() + 1; System.out.println("secInx: " + secInx + " " + tblSQL.toString()); HashSet<String> nameSet = new HashSet<String>(); int cnt = 0; for (Object nmObj : BasicSQLUtils.querySingleCol(connection, sql)) { String name = nmObj.toString(); if (name.endsWith("ID")) { continue; } name = StringUtils.replace(name, "(", "_"); name = StringUtils.replace(name, ")", "_"); if (nameSet.contains(name)) continue; nameSet.add(name); tblSQL.append(",\n "); if (name.startsWith("num_") || name.startsWith("Usage_")) { tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.INTEGER); } else if (name.endsWith("_number")) { tblSQL.append(String.format("`%s` VARCHAR(16) DEFAULT NULL", name)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.VARCHAR); } else { int maxLen = BasicSQLUtils.getCountAsInt(connection, String.format(sql2, name)); tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, maxLen + 1)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.VARCHAR); } cnt++; } if (isRegBuild) { tblSQL.append(String.format(",\n`RecordType`INT(11) DEFAULT NULL")); } tblSQL.append(String.format(",\n PRIMARY KEY (`%s`)) ENGINE=InnoDB DEFAULT CHARSET=UTF8", keyName)); System.out.println(tblSQL.toString()); DBMSUserMgr dbMgr = DBMSUserMgr.getInstance(); dbMgr.setConnection(connection); if (dbMgr.doesDBHaveTable(newTblName)) { BasicSQLUtils.update(connection, "DROP TABLE " + newTblName); } BasicSQLUtils.update(connection, tblSQL.toString()); HashMap<Integer, String> inxToName = new HashMap<Integer, String>(); StringBuilder fields = new StringBuilder(); StringBuilder vals = new StringBuilder(); int inx = 0; for (String nm : dbFieldNames) { if (fields.length() > 0) fields.append(","); fields.append(nm); if (vals.length() > 0) vals.append(","); vals.append('?'); inxToName.put(inx, nm); inx++; } if (isRegBuild) { if (fields.length() > 0) fields.append(","); fields.append("RecordType"); if (vals.length() > 0) vals.append(","); vals.append('?'); } String insertSQL = String.format("INSERT INTO %s (%s) VALUES(%s)", newTblName, fields.toString(), vals.toString()); System.out.println(insertSQL); PreparedStatement pStmt = connection.prepareStatement(insertSQL); if (isRegBuild) { fillRegisterTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames, inxToName); } else { fillTrackTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames, inxToName); } System.out.println("InstCnt: " + instCnt); pStmt.close(); } boolean doIP = false; if (doIP) { HTTPGetter httpGetter = new HTTPGetter(); sql = "SELECT RegID, IP from reg"; PreparedStatement pStmt = connection.prepareStatement(String .format("UPDATE %s SET lookup=?, Country=?, City=? WHERE %s = ?", newTblName, keyName)); HashMap<String, String> ipHash = new HashMap<String, String>(); HashMap<String, Pair<String, String>> ccHash = new HashMap<String, Pair<String, String>>(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int regId = rs.getInt(1); String ip = rs.getString(2); String hostName = ipHash.get(ip); String country = null; String city = null; if (hostName == null) { String rvStr = new String( httpGetter.doHTTPRequest("http://api.hostip.info/get_html.php?ip=" + ip)); country = parse(rvStr, "Country:"); city = parse(rvStr, "City:"); System.out.println(rvStr + "[" + country + "][" + city + "]"); try { InetAddress addr = InetAddress.getByName(ip); hostName = addr.getHostName(); ipHash.put(ip, hostName); ccHash.put(ip, new Pair<String, String>(country, city)); } catch (UnknownHostException e) { e.printStackTrace(); } } else { Pair<String, String> p = ccHash.get(ip); if (p != null) { country = p.first; city = p.second; } } pStmt.setString(1, hostName); pStmt.setString(2, country); pStmt.setString(3, city); pStmt.setInt(4, regId); pStmt.executeUpdate(); } pStmt.close(); } stmt.close(); colDBConn.close(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Done."); }
From source file:lfsom.visualization.clustering.LFSKMeans.java
/** * cluster centres are initialised by equally sized random chunks of the * input data when there's 150 instances, we assign 50 chosen randomly to * each cluster and calculate its centre from these (the last cluster might * be larger if numInstances mod k < 0) *//*from www . j ava2s.c o m*/ private void initClustersEqualNumbers() { HashSet<Integer> usedIndices = new HashSet<Integer>(); int limit = numberOfInstances / k; // FIXME: Test clustering with new permutation generator! // int[] randPermIndices = RandomTools.permutation(new // Random(RANDOM_SEED), this.numberOfInstances); JDKRandomGenerator rg = new JDKRandomGenerator(); rg.setSeed(RANDOM_SEED); int[] randPermIndices = new RandomDataImpl(rg).nextPermutation(this.numberOfInstances, this.numberOfInstances); for (int clusterIndex = 0; clusterIndex < k; clusterIndex++) { LFSCluster c = new LFSCluster(new double[data[0].length]); // System.out.println("cluster: " + clusterIndex); for (int randPermIndice : randPermIndices) { int currentIndex = randPermIndice; if ((c.getNumberOfInstances() < limit || clusterIndex == k - 1) && !usedIndices.contains(currentIndex)) { c.addIndex(currentIndex); usedIndices.add(currentIndex); // System.out.print(" " + currentIndex); } } // System.out.println(); c.calculateCentroid(data); // clusters[clusterIndex] = c; clusters[clusterIndex] = new LFSCluster(c.getCentroid()); } }
From source file:org.walkmod.conf.providers.yml.RemoveProvidersYMLAction.java
@Override public void doAction(JsonNode node) throws Exception { HashSet<String> providerSet = new HashSet<String>(); for (String elem : providers) { String[] partsType = elem.split(":"); if (partsType.length == 1) { elem = "org.walkmod:walkmod-" + elem + "-plugin:" + elem; }/*from w w w .j av a 2 s .c o m*/ if (partsType.length != 3 && partsType.length != 1) { throw new TransformerException("Invalid conf-provider"); } providerSet.add(elem); } if (node.has("conf-providers")) { JsonNode aux = node.get("conf-providers"); if (aux.isArray()) { ArrayNode providersList = (ArrayNode) node.get("conf-providers"); Iterator<JsonNode> it = providersList.iterator(); ArrayNode newProvidersList = new ArrayNode(provider.getObjectMapper().getNodeFactory()); while (it.hasNext()) { JsonNode next = it.next(); if (next.isObject()) { String type = next.get("type").asText(); String[] parts = type.split(":"); if (parts.length == 1) { type = "org.walkmod:walkmod-" + type + "-plugin:" + type; } else if (parts.length != 3) { throw new TransformerException("Invalid conf-provider"); } if (!providerSet.contains(type)) { newProvidersList.add(next); } } } ObjectNode oNode = (ObjectNode) node; if (newProvidersList.size() > 0) { oNode.set("conf-providers", newProvidersList); } else { oNode.remove("conf-providers"); } provider.write(node); } } }
From source file:it.cnr.icar.eric.server.common.ServerRequestContext.java
/** * Delete of composed objects such as ClassificationNodes within Schemes * can result in duplicate ObjectRefs being deleted. *///from ww w . j a v a 2s.c o m private void removeDuplicateAffectedObjects(AuditableEventType ae) { HashSet<String> ids = new HashSet<String>(); HashSet<ObjectRefType> duplicateObjectRefs = new HashSet<ObjectRefType>(); //Determine duplicate ObjectRefs Iterator<ObjectRefType> iter = ae.getAffectedObjects().getObjectRef().iterator(); while (iter.hasNext()) { ObjectRefType oref = iter.next(); String id = oref.getId(); if (ids.contains(id)) { duplicateObjectRefs.add(oref); } else { ids.add(id); } } //Now remove duplicate ObjectRefs iter = duplicateObjectRefs.iterator(); while (iter.hasNext()) { ae.getAffectedObjects().getObjectRef().remove(iter.next()); } }
From source file:net.spy.memcached.CouchbaseConnection.java
@Override public void reconfigure(Bucket bucket) { reconfiguring = true;// w w w . j ava2s . co m try { // get a new collection of addresses from the received config List<String> servers = bucket.getConfig().getServers(); HashSet<SocketAddress> newServerAddresses = new HashSet<SocketAddress>(); ArrayList<InetSocketAddress> newServers = new ArrayList<InetSocketAddress>(); for (String server : servers) { int finalColon = server.lastIndexOf(':'); if (finalColon < 1) { throw new IllegalArgumentException( "Invalid server ``" + server + "'' in vbucket's server list"); } String hostPart = server.substring(0, finalColon); // String portNum = server.substring(finalColon + 1); InetSocketAddress address = new InetSocketAddress(hostPart, Integer.parseInt("5984")); // add parsed address to our collections newServerAddresses.add(address); newServers.add(address); } // split current nodes to "odd nodes" and "stay nodes" ArrayList<CouchbaseNode> oddNodes = new ArrayList<CouchbaseNode>(); ArrayList<CouchbaseNode> stayNodes = new ArrayList<CouchbaseNode>(); ArrayList<InetSocketAddress> stayServers = new ArrayList<InetSocketAddress>(); for (CouchbaseNode current : nodes) { if (newServerAddresses.contains(current.getSocketAddress())) { stayNodes.add(current); stayServers.add((InetSocketAddress) current.getSocketAddress()); } else { oddNodes.add(current); } } // prepare a collection of addresses for new nodes newServers.removeAll(stayServers); // create a collection of new nodes List<CouchbaseNode> newNodes = createConnections(newServers); // merge stay nodes with new nodes List<CouchbaseNode> mergedNodes = new ArrayList<CouchbaseNode>(); mergedNodes.addAll(stayNodes); mergedNodes.addAll(newNodes); // call update locator with new nodes list and vbucket config nodes = mergedNodes; // schedule shutdown for the oddNodes nodesToShutdown.addAll(oddNodes); } catch (IOException e) { getLogger().error("Connection reconfiguration failed", e); } finally { reconfiguring = false; } }
From source file:com.termmed.statistics.Processor.java
private void printExcluyentList(IReportDetail file, HashSet<Long> conceptList, File outputFold) throws IOException { File exclFile = new File(I_Constants.EXCLUYENT_OUTPUT_FOLDER + "/" + file.getFile() + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv")); File completeDetailFile = new File(I_Constants.STATS_OUTPUT_FOLDER + "/" + file.getFile() + (file.getFile().toLowerCase().endsWith(".csv") ? "" : ".csv")); BufferedReader br = FileHelper.getReader(completeDetailFile); BufferedWriter bw = FileHelper.getWriter(exclFile); Integer sctIdIndex = file.getSctIdIndex(); if (sctIdIndex == null) { sctIdIndex = 1;/*from w ww. j ava2 s . c om*/ } bw.append(br.readLine()); bw.append("\r\n"); String line; String[] spl; while ((line = br.readLine()) != null) { spl = line.split(",", -1); Long cid = Long.parseLong(spl[sctIdIndex]); if (conceptList.contains(cid)) { continue; } bw.append(line); bw.append("\r\n"); conceptList.add(cid); } br.close(); bw.close(); }
From source file:com.haulmont.cuba.core.sys.AbstractViewRepository.java
protected void replaceOverridden(View root, View replacementView, HashSet<View> checked) { checked.add(root);/* www . j a v a 2s . co m*/ List<ViewProperty> replacements = null; for (ViewProperty property : root.getProperties()) { View propertyView = property.getView(); if (propertyView != null) { if (Objects.equals(propertyView.getName(), replacementView.getName()) && replacementView.getEntityClass() == propertyView.getEntityClass()) { if (replacements == null) { replacements = new LinkedList<>(); } replacements .add(new ViewProperty(property.getName(), replacementView, property.getFetchMode())); } else if (propertyView.getEntityClass() != null && !checked.contains(propertyView)) { replaceOverridden(propertyView, replacementView, checked); } } } if (replacements != null) { for (ViewProperty replacement : replacements) { root.addProperty(replacement.getName(), replacement.getView(), replacement.getFetchMode()); } } }