List of usage examples for java.util SortedSet contains
boolean contains(Object o);
From source file:com.alibaba.otter.shared.arbitrate.impl.zookeeper.lock.DistributedLock.java
/** * lock??watch????lock?// w ww . j av a2s. c o m */ private Boolean acquireLock(final BooleanMutex mutex) { try { do { if (id == null) {// ?lock long sessionId = getSessionId(); String prefix = "x-" + sessionId + "-"; // String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL); int index = path.lastIndexOf("/"); id = StringUtils.substring(path, index + 1); idName = new LockNode(id); } if (id != null) { List<String> names = zookeeper.getChildren(root); if (names.isEmpty()) { logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName); unlock();// ?? } else { // ? SortedSet<LockNode> sortedNames = new TreeSet<LockNode>(); for (String name : names) { sortedNames.add(new LockNode(name)); } if (sortedNames.contains(idName) == false) { logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName); unlock();// ?? continue; } // ?ownerId ownerId = sortedNames.first().getName(); if (mutex != null && isOwner()) { mutex.set(true);// ? return true; } else if (mutex == null) { return isOwner(); } SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName); if (!lessThanMe.isEmpty()) { // ? LockNode lastChildName = lessThanMe.last(); lastChildId = lastChildName.getName(); // watcher? IZkConnection connection = zookeeper.getConnection(); // zkclient?zk?lock??watcher?zk? ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper(); Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() { public void asyncProcess(WatchedEvent event) { if (!mutex.state()) { // ?????lock acquireLock(mutex); } else { logger.warn("locked successful."); } } }); if (stat == null) { acquireLock(mutex);// ????watcher? } } else { if (isOwner()) { mutex.set(true); } else { logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName); unlock();// ?idownerId?? } } } } } while (id == null); } catch (KeeperException e) { exception = e; if (mutex != null) { mutex.set(true); } } catch (InterruptedException e) { interrupt = e; if (mutex != null) { mutex.set(true); } } catch (Throwable e) { other = e; if (mutex != null) { mutex.set(true); } } if (isOwner() && mutex != null) { mutex.set(true); } return Boolean.FALSE; }
From source file:org.apache.mahout.regression.penalizedlinear.LinearRegularizePath.java
private boolean validateParameter(LinearRegularizePathParameter parameter, String featureNames, String separator) {// w w w . ja v a 2 s.c o m String pattern = FeatureExtractUtility.SeparatorToPattern(separator); if (parameter.dependent.equals("") && parameter.interaction.equals("")) { log.error("both of the dependent and interaction are empty!"); return false; } else { String[] features = featureNames.trim().split(pattern); SortedSet<String> featureSet = new TreeSet<String>(); for (int i = 0; i < features.length; ++i) { featureSet.add(features[i]); } if (!parameter.independent.equals("")) { String[] independent = parameter.independent.split(","); for (int i = 0; i < independent.length; ++i) { if (!featureSet.contains(independent[i])) { return false; } } } if (!parameter.interaction.equals("")) { String[] interaction = parameter.interaction.split(","); for (int i = 0; i < interaction.length; ++i) { if ((!featureSet.contains(interaction[i].split(":")[0])) || (!featureSet.contains(interaction[i].split(":")[1]))) { return false; } } } return featureSet.contains(parameter.dependent); } }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImplTest.java
/** * /* w w w . ja v a 2 s . c o m*/ * @throws Exception */ @Test public void testAddToSchedule() throws Exception { AvailableBlock single = AvailableBlockBuilder.createBlock("20091102-1330", "20091102-1400"); AvailableSchedule schedule = availableScheduleDao.addToSchedule(sampleOwners[0], single); SortedSet<AvailableBlock> stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); schedule = availableScheduleDao.retrieve(sampleOwners[0]); stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImplTest.java
/** * /*from w ww . j av a 2 s .com*/ * @throws Exception */ @Test public void testAddToSchedule10Visitors() throws Exception { AvailableBlock single = AvailableBlockBuilder.createBlock("20091102-1330", "20091102-1400", 10); AvailableSchedule schedule = availableScheduleDao.addToSchedule(sampleOwners[0], single); SortedSet<AvailableBlock> stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); schedule = availableScheduleDao.retrieve(sampleOwners[0]); stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImplTest.java
/** * // w w w . j a v a 2 s .co m * @throws Exception */ @Test public void testAddToScheduleOverrideMeetingLocation() throws Exception { AvailableBlock single = AvailableBlockBuilder.createBlock("20091102-1330", "20091102-1400", 1, "alternate location"); AvailableSchedule schedule = availableScheduleDao.addToSchedule(sampleOwners[0], single); SortedSet<AvailableBlock> stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); schedule = availableScheduleDao.retrieve(sampleOwners[0]); stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(single)); Assert.assertEquals(1, stored.size()); Assert.assertEquals("alternate location", stored.first().getMeetingLocation()); }
From source file:com.oneops.metrics.OneOpsMetrics.java
private void addIbatisMetrics() { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); int initialDelay = 10; //scheduled with ibatis //getMap and register all meters with id and avg time . Runnable registerMetrics = () -> { Map<String, Stats> metrics = StatsPlugin.getStatsMap(); try {//from ww w . ja va 2s .c om final SortedSet<String> registeredMetrics = ooMetricsRegistry.getNames(); final long count = metrics.entrySet().parallelStream().map((e) -> { Meter m = ooMetricsRegistry.meter(e.getKey()); if (m.getCount() != e.getValue().getNoOfCalls()) { ooMetricsRegistry.meter(e.getKey()).mark(e.getValue().getNoOfCalls() - m.getCount()); } if (!registeredMetrics.contains(e.getKey() + "_avg")) { ooMetricsRegistry.register(e.getKey() + "_avg", (Gauge<Double>) e.getValue()::getAverage); } if (!registeredMetrics.contains(e.getKey() + "_max")) { ooMetricsRegistry.register(e.getKey() + "_max", (Gauge<Long>) e.getValue()::getMaxTime); } return 1; }).count(); } catch (Exception e) { logger.warn("There was an error in reporting metrics", e); } if (logger.isDebugEnabled()) { logger.debug("Finished reporting metrics for ibatis" + metrics.size()); } }; executor.scheduleAtFixedRate(registerMetrics, initialDelay, 60, TimeUnit.SECONDS); }
From source file:org.onehippo.cms7.essentials.dashboard.services.ContentBeansService.java
private void processMissing(final List<HippoContentBean> missingBeans) { for (HippoContentBean missingBean : missingBeans) { final SortedSet<String> mySupertypes = missingBean.getContentType().getSuperTypes(); if (mySupertypes.contains("hippogallery:relaxed")) { final Path javaClass = createJavaClass(missingBean); JavaSourceUtils.createHippoBean(javaClass, context.beansPackageName(), missingBean.getName(), missingBean.getName()); JavaSourceUtils.addExtendsClass(javaClass, HIPPO_GALLERY_IMAGE_SET_CLASS); JavaSourceUtils.addImport(javaClass, EssentialConst.HIPPO_IMAGE_SET_IMPORT); addMethods(missingBean, javaClass, new ArrayList<String>()); }//from w ww . jav a 2s. c o m } }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImplTest.java
/** * /* ww w . ja va2 s . co m*/ * @throws Exception */ @Test public void testAddRemoveScheduleMultiples() throws Exception { Set<AvailableBlock> blocks = AvailableBlockBuilder.createBlocks("9:00 AM", "5:00 PM", "MWF", CommonDateOperations.parseDatePhrase("20091102"), CommonDateOperations.parseDatePhrase("20091127")); AvailableSchedule schedule = availableScheduleDao.addToSchedule(sampleOwners[0], blocks); SortedSet<AvailableBlock> stored = schedule.getAvailableBlocks(); Assert.assertEquals(12, stored.size()); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091102-0900", "20091102-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091104-0900", "20091104-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091106-0900", "20091106-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091109-0900", "20091109-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091111-0900", "20091111-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091113-0900", "20091113-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091116-0900", "20091116-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091118-0900", "20091118-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091120-0900", "20091120-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091123-0900", "20091123-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091125-0900", "20091125-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091127-0900", "20091127-1700"))); schedule = availableScheduleDao.retrieve(sampleOwners[0]); stored = schedule.getAvailableBlocks(); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091102-0900", "20091102-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091104-0900", "20091104-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091106-0900", "20091106-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091109-0900", "20091109-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091111-0900", "20091111-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091113-0900", "20091113-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091116-0900", "20091116-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091118-0900", "20091118-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091120-0900", "20091120-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091123-0900", "20091123-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091125-0900", "20091125-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091127-0900", "20091127-1700"))); // remove some blocks from the middle of a few days schedule = availableScheduleDao.removeFromSchedule(sampleOwners[0], AvailableBlockBuilder.createBlock("20091111-1200", "20091111-1300")); stored = schedule.getAvailableBlocks(); Assert.assertFalse(stored.contains(AvailableBlockBuilder.createBlock("20091111-0900", "20091111-1700"))); Assert.assertFalse(stored.contains(AvailableBlockBuilder.createBlock("20091111-1200", "20091111-1300"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091111-0900", "20091111-1200"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091111-1300", "20091111-1700"))); schedule = availableScheduleDao.removeFromSchedule(sampleOwners[0], AvailableBlockBuilder.createBlock("20091116-0900", "20091116-1200")); stored = schedule.getAvailableBlocks(); Assert.assertFalse(stored.contains(AvailableBlockBuilder.createBlock("20091116-0900", "20091116-1200"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091116-1200", "20091116-1700"))); schedule = availableScheduleDao.removeFromSchedule(sampleOwners[0], AvailableBlockBuilder.createBlock("20091127-1600", "20091127-1800")); stored = schedule.getAvailableBlocks(); Assert.assertFalse(stored.contains(AvailableBlockBuilder.createBlock("20091127-0900", "20091127-1700"))); Assert.assertTrue(stored.contains(AvailableBlockBuilder.createBlock("20091127-0900", "20091127-1600"))); }
From source file:org.apache.ctakes.ytex.kernel.KernelUtilImpl.java
/** * this can be very large - avoid loading the entire jdbc ResultSet into * memory//from w w w .jav a 2 s .c o m */ @Override public InstanceData loadInstances(String strQuery) { final InstanceData instanceLabel = new InstanceData(); PreparedStatement s = null; Connection conn = null; ResultSet rs = null; try { // jdbcTemplate.query(strQuery, new RowCallbackHandler() { RowCallbackHandler ch = new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { String label = ""; int run = 0; int fold = 0; boolean train = true; long instanceId = rs.getLong(1); String className = rs.getString(2); if (rs.getMetaData().getColumnCount() >= 3) train = rs.getBoolean(3); if (rs.getMetaData().getColumnCount() >= 4) { label = rs.getString(4); if (label == null) label = ""; } if (rs.getMetaData().getColumnCount() >= 5) fold = rs.getInt(5); if (rs.getMetaData().getColumnCount() >= 6) run = rs.getInt(6); // get runs for label SortedMap<Integer, SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>> runToInstanceMap = instanceLabel .getLabelToInstanceMap().get(label); if (runToInstanceMap == null) { runToInstanceMap = new TreeMap<Integer, SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>>(); instanceLabel.getLabelToInstanceMap().put(label, runToInstanceMap); } // get folds for run SortedMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>> foldToInstanceMap = runToInstanceMap .get(run); if (foldToInstanceMap == null) { foldToInstanceMap = new TreeMap<Integer, SortedMap<Boolean, SortedMap<Long, String>>>(); runToInstanceMap.put(run, foldToInstanceMap); } // get train/test set for fold SortedMap<Boolean, SortedMap<Long, String>> ttToClassMap = foldToInstanceMap.get(fold); if (ttToClassMap == null) { ttToClassMap = new TreeMap<Boolean, SortedMap<Long, String>>(); foldToInstanceMap.put(fold, ttToClassMap); } // get instances for train/test set SortedMap<Long, String> instanceToClassMap = ttToClassMap.get(train); if (instanceToClassMap == null) { instanceToClassMap = new TreeMap<Long, String>(); ttToClassMap.put(train, instanceToClassMap); } // set the instance class instanceToClassMap.put(instanceId, className); // add the class to the labelToClassMap SortedSet<String> labelClasses = instanceLabel.getLabelToClassMap().get(label); if (labelClasses == null) { labelClasses = new TreeSet<String>(); instanceLabel.getLabelToClassMap().put(label, labelClasses); } if (!labelClasses.contains(className)) labelClasses.add(className); } }; conn = this.jdbcTemplate.getDataSource().getConnection(); s = conn.prepareStatement(strQuery, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); if ("MySQL".equals(conn.getMetaData().getDatabaseProductName())) { s.setFetchSize(Integer.MIN_VALUE); } else if (s.getClass().getName().equals("com.microsoft.sqlserver.jdbc.SQLServerStatement")) { try { BeanUtils.setProperty(s, "responseBuffering", "adaptive"); } catch (IllegalAccessException e) { log.warn("error setting responseBuffering", e); } catch (InvocationTargetException e) { log.warn("error setting responseBuffering", e); } } rs = s.executeQuery(); while (rs.next()) { ch.processRow(rs); } } catch (SQLException j) { log.error("loadInstances failed", j); throw new RuntimeException(j); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (s != null) { try { s.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } return instanceLabel; }
From source file:com.streamsets.pipeline.stage.destination.cassandra.CassandraTarget.java
@Override protected List<ConfigIssue> init() { List<ConfigIssue> issues = super.init(); errorRecordHandler = new DefaultErrorRecordHandler(getContext()); Target.Context context = getContext(); if (addresses.isEmpty()) { issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00)); }// w w w . jav a 2 s .co m for (String address : addresses) { if (address.isEmpty()) { issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_01)); } } contactPoints = new ArrayList<>(addresses.size()); for (String address : addresses) { if (null == address) { LOG.warn("A null value was passed in as a contact point."); // This isn't valid but InetAddress won't complain so we skip this entry. continue; } try { contactPoints.add(InetAddress.getByName(address)); } catch (UnknownHostException e) { issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_04, address)); } } if (contactPoints.size() < 1) { issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00)); } if (!qualifiedTableName.contains(".")) { issues.add( context.createConfigIssue(Groups.CASSANDRA.name(), "qualifiedTableName", Errors.CASSANDRA_02)); } else { if (checkCassandraReachable(issues)) { List<String> invalidColumns = checkColumnMappings(); if (invalidColumns.size() != 0) { issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "columnNames", Errors.CASSANDRA_08, Joiner.on(", ").join(invalidColumns))); } } } if (issues.isEmpty()) { cluster = Cluster.builder().addContactPoints(contactPoints).withCompression(compression).withPort(port) // If authentication is disabled on the C* cluster, this method has no effect. .withCredentials(username, password).build(); try { session = cluster.connect(); statementCache = CacheBuilder.newBuilder() // No expiration as prepared statements are good for the entire session. .build(new CacheLoader<SortedSet<String>, PreparedStatement>() { @Override public PreparedStatement load(SortedSet<String> columns) { // The INSERT query we're going to perform (parameterized). SortedSet<String> statementColumns = new TreeSet<>(); for (String fieldPath : columnMappings.keySet()) { final String fieldName = fieldPath.replaceAll("/", ""); if (columns.contains(fieldName)) { statementColumns.add(fieldName); } } final String query = String.format("INSERT INTO %s (%s) VALUES (%s);", qualifiedTableName, Joiner.on(", ").join(statementColumns), Joiner.on(", ").join(Collections.nCopies(statementColumns.size(), "?"))); LOG.trace("Prepared Query: {}", query); return session.prepare(query); } }); } catch (NoHostAvailableException | AuthenticationException | IllegalStateException e) { issues.add(context.createConfigIssue(null, null, Errors.CASSANDRA_03, e.toString())); } } return issues; }