List of usage examples for java.util Set toArray
Object[] toArray();
From source file:com.seyren.mongo.MongoStore.java
@Override public SeyrenResponse<Check> getChecksByState(Set<String> states, Boolean enabled) { List<Check> checks = new ArrayList<Check>(); DBObject query = new BasicDBObject(); query.put("state", object("$in", states.toArray())); if (enabled != null) { query.put("enabled", enabled); }/*from w w w. jav a2 s . c o m*/ DBCursor dbc = getChecksCollection().find(query); while (dbc.hasNext()) { checks.add(mapper.checkFrom(dbc.next())); } dbc.close(); return new SeyrenResponse<Check>().withValues(checks).withTotal(dbc.count()); }
From source file:gemlite.shell.commands.admin.Monitor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @CliCommand(value = "list services", help = "list services") public String services() { Set<ObjectInstance> names = jmxSrv.listMBeans(); List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); if (names == null) return "no services"; Object[] a = names.toArray(); //???//from ww w . j a v a2s.co m Arrays.sort(a, (Comparator) new Comparator<ObjectInstance>() { @Override public int compare(ObjectInstance o1, ObjectInstance o2) { return (o1.getObjectName().toString()).compareTo(o2.getObjectName().toString()); } }); if (LogUtil.getCoreLog().isDebugEnabled()) LogUtil.getCoreLog().debug("get names size:{} values:{}", names.size(), names.toString()); //?service? for (int i = 0; i < a.length; i++) { ObjectInstance oi = (ObjectInstance) a[i]; // service?,??? HashMap<String, Object> service = new HashMap<String, Object>(); service.put(oi.getObjectName().toString(), service); service.put("serviceName", service); try { Map<String, Object> map = jmxSrv.getAttributesValues(oi.getObjectName().toString()); if (map.size() <= 0) { map.put("serviceName", oi.getObjectName().toString()); LogUtil.getCoreLog().warn("jmxSrv.getAttributesValues is null ,ObjectName {}", oi.getObjectName().toString()); result.add(map); } else { result.add(map); } } catch (Exception e) { LogUtil.getCoreLog().error("jmxSrv.getAttributesValues is null ,ObjectName {},error:{}", oi.getObjectName().toString(), e); } } LinkedHashMap<String, HashMap<String, Object>> rs = (LinkedHashMap<String, HashMap<String, Object>>) get( CommandMeta.LIST_SERVICES); if (rs == null) rs = new LinkedHashMap<String, HashMap<String, Object>>(); for (Map<String, Object> map : result) { // ? HashMap<String, Object> service = rs.get(map.get("serviceName")); if (service == null) { service = new HashMap<String, Object>(); } service.putAll(map); // ? rs.put((String) map.get("serviceName"), service); } // ws?? put(CommandMeta.LIST_SERVICES, rs); if (!result.isEmpty()) return result.toString(); return "no services"; }
From source file:com.impetus.kundera.persistence.AssociationBuilder.java
/** * Populates entities related via join table for <code>entity</code> * // w ww.ja v a 2s. c o m * @param entity * @param entityMetadata * @param delegator * @param relation */ void populateRelationFromJoinTable(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator, Relation relation) { JoinTableMetadata jtMetadata = relation.getJoinTableMetadata(); String joinTableName = jtMetadata.getJoinTableName(); Set<String> joinColumns = jtMetadata.getJoinColumns(); Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns(); String joinColumnName = (String) joinColumns.toArray()[0]; String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0]; // EntityMetadata relMetadata = // delegator.getMetadata(relation.getTargetEntity()); Client pClient = delegator.getClient(entityMetadata); String entityId = PropertyAccessorHelper.getId(entity, entityMetadata); List<?> foreignKeys = pClient.getColumnsById(joinTableName, joinColumnName, inverseJoinColumnName, entityId); List childrenEntities = new ArrayList(); for (Object foreignKey : foreignKeys) { EntityMetadata childMetadata = delegator.getMetadata(relation.getTargetEntity()); Object child = delegator.find(relation.getTargetEntity(), foreignKey); Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity() : child; // If child has any bidirectional relationship, process them here Field biDirectionalField = getBiDirectionalField(entity.getClass(), relation.getTargetEntity()); boolean isBidirectionalRelation = (biDirectionalField != null); if (isBidirectionalRelation && obj != null) { String columnValue = PropertyAccessorHelper.getId(obj, childMetadata); Object[] pKeys = pClient.findIdsByColumn(joinTableName, joinColumnName, inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz()); List parents = delegator.find(entity.getClass(), pKeys); PropertyAccessorHelper.set(obj, biDirectionalField, ObjectUtils.getFieldInstance(parents, biDirectionalField)); } childrenEntities.add(obj); } Field childField = relation.getProperty(); try { PropertyAccessorHelper.set(entity, childField, PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(childrenEntities, childField) : childrenEntities.get(0)); PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId); } catch (PropertyAccessException ex) { throw new EntityReaderException(ex); } }
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;// w w w . ja v a2 s . c om try { 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:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.AdjMatrixRandomWalkJGraphT.java
/** * Randomly picks a child of the given source node, and burns it, i.e. puts it into the graph, along with * the corresponding edge/*w w w. j a va 2 s.c o m*/ * @param source * @param graph * @throws LexicalSemanticResourceException * @throws UnsupportedOperationException * @return The child burned, if the source has children. The source itself, otherwise. */ private Entity burnChild(Entity source, DirectedGraph<Entity, DefaultEdge> graph) throws LexicalSemanticResourceException { Set<Entity> children = adjMatrix.getAdjacencies(source); int numChildren = children.size(); Entity child = null; Random generator = new Random(); if (numChildren != 0) { // randomly select one of the children: int pickedChild = generator.nextInt(numChildren); child = (Entity) children.toArray()[pickedChild]; // put child and edge into the graph, if not there yet, and return the child if (!graph.containsVertex(child)) { graph.addVertex(child); //logger.info(child + " added in the RW graph."); graphSize++; } if (!graph.containsEdge(source, child)) { graph.addEdge(source, child); } return child; } else { return source; } }
From source file:edu.isi.pfindr.learn.util.CleanDataUtil.java
public static String preprocessStemAndTokenizeReturnDistinctTokens(String data) { //System.out.println("Preprocess data, remove stop words, stem, tokenize .."); Set<String> transformedSet = new LinkedHashSet<String>(); List<String> stemmedList = new ArrayList<String>(); Tokenizer analyzer = new Tokenizer(Version.LUCENE_30); TokenStream tokenStream = analyzer.tokenStream("", new StringReader(data)); TermAttribute termAttribute;//from w w w. j a v a 2 s .c om String term; try { while (tokenStream.incrementToken()) { termAttribute = tokenStream.getAttribute(TermAttribute.class); term = termAttribute.term(); if (digitPattern.matcher(term).find()) //ignore digits continue; if (stopwords.contains(term)) //ignore stopwords continue; if (term.length() <= 1) //ignore single letter words continue; stemmer.setCurrent(term); stemmer.stem(); stemmedList.add(stemmer.getCurrent()); } transformedSet.addAll(stemmedList); } catch (Exception e) { e.printStackTrace(); } stemmedList.clear(); stemmedList = null; return StringUtils.join(transformedSet.toArray(), " "); }
From source file:org.terasoluna.gfw.common.codelist.ExistInCodeListTest.java
@SuppressWarnings("unchecked") @Test//from www.ja v a 2s . c om public void test_hasInValidCharacterCode() { Customer c = new Customer(); c.gender = 'G'; c.lang = "JP"; Set<ConstraintViolation<Customer>> result = validator.validate(c); assertThat(result.size(), is(1)); assertThat(((ConstraintViolation<Customer>) result.toArray()[0]).getMessage(), is("Does not exist in CD_GENDER")); }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImpl.java
/** * Inserts all of the arguments into the schedules table using * {@link SimpleJdbcTemplate#batchUpdate(String, SqlParameterSource[])}. * /*from w w w .ja v a2 s . c om*/ * @param blocks */ protected void internalStoreBlocks(final Set<PersistenceAvailableBlock> blocks) { SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(blocks.toArray()); this.simpleJdbcTemplate.batchUpdate( "insert into schedules (owner_id, start_time, end_time, visitor_limit, meeting_location) values (:ownerId, :startTime, :endTime, :visitorLimit, :meetingLocation)", batch); }
From source file:ch.cyberduck.cli.TerminalOptionsInputValidator.java
public boolean validate(final CommandLine input) { for (Option o : input.getOptions()) { if (Option.UNINITIALIZED == o.getArgs()) { continue; }/* ww w. j a va2 s. c o m*/ if (o.hasOptionalArg()) { continue; } if (o.getArgs() != o.getValuesList().size()) { console.printf("Missing argument for option %s%n", o.getLongOpt()); return false; } } final TerminalAction action = TerminalActionFinder.get(input); if (null == action) { console.printf("%s%n", "Missing argument"); return false; } if (input.hasOption(TerminalOptionsBuilder.Params.existing.name())) { final String arg = input.getOptionValue(TerminalOptionsBuilder.Params.existing.name()); if (null == TransferAction.forName(arg)) { final Set<TransferAction> actions = new HashSet<TransferAction>( TransferAction.forTransfer(Transfer.Type.download)); actions.add(TransferAction.cancel); console.printf("Invalid argument '%s' for option %s. Must be one of %s%n", arg, TerminalOptionsBuilder.Params.existing.name(), Arrays.toString(actions.toArray())); return false; } switch (action) { case download: if (!validate(arg, Transfer.Type.download)) { return false; } break; case upload: if (!validate(arg, Transfer.Type.upload)) { return false; } break; case synchronize: if (!validate(arg, Transfer.Type.sync)) { return false; } break; case copy: if (!validate(arg, Transfer.Type.copy)) { return false; } break; } } // Validate arguments switch (action) { case list: case download: if (!validate(input.getOptionValue(action.name()))) { return false; } break; case upload: case copy: case synchronize: if (!validate(input.getOptionValue(action.name()))) { return false; } break; } return true; }
From source file:org.stockwatcher.data.cassandra.StockDAOImpl.java
@Override public SortedSet<Stock> findStocks(StatementOptions options, StockCriteria criteria) { validateCriteria(criteria);/*from w ww .jav a 2s. c o m*/ Integer[] industries = criteria.getIndustryIds(); Set<String> exchanges = new HashSet<String>(Arrays.asList(criteria.getExchangeIds())); BigDecimal minPrice = criteria.getMinimumPrice(); BigDecimal maxPrice = criteria.getMaximumPrice(); SortedSet<Stock> stocks = new TreeSet<Stock>(); try { Set<String> symbols = getMatchingSymbols(options, industries, exchanges); Clause where = in("stock_symbol", symbols.toArray()); for (Row row : getStockResultSet(options, where)) { BigDecimal curPrice = row.getDecimal("current_price"); if (row.getBool("active") && (minPrice.compareTo(curPrice) <= 0) && (maxPrice.compareTo(curPrice) >= 0)) { stocks.add(createStock(row)); } } } catch (DriverException e) { throw new DAOException(e); } return stocks; }