List of usage examples for java.util HashSet isEmpty
public boolean isEmpty()
From source file:de.uni_koblenz.jgralab.utilities.csv2tg.Csv2Tg.java
private String[] getFilesInFolder(String[] filenames) { HashSet<String> fileList = new HashSet<>(); for (String filename : filenames) { File file = new File(filename).getAbsoluteFile(); if (!file.exists()) { throw new RuntimeException("File or folder \"" + filename + "\" does not exist!"); }/*from w w w . j a va 2s.co m*/ if (file.isDirectory()) { for (File foundFile : file.listFiles(this)) { fileList.add(foundFile.getAbsolutePath()); } } else { fileList.add(file.getAbsolutePath()); } } if (fileList.isEmpty()) { throw new RuntimeException("No csv-files to convert to a tg-file."); } String[] result = new String[fileList.size()]; return fileList.toArray(result); }
From source file:org.apache.storm.daemon.supervisor.Supervisor.java
void killWorkers(Collection<String> workerIds, ContainerLauncher launcher) throws InterruptedException, IOException { HashSet<Killable> containers = new HashSet<>(); for (String workerId : workerIds) { try {//from w w w .j av a 2s. com Killable k = launcher.recoverContainer(workerId, localState); if (!k.areAllProcessesDead()) { k.kill(); containers.add(k); } else { k.cleanUp(); } } catch (Exception e) { LOG.error("Error trying to kill {}", workerId, e); } } int shutdownSleepSecs = ObjectReader.getInt(conf.get(DaemonConfig.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS), 1); if (!containers.isEmpty()) { Time.sleepSecs(shutdownSleepSecs); } for (Killable k : containers) { try { k.forceKill(); long start = Time.currentTimeMillis(); while (!k.areAllProcessesDead()) { if ((Time.currentTimeMillis() - start) > 10_000) { throw new RuntimeException("Giving up on killing " + k + " after " + (Time.currentTimeMillis() - start) + " ms"); } Time.sleep(100); k.forceKill(); } k.cleanUp(); } catch (Exception e) { LOG.error("Error trying to clean up {}", k, e); } } }
From source file:com.aimluck.eip.wiki.WikiSelectData.java
@Override protected SelectQuery<EipTWiki> buildSelectQueryForFilter(SelectQuery<EipTWiki> query, RunData rundata, Context context) {/*from ww w . jav a2 s . c o m*/ if (current_filterMap.containsKey("category")) { // ???????? List<String> categoryIds = current_filterMap.get("category"); categoryId = categoryIds.get(0).toString(); if (null == topWikiList) { topWikiList = WikiUtils.loadTopWikiList(rundata); } boolean existCategory = false; if (topWikiList != null && topWikiList.size() > 0) { for (WikiResultData category : topWikiList) { if (categoryId.equals(category.getId().toString())) { existCategory = true; break; } } } if (!existCategory) { categoryId = ""; current_filterMap.remove("category"); } else { Expression exp = ExpressionFactory.matchExp(EipTWiki.PARENT_ID_PROPERTY, categoryId); Expression exp2 = ExpressionFactory.matchDbExp(EipTWiki.WIKI_ID_PK_COLUMN, categoryId); query.andQualifier(exp.orExp(exp2)); } updateCategoryName(); } super.buildSelectQueryForFilter(query, rundata, context); if (current_filterMap.containsKey("post")) { // ???????? List<String> postIds = current_filterMap.get("post"); HashSet<Integer> userIds = new HashSet<Integer>(); for (String post : postIds) { List<Integer> userId = ALEipUtils.getUserIds(post); userIds.addAll(userId); } if (userIds.isEmpty()) { userIds.add(-1); } Expression exp = ExpressionFactory.inExp(EipTWiki.UPDATE_USER_ID_PROPERTY, userIds); query.andQualifier(exp); postId = postIds.get(0).toString(); updatePostName(); } String search = ALEipUtils.getTemp(rundata, context, LIST_SEARCH_STR); if (search != null && !"".equals(search)) { current_search = search; Expression ex1 = ExpressionFactory.likeExp(EipTWiki.NOTE_PROPERTY, "%" + search + "%"); Expression ex2 = ExpressionFactory.likeExp(EipTWiki.WIKI_NAME_PROPERTY, "%" + search + "%"); SelectQuery<EipTWiki> q = Database.query(EipTWiki.class); q.andQualifier(ex1.orExp(ex2)); List<EipTWiki> queryList = q.fetchList(); List<Integer> resultid = new ArrayList<Integer>(); for (EipTWiki item : queryList) { resultid.add(item.getWikiId()); } if (resultid.size() == 0) { // ??????????-1 resultid.add(-1); } Expression ex = ExpressionFactory.inDbExp(EipTWiki.WIKI_ID_PK_COLUMN, resultid); query.andQualifier(ex); } return query; }
From source file:org.openhab.binding.maxcul.internal.MaxCulBinding.java
@Override public void maxCulMsgReceived(String data, boolean isBroadcast) { logger.debug("Received data from CUL: " + data); MaxCulMsgType msgType = BaseMsg.getMsgType(data); /*//from w w w .ja v a 2 s . com * Check if it's broadcast and we're in pair mode or a PAIR_PING message * directly for us */ if (((pairMode && isBroadcast) || !isBroadcast) && msgType == MaxCulMsgType.PAIR_PING) { logger.debug("Got PAIR_PING message"); MaxCulBindingConfig configWithTempsConfig = null; /* process packet */ PairPingMsg pkt = new PairPingMsg(data); /* Match serial number to binding configuration */ Collection<MaxCulBindingConfig> bindingConfigs = getBindingsBySerial(pkt.serial); /* * only respond and set pairing info if we found at least one * binding config */ if (bindingConfigs != null) { logger.debug("Found " + bindingConfigs.size() + " configs for " + pkt.serial); for (MaxCulBindingConfig bc : bindingConfigs) { /* Set pairing information */ bc.setPairedInfo(pkt.srcAddrStr); /* * where it came from gives * the addr of the device */ if (bc.isTemperatureConfigSet() && configWithTempsConfig == null) { configWithTempsConfig = bc; } } /* if none have values set then send default from first config */ if (configWithTempsConfig == null) { logger.debug("Using default temperature configuration from config 0"); configWithTempsConfig = (MaxCulBindingConfig) bindingConfigs.toArray()[0]; } /* get device associations */ HashSet<MaxCulBindingConfig> associations = null; for (MaxCulBindingProvider provider : super.providers) { associations = provider.getAssociations(configWithTempsConfig.getSerialNumber()); if (associations != null && associations.isEmpty() == false) { logger.debug("Found associations"); break; } } /* start the initialisation sequence */ logger.debug("Creating pairing sequencer"); PairingInitialisationSequence ps = new PairingInitialisationSequence(this.DEFAULT_GROUP_ID, messageHandler, configWithTempsConfig, associations); messageHandler.startSequence(ps, pkt); } else { logger.error("Pairing failed: Unable to find binding config for device " + pkt.serial); } } else { switch (msgType) { /* * TODO there are other incoming messages that aren't handled that * could be */ case WALL_THERMOSTAT_CONTROL: WallThermostatControlMsg wallThermCtrlMsg = new WallThermostatControlMsg(data); wallThermCtrlMsg.printMessage(); for (MaxCulBindingProvider provider : super.providers) { Collection<MaxCulBindingConfig> bindingConfigs = provider .getConfigsForRadioAddr(wallThermCtrlMsg.srcAddrStr); for (MaxCulBindingConfig bc : bindingConfigs) { if (bc.getFeature() == MaxCulFeature.THERMOSTAT && wallThermCtrlMsg.getDesiredTemperature() != null) { String itemName = provider.getItemNameForConfig(bc); eventPublisher.postUpdate(itemName, new DecimalType(wallThermCtrlMsg.getDesiredTemperature())); } else if (bc.getFeature() == MaxCulFeature.TEMPERATURE && wallThermCtrlMsg.getMeasuredTemperature() != null) { String itemName = provider.getItemNameForConfig(bc); eventPublisher.postUpdate(itemName, new DecimalType(wallThermCtrlMsg.getMeasuredTemperature())); } // TODO switch mode between manual/automatic? } } /* reply only if not broadcast */ if (isBroadcast == false) this.messageHandler.sendAck(wallThermCtrlMsg); break; case SET_TEMPERATURE: SetTemperatureMsg setTempMsg = new SetTemperatureMsg(data); setTempMsg.printMessage(); for (MaxCulBindingProvider provider : super.providers) { Collection<MaxCulBindingConfig> bindingConfigs = provider .getConfigsForRadioAddr(setTempMsg.srcAddrStr); for (MaxCulBindingConfig bc : bindingConfigs) { if (bc.getFeature() == MaxCulFeature.THERMOSTAT) { String itemName = provider.getItemNameForConfig(bc); eventPublisher.postUpdate(itemName, new DecimalType(setTempMsg.getDesiredTemperature())); } // TODO switch mode between manual/automatic? } } /* respond to device */ if (isBroadcast == false) this.messageHandler.sendAck(setTempMsg); break; case THERMOSTAT_STATE: ThermostatStateMsg thermStateMsg = new ThermostatStateMsg(data); thermStateMsg.printMessage(); for (MaxCulBindingProvider provider : super.providers) { Collection<MaxCulBindingConfig> bindingConfigs = provider .getConfigsForRadioAddr(thermStateMsg.srcAddrStr); for (MaxCulBindingConfig bc : bindingConfigs) { String itemName = provider.getItemNameForConfig(bc); if (bc.getFeature() == MaxCulFeature.THERMOSTAT && thermStateMsg.getDesiredTemperature() != null) { eventPublisher.postUpdate(itemName, new DecimalType(thermStateMsg.getDesiredTemperature())); } else if (bc.getFeature() == MaxCulFeature.TEMPERATURE && thermStateMsg.getMeasuredTemperature() != null) { eventPublisher.postUpdate(itemName, new DecimalType(thermStateMsg.getMeasuredTemperature())); } else if (bc.getFeature() == MaxCulFeature.BATTERY) { eventPublisher.postUpdate(itemName, thermStateMsg.getBatteryLow() ? OnOffType.ON : OnOffType.OFF); } else if (bc.getFeature() == MaxCulFeature.MODE) { eventPublisher.postUpdate(itemName, new DecimalType(thermStateMsg.getControlMode().toInt())); } else if (bc.getFeature() == MaxCulFeature.VALVE_POS) { eventPublisher.postUpdate(itemName, new DecimalType(thermStateMsg.getValvePos())); } // TODO switch mode between manual/automatic? } } /* respond to device */ if (isBroadcast == false) this.messageHandler.sendAck(thermStateMsg); break; case WALL_THERMOSTAT_STATE: WallThermostatStateMsg wallThermStateMsg = new WallThermostatStateMsg(data); wallThermStateMsg.printMessage(); for (MaxCulBindingProvider provider : super.providers) { Collection<MaxCulBindingConfig> bindingConfigs = provider .getConfigsForRadioAddr(wallThermStateMsg.srcAddrStr); for (MaxCulBindingConfig bc : bindingConfigs) { String itemName = provider.getItemNameForConfig(bc); if (bc.getFeature() == MaxCulFeature.THERMOSTAT && wallThermStateMsg.getDesiredTemperature() != null) { eventPublisher.postUpdate(itemName, new DecimalType(wallThermStateMsg.getDesiredTemperature())); } else if (bc.getFeature() == MaxCulFeature.TEMPERATURE && wallThermStateMsg.getMeasuredTemperature() != null) { eventPublisher.postUpdate(itemName, new DecimalType(wallThermStateMsg.getMeasuredTemperature())); } else if (bc.getFeature() == MaxCulFeature.BATTERY) { eventPublisher.postUpdate(itemName, wallThermStateMsg.getBatteryLow() ? OnOffType.ON : OnOffType.OFF); } else if (bc.getFeature() == MaxCulFeature.MODE) { eventPublisher.postUpdate(itemName, new DecimalType(wallThermStateMsg.getControlMode().toInt())); } } } /* respond to device */ if (isBroadcast == false) this.messageHandler.sendAck(wallThermStateMsg); break; case TIME_INFO: TimeInfoMsg timeMsg = new TimeInfoMsg(data); timeMsg.printMessage(); TimeUpdateRequestSequence timeSeq = new TimeUpdateRequestSequence(this.tzStr, messageHandler); messageHandler.startSequence(timeSeq, timeMsg); break; case PUSH_BUTTON_STATE: PushButtonMsg pbMsg = new PushButtonMsg(data); pbMsg.printMessage(); for (MaxCulBindingProvider provider : super.providers) { Collection<MaxCulBindingConfig> bindingConfigs = provider .getConfigsForRadioAddr(pbMsg.srcAddrStr); for (MaxCulBindingConfig bc : bindingConfigs) { String itemName = provider.getItemNameForConfig(bc); if (bc.getFeature() == MaxCulFeature.SWITCH) { // ON maps to 'AUTO' if (pbMsg.getMode() == PushButtonMode.AUTO) eventPublisher.postUpdate(itemName, OnOffType.ON); // OFF maps to 'ECO' else if (pbMsg.getMode() == PushButtonMode.ECO) eventPublisher.postUpdate(itemName, OnOffType.OFF); } } } if (isBroadcast == false) this.messageHandler.sendAck(pbMsg); break; default: logger.debug("Unhandled message type " + msgType.toString()); break; } } updateCreditMonitors(); }
From source file:net.unicon.sakora.impl.csv.CsvCommonHandlerService.java
protected int setCurrentAcademicSessions(String[] sessions) { HashSet<String> currentAcademicSessionEids; if (sessions != null) { currentAcademicSessionEids = new HashSet<String>(sessions.length); for (int i = 0; i < sessions.length; i++) { currentAcademicSessionEids.add(sessions[i]); }//from ww w . j av a 2 s.c o m } else { currentAcademicSessionEids = new HashSet<String>(0); } if (currentAcademicSessionEids.isEmpty()) { log.warn( "SakoraCSV has no current academic sessions, this is typically not a valid state, please check your sessions.csv file"); } setCurrentSyncVar(CURRENT_SESSION_EIDS, currentAcademicSessionEids); return currentAcademicSessionEids.size(); }
From source file:Tim.MarkovChains.java
public int getSeedWord(String message, String type, int lastSeed) { String[] words = message.split(" "); HashSet<Integer> wordIds = new HashSet<>(); Connection con = null;//w ww . j av a 2s. c o m for (String word : words) { wordIds.add(getMarkovWordId(word)); } wordIds.remove(lastSeed); if (wordIds.isEmpty()) { return 0; } String ids = StringUtils.join(wordIds, ","); try { con = Tim.db.pool.getConnection(timeout); PreparedStatement s; if (type.equals("say")) { s = con.prepareStatement( "SELECT * FROM (SELECT second_id FROM markov3_say_data msd WHERE msd.first_id = 1 AND msd.third_id != 1 AND msd.second_id IN (" + ids + ") " + "GROUP BY msd.second_id ORDER BY sum(msd.count) ASC LIMIT ?) derived ORDER BY RAND() LIMIT 1"); } else { s = con.prepareStatement( "SELECT * FROM (SELECT second_id FROM markov3_emote_data msd WHERE msd.first_id = 1 AND msd.third_id != 1 AND msd.second_id IN (" + ids + ") " + "GROUP BY msd.second_id ORDER BY sum(msd.count) ASC LIMIT ?) derived ORDER BY RAND() LIMIT 1"); } int innerLimit = 2; if ((words.length / 4) > 2) { innerLimit = words.length / 4; } s.setInt(1, innerLimit); s.executeQuery(); ResultSet rs = s.getResultSet(); if (rs.next()) { return rs.getInt(1); } rs.close(); s.close(); } catch (SQLException ex) { Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (con != null) { con.close(); } } catch (SQLException ex) { Logger.getLogger(Tim.class.getName()).log(Level.SEVERE, null, ex); } } return 0; }
From source file:edu.cens.loci.classes.LociWifiFingerprint.java
public boolean hasNewBssid(LociWifiFingerprint sig) { HashSet<String> diff = new HashSet<String>(sig.getBssids()); diff.removeAll(this.getBssids()); /*/*from w w w. j a v a 2s. c o m*/ Iterator<String> iter = diff.iterator(); String debugMsg = ""; while (iter.hasNext()) { String key = iter.next(); debugMsg = debugMsg + " " + this.getSsid(key); } */ return !diff.isEmpty(); }
From source file:at.treedb.backup.Export.java
/** * Detaches the binary data for every entity of a list. * /*from www . ja v a2s .co m*/ * @param clazz * class of the entity * @param list * list of entities * @return list of duplicated entities with removed binary data, or the * original list, if removing binary data is not necessary. * @throws Exception */ private List<Object> detachBinaryData(DAOiface dao, Class<?> clazz, List<Object> list) throws Exception { // handling for virtual files (data base files) if (clazz.equals(DBfile.class)) { for (Object o : list) { DBfile f = (DBfile) o; write(FILES_DIR, f, date); } } else { HashSet<Field> detachList = new HashSet<Field>(); for (Field f : clazz.getDeclaredFields()) { if (f.getAnnotation(Detach.class) != null) { f.setAccessible(true); detachList.add(f); } } // detach binary data if (!detachList.isEmpty()) { ArrayList<Object> l = new ArrayList<Object>(); for (Object o : list) { // clone the original data! ExportIface export = (ExportIface) ((ExportIface) o).clone(); if (dao.isJPA()) { dao.detach(o); } // enumerate binary fields for (Field f : detachList) { // read optional index - necessary if more than one // binary data element should be detached int index = f.getAnnotation(Detach.class).index(); if ((byte[]) f.get(export) != null) { write(createBinaryPath(index, export), (byte[]) f.get(export), date); } f.set(export, null); } l.add(export); } return l; } } return list; }
From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java
/** * Deletes the given databases from Virtuoso. * * @param dbNames// ww w .j a v a 2 s.c om * The database names. * @param conn * The SQL connection to use. * @throws SQLException * When database access error happens. */ private void deleteDatabases(List<String> dbNames, Connection conn) throws SQLException { HashMap<String, HashSet<String>> dbTables = new HashMap<String, HashSet<String>>(); String userName = conn.getMetaData().getUserName(); // First, get the tables present in each of the given databases. ResultSet rs = null; try { for (String dbName : dbNames) { HashSet<String> tables = new HashSet<String>(); rs = conn.getMetaData().getTables(dbName, userName, null, null); while (rs.next()) { tables.add(rs.getString("TABLE_NAME")); } if (!tables.isEmpty()) { dbTables.put(dbName, tables); } } } finally { SQLUtil.close(rs); } // Second, loop through the above-found tables, delete each. for (Entry<String, HashSet<String>> entry : dbTables.entrySet()) { String dbName = entry.getKey(); HashSet<String> tables = entry.getValue(); for (String tableName : tables) { SQLUtil.executeUpdate("drop table " + dbName + "." + userName + ".\"" + tableName + "\"", conn); } } }
From source file:com.thinkaurelius.titan.diskstorage.solr.Solr5Index.java
private void deleteIndividualFieldsFromIndex(String collectionName, String keyIdField, String docId, HashSet<IndexEntry> fieldDeletions) throws SolrServerException, IOException { if (fieldDeletions.isEmpty()) return;//from w ww. j a v a 2s. com Map<String, String> fieldDeletes = new HashMap<String, String>(1) { { put("set", null); } }; SolrInputDocument doc = new SolrInputDocument(); doc.addField(keyIdField, docId); StringBuilder sb = new StringBuilder(); for (IndexEntry fieldToDelete : fieldDeletions) { doc.addField(fieldToDelete.field, fieldDeletes); sb.append(fieldToDelete).append(","); } if (logger.isTraceEnabled()) logger.trace("Deleting individual fields [{}] for document {}", sb.toString(), docId); UpdateRequest singleDocument = newUpdateRequest(); singleDocument.add(doc); solrClient.request(singleDocument, collectionName); }