Java Code Examples for java.util.Iterator

The following are top voted examples for showing how to use java.util.Iterator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xproject   File: ShiroUtils.java   Source Code and License 8 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T getRealm(Class<? extends Realm> realmType){
	RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
	if(!CollectionUtils.isEmpty(securityManager.getRealms())){
		for(Iterator<Realm> it = securityManager.getRealms().iterator(); it.hasNext();){
			Realm realm = it.next();
			if(realm.getClass().equals(realmType)){
				return (T) realm;
			}
		}
	}
	return null;
}
 
Example 2
Project: ctsms   File: DateUtil.java   Source Code and License 8 votes vote down vote up
public static Map<Integer, ArrayList<TimeZone>> getTimeZoneByOffsets(Collection<TimeZone> timeZones) {
	TreeMap<Integer, ArrayList<TimeZone>> result = new TreeMap<Integer, ArrayList<TimeZone>>();
	if (timeZones != null) {
		Iterator<TimeZone> it = timeZones.iterator();
		while (it.hasNext()) {
			TimeZone timeZone = it.next();
			int timeZoneOffset = timeZone.getRawOffset();
			ArrayList<TimeZone> offsetTimeZones;
			if (!result.containsKey(timeZoneOffset)) {
				offsetTimeZones = new ArrayList<TimeZone>();
				result.put(timeZoneOffset, offsetTimeZones);
			} else {
				offsetTimeZones = result.get(timeZoneOffset);
			}
			offsetTimeZones.add(timeZone);
		}
	}
	return result;
}
 
Example 3
Project: lib-commons-httpclient   File: HttpState.java   Source Code and License 7 votes vote down vote up
/**
 * Find matching {@link Credentials credentials} for the given authentication scope.
 *
 * @param map the credentials hash map
 * @param token the {@link AuthScope authentication scope}
 * @return the credentials 
 * 
 */
private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
    // see if we get a direct hit
    Credentials creds = (Credentials)map.get(authscope);
    if (creds == null) {
        // Nope.
        // Do a full scan
        int bestMatchFactor  = -1;
        AuthScope bestMatch  = null;
        Iterator items = map.keySet().iterator();
        while (items.hasNext()) {
            AuthScope current = (AuthScope)items.next();
            int factor = authscope.match(current);
            if (factor > bestMatchFactor) {
                bestMatchFactor = factor;
                bestMatch = current;
            }
        }
        if (bestMatch != null) {
            creds = (Credentials)map.get(bestMatch);
        }
    }
    return creds;
}
 
Example 4
Project: JRediClients   File: AbstractCacheMap.java   Source Code and License 7 votes vote down vote up
@Override
public Iterator<V> iterator() {
    return new MapIterator<V>() {
        @Override
        public V next() {
            if (mapEntry == null) {
                throw new NoSuchElementException();
            }
            
            V value = readValue(mapEntry.getValue());
            mapEntry = null;
            return value;
        }

        @Override
        public void remove() {
            if (mapEntry == null) {
                throw new IllegalStateException();
            }
            map.remove(mapEntry.getKey(), mapEntry.getValue());
            mapEntry = null;
        }
    };
}
 
Example 5
Project: boohee_v5.6   File: Fallback.java   Source Code and License 7 votes vote down vote up
public synchronized void a(String[] strArr) {
    for (int size = this.j.size() - 1; size >= 0; size--) {
        for (CharSequence equals : strArr) {
            if (TextUtils.equals(((e) this.j.get(size)).a, equals)) {
                this.j.remove(size);
                break;
            }
        }
    }
    Iterator it = this.j.iterator();
    int i = 0;
    while (it.hasNext()) {
        e eVar = (e) it.next();
        i = eVar.b > i ? eVar.b : i;
    }
    for (int i2 = 0; i2 < strArr.length; i2++) {
        a(new e(strArr[i2], (strArr.length + i) - i2));
    }
}
 
Example 6
Project: rapidminer   File: LibSVMLearner.java   Source Code and License 7 votes vote down vote up
/**
 * Creates a support vector problem for the LibSVM.
 * 
 * @throws UserError
 */
private svm_problem getProblem(ExampleSet exampleSet) throws UserError {
	log("Creating LibSVM problem.");
	FastExample2SparseTransform ripper = new FastExample2SparseTransform(exampleSet);
	int nodeCount = 0;
	svm_problem problem = new svm_problem();
	problem.l = exampleSet.size();
	problem.y = new double[exampleSet.size()];
	problem.x = new svm_node[exampleSet.size()][];
	Iterator<Example> i = exampleSet.iterator();
	Attribute label = exampleSet.getAttributes().getLabel();
	int j = 0;
	while (i.hasNext()) {
		Example e = i.next();
		problem.x[j] = makeNodes(e, ripper);
		problem.y[j] = e.getValue(label);
		nodeCount += problem.x[j].length;
		j++;
	}
	log("Created " + nodeCount + " nodes for " + j + " examples.");
	return problem;
}
 
Example 7
Project: common-services   File: ServiceMessageHandlerTest.java   Source Code and License 7 votes vote down vote up
private ResultSet<String> createBlockingResultSet(BlockingQueue<String> queue, Supplier<Boolean> finished) {
  AtomicReference<String> ref = new AtomicReference<>();
  AtomicInteger sizeref = new AtomicInteger(0);
  Iterator<String> blockingIterator = new Iterator<String>() {
    @Override
    public boolean hasNext() {
      if (ref.get() != null) return true;
      while (!finished.get()) {
        if (ref.get() != null) return true;
        try {
          ref.set(queue.poll(1000, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      return ref.get() != null;
    }

    @Override
    public String next() {
      sizeref.incrementAndGet();
      return ref.getAndSet(null);
    }
  };
  return createResultSet(blockingIterator);
}
 
Example 8
Project: weak-semi-crf-naacl2016   File: AttributedWord.java   Source Code and License 7 votes vote down vote up
@Override
public String toString(){
	StringBuilder sb = new StringBuilder();
	sb.append(this.getName());
	Iterator<String> attNames = this._attrs.keySet().iterator();
	while(attNames.hasNext()){
		String attName = attNames.next();
		ArrayList<String> attValues = this._attrs.get(attName);
		sb.append("|");
		sb.append(attName);
		for(String attValue : attValues){
			sb.append(":");
			sb.append(attValue);
		}
	}
	return sb.toString();
}
 
Example 9
Project: dhus-core   File: CheckIterator.java   Source Code and License 7 votes vote down vote up
/**
 * Checks number of elements within a iterator.
 * @param it iterator to check
 * @param n number of elements found
 * @return true if n equals elements number in iterator, otherwise false.
 */
public static boolean checkElementNumber (Iterator<?> it, int n)
{
   int i = 0;      
   while (it.hasNext ())
   {
      if (it.next () == null)
      {
         return false;
      }
      i++;
   }
   return (i == n);
}
 
Example 10
Project: guava-mock   File: Hashing.java   Source Code and License 7 votes vote down vote up
/**
 * Returns a hash code, having the same bit length as each of the input hash codes, that combines
 * the information of these hash codes in an ordered fashion. That is, whenever two equal hash
 * codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
 * was computed from the <i>same</i> input hash codes in the <i>same</i> order.
 *
 * @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
 *     have the same bit length
 */
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
  Iterator<HashCode> iterator = hashCodes.iterator();
  checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
  int bits = iterator.next().bits();
  byte[] resultBytes = new byte[bits / 8];
  for (HashCode hashCode : hashCodes) {
    byte[] nextBytes = hashCode.asBytes();
    checkArgument(
        nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
    for (int i = 0; i < nextBytes.length; i++) {
      resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
    }
  }
  return HashCode.fromBytesNoCopy(resultBytes);
}
 
Example 11
Project: ctsms   File: ProbandListEntryTagValueBean.java   Source Code and License 7 votes vote down vote up
public static void copyProbandListEntryTagValueOutToIn(ProbandListEntryTagValueInVO in, ProbandListEntryTagValueOutVO out) {
	if (in != null && out != null) {
		ProbandListEntryOutVO listEntryVO = out.getListEntry();
		ProbandListEntryTagOutVO tagVO = out.getTag();
		Collection<InputFieldSelectionSetValueOutVO> tagValueVOs = out.getSelectionValues();
		in.setBooleanValue(out.getBooleanValue());
		in.setDateValue(out.getDateValue());
		in.setTimeValue(out.getTimeValue());
		in.setFloatValue(out.getFloatValue());
		in.setId(out.getId());
		in.setListEntryId(listEntryVO == null ? null : listEntryVO.getId());
		in.setLongValue(out.getLongValue());
		ArrayList<Long> selectionValueIds = new ArrayList<Long>(tagValueVOs.size());
		Iterator<InputFieldSelectionSetValueOutVO> tagValueVOsIt = tagValueVOs.iterator();
		while (tagValueVOsIt.hasNext()) {
			selectionValueIds.add(tagValueVOsIt.next().getId());
		}
		in.setSelectionValueIds(selectionValueIds);
		in.setTagId(tagVO == null ? null : tagVO.getId());
		in.setTextValue(out.getTextValue());
		in.setTimestampValue(out.getTimestampValue());
		in.setInkValues(out.getInkValues());
		in.setVersion(out.getVersion());
	}
}
 
Example 12
Project: ctsms   File: SearchServiceImpl.java   Source Code and License 7 votes vote down vote up
private static CriteriaOutVO obfuscateCriterions(CriteriaOutVO criteriaVO) {
	if (criteriaVO != null) {
		CriteriaOutVO result = new CriteriaOutVO(criteriaVO);
		ArrayList<CriterionOutVO> obfuscatedCriterions = new ArrayList<CriterionOutVO>();
		Iterator<CriterionOutVO> criterionsIt = criteriaVO.getCriterions().iterator();
		while (criterionsIt.hasNext()) {
			CriterionOutVO obfuscatedCriterion = new CriterionOutVO(criterionsIt.next());
			obfuscatedCriterion.setCriteria(result);
			CriterionPropertyVO property = obfuscatedCriterion.getProperty();
			if (property != null && OmittedFields.isOmitted(property.getProperty())) {
				obfuscatedCriterion.setStringValue(OmittedFields.OBFUSCATED_STRING);
			}
			obfuscatedCriterions.add(obfuscatedCriterion);
		}
		result.setCriterions(obfuscatedCriterions);
		return result;
	}
	return null;
}
 
Example 13
Project: kestrel   File: VariantWriter.java   Source Code and License 7 votes vote down vote up
/**
 * List any valid writers that can be found.
 * 
 * @param loader Loader to search for classes. If <code>null</code>, the system class
 *   loader is used.
 * 
 * @return A sorted list of writer names.
 */
public static String[] listWriters(URLClassLoader loader) {
	
	// Create structures
	Set<String> urlSet = SystemUtil.findSubPackages(PACKAGE_NAME, loader.getURLs(), true);
	
	Iterator<String> setIter = urlSet.iterator();
	
	while (setIter.hasNext()) {
		String url = setIter.next();
		
		try {
			getWriterClass(url, loader);
			
		} catch (Throwable ex) {
			setIter.remove();
		}
	}
	
	// Sort and return
	String[] writers = urlSet.toArray(new String[0]);
	Arrays.sort(writers);
	
	return writers;
}
 
Example 14
Project: Elasticsearch   File: FieldNamesFieldMapper.java   Source Code and License 7 votes vote down vote up
@Override
public MetadataFieldMapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    if (parserContext.indexVersionCreated().before(Version.V_1_3_0)) {
        throw new IllegalArgumentException("type="+CONTENT_TYPE+" is not supported on indices created before version 1.3.0. Is your cluster running multiple datanode versions?");
    }
    
    Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
    if (parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) {
        parseField(builder, builder.name, node, parserContext);
    }

    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = Strings.toUnderscoreCase(entry.getKey());
        Object fieldNode = entry.getValue();
        if (fieldName.equals("enabled")) {
            builder.enabled(nodeBooleanValue(fieldNode));
            iterator.remove();
        }
    }
    return builder;
}
 
Example 15
Project: HCFCore   File: IteratorUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Executes the given closure on each but the last element in the iterator.
 * <p>
 * If the input iterator is null no change is made.
 *
 * @param <E> the type of object the {@link Iterator} contains
 * @param iterator  the iterator to get the input from, may be null
 * @param closure  the closure to perform, may not be null
 * @return the last element in the iterator, or null if iterator is null or empty
 * @throws NullPointerException if closure is null
 * @since 4.1
 */
public static <E> E forEachButLast(final Iterator<E> iterator, final Closure<? super E> closure) {
    if (closure == null) {
        throw new NullPointerException("Closure must not be null.");
    }
    if (iterator != null) {
        while (iterator.hasNext()) {
            final E element = iterator.next();
            if (iterator.hasNext()) {
                closure.execute(element);
            } else {
                return element;
            }
        }
    }
    return null;
}
 
Example 16
Project: soapbox-race-jlauncher   File: Md5Files.java   Source Code and License 7 votes vote down vote up
public static boolean checkModules(String path) {
	setFiles();
	Iterator<Entry<String, byte[]>> iterator = filesToCheck.entrySet().iterator();
	while (iterator.hasNext()) {
		Entry<String, byte[]> next = iterator.next();
		String filename = path.concat("/".concat(next.getKey()));
		try {
			byte[] createChecksum = createChecksum(filename);
			if (!Arrays.equals(next.getValue(), createChecksum)) {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	return true;
}
 
Example 17
Project: OpenJSharp   File: InstructionList.java   Source Code and License 7 votes vote down vote up
/**
 * @return Enumeration that lists all instructions (handles)
 */
public Iterator iterator() {
  return new Iterator() {
    private InstructionHandle ih = start;

    public Object next() {
      InstructionHandle i = ih;
      ih = ih.next;
      return i;
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }

    public boolean hasNext() { return ih != null; }
  };
}
 
Example 18
Project: openjdk-jdk10   File: ArrayBlockingQueueTest.java   Source Code and License 7 votes vote down vote up
/**
 * iterator.remove removes current element
 */
public void testIteratorRemove() {
    final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
    q.add(two);
    q.add(one);
    q.add(three);

    Iterator it = q.iterator();
    it.next();
    it.remove();

    it = q.iterator();
    assertSame(it.next(), one);
    assertSame(it.next(), three);
    assertFalse(it.hasNext());
}
 
Example 19
Project: java-android-websocket-client   File: AbstractConnPool.java   Source Code and License 7 votes vote down vote up
/**
 * Enumerates all available connections.
 *
 * @since 4.3
 */
protected void enumAvailable(final PoolEntryCallback<T, C> callback) {
    this.lock.lock();
    try {
        final Iterator<E> it = this.available.iterator();
        while (it.hasNext()) {
            final E entry = it.next();
            callback.process(entry);
            if (entry.isClosed()) {
                final RouteSpecificPool<T, C, E> pool = getPool(entry.getRoute());
                pool.remove(entry);
                it.remove();
            }
        }
        purgePoolMap();
    } finally {
        this.lock.unlock();
    }
}
 
Example 20
Project: monarch   File: ClientHealthStats.java   Source Code and License 7 votes vote down vote up
@Override
public String toString() {

  StringBuffer buf = new StringBuffer();
  buf.append("ClientHealthStats [");
  buf.append("\n numOfGets=" + this.numOfGets);
  buf.append("\n numOfPuts=" + this.numOfPuts);
  buf.append("\n numOfMisses=" + this.numOfMisses);
  buf.append("\n numOfCacheListenerCalls=" + this.numOfCacheListenerCalls);
  buf.append("\n numOfThreads=" + this.numOfThreads);
  buf.append("\n cpus=" + this.cpus);
  buf.append("\n processCpuTime=" + this.processCpuTime);
  buf.append("\n updateTime=" + this.updateTime);
  Iterator<Entry<String, String>> it = this.poolStats.entrySet().iterator();
  StringBuffer tempBuffer = new StringBuffer();
  while (it.hasNext()) {
    Entry<String, String> entry = it.next();
    tempBuffer.append(entry.getKey() + " = " + entry.getValue());
  }
  buf.append("\n poolStats " + tempBuffer);
  buf.append("\n]");

  return buf.toString();
}
 
Example 21
Project: sstore-soft   File: TestMultiPartitionTxnFilter.java   Source Code and License 7 votes vote down vote up
/**
 * testMultiPartition
 */
@Test
public void testMultiPartition() throws Exception {
    MultiPartitionTxnFilter filter = new MultiPartitionTxnFilter(p_estimator, false);
    
    Iterator<TransactionTrace> it = workload.iterator(filter);
    assertNotNull(it);

    int count = 0;
    while (it.hasNext()) {
        AbstractTraceElement<? extends CatalogType> element = it.next();
        if (element instanceof TransactionTrace) {
            // Make sure that this txn's base partition is what we expect it to be
            TransactionTrace txn = (TransactionTrace)element;
            partitions.clear();
            p_estimator.getAllPartitions(partitions, txn);
            assertNotNull(partitions);
            assertNotSame(1, partitions.size());
            count++;
        }
    } // WHILE
    assert(count > 0);
}
 
Example 22
Project: incubator-netbeans   File: JDBCDriverConvertor.java   Source Code and License 7 votes vote down vote up
private static JDBCDriver readDriverFromFile(FileObject fo) throws IOException, MalformedURLException {
    Handler handler = new Handler();
    
    // parse the XM file
    try {
        XMLReader reader = XMLUtil.createXMLReader();
        InputSource is = new InputSource(fo.getInputStream());
        is.setSystemId(fo.toURL().toExternalForm());
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.setEntityResolver(EntityCatalog.getDefault());

        reader.parse(is);
    } catch (SAXException ex) {
        throw new IOException(ex.getMessage());
    }
    
    // read the driver from the handler
    URL[] urls = new URL[handler.urls.size()];
    int j = 0;
    for (Iterator i = handler.urls.iterator(); i.hasNext(); j++) {
        urls[j] = new URL((String)i.next());
    }
    if (checkClassPathDrivers(handler.clazz, urls) == false) {
        return null;
    }
    
    if (handler.displayName == null) {
        handler.displayName = handler.name;
    }
    return JDBCDriver.create(handler.name, handler.displayName, handler.clazz, urls);
}
 
Example 23
Project: JRediClients   File: RedissonMapCacheReactiveTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testKeyIterator() {
    RMapReactive<Integer, Integer> map = redisson.getMapCache("simple");
    sync(map.put(1, 0));
    sync(map.put(3, 5));
    sync(map.put(4, 6));
    sync(map.put(7, 8));

    List<Integer> keys = new ArrayList<Integer>(Arrays.asList(1, 3, 4, 7));
    for (Iterator<Integer> iterator = toIterator(map.keyIterator()); iterator.hasNext();) {
        Integer value = iterator.next();
        if (!keys.remove(value)) {
            Assert.fail();
        }
    }

    Assert.assertEquals(0, keys.size());
}
 
Example 24
Project: OpenJSharp   File: CorbaMessageMediatorImpl.java   Source Code and License 7 votes vote down vote up
private byte getStreamFormatVersionForThisRequest(IOR ior,
                                                  GIOPVersion giopVersion)
{

    byte localMaxVersion
        = ORBUtility.getMaxStreamFormatVersion();

    IOR effectiveTargetIOR =
        ((CorbaContactInfo)this.contactInfo).getEffectiveTargetIOR();
    IIOPProfileTemplate temp =
        (IIOPProfileTemplate)effectiveTargetIOR.getProfile().getTaggedProfileTemplate();
    Iterator iter = temp.iteratorById(TAG_RMI_CUSTOM_MAX_STREAM_FORMAT.value);
    if (!iter.hasNext()) {
        // Didn't have the max stream format version tagged
        // component.
        if (giopVersion.lessThan(GIOPVersion.V1_3))
            return ORBConstants.STREAM_FORMAT_VERSION_1;
        else
            return ORBConstants.STREAM_FORMAT_VERSION_2;
    }

    byte remoteMaxVersion
        = ((MaxStreamFormatVersionComponent)iter.next()).getMaxStreamFormatVersion();

    return (byte)Math.min(localMaxVersion, remoteMaxVersion);
}
 
Example 25
Project: SimQRI   File: BatchProcessPropertiesEditionPartImpl.java   Source Code and License 7 votes vote down vote up
/**
 * 
 */
protected void addStorageOutputFlow() {
	TabElementTreeSelectionDialog dialog = new TabElementTreeSelectionDialog(storageOutputFlow.getInput(), storageOutputFlowFilters, storageOutputFlowBusinessFilters,
	"storageOutputFlow", propertiesEditionComponent.getEditingContext().getAdapterFactory(), current.eResource()) {
		@Override
		public void process(IStructuredSelection selection) {
			for (Iterator<?> iter = selection.iterator(); iter.hasNext();) {
				EObject elem = (EObject) iter.next();
				propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(BatchProcessPropertiesEditionPartImpl.this, MetamodelViewsRepository.BatchProcess.Properties.storageOutputFlow,
					PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, elem));
			}
			storageOutputFlow.refresh();
		}
	};
	dialog.open();
}
 
Example 26
Project: lams   File: AuthoringAction.java   Source Code and License 7 votes vote down vote up
/**
    * Updates SessionMap using Scribe content.
    * 
    * @param scribe
    * @param mode
    */
   private SessionMap<String, Object> createSessionMap(Scribe scribe, ToolAccessMode mode, String contentFolderID,
    Long toolContentID) {

SessionMap<String, Object> map = new SessionMap<String, Object>();

map.put(KEY_MODE, mode);
map.put(KEY_CONTENT_FOLDER_ID, contentFolderID);
map.put(KEY_TOOL_CONTENT_ID, toolContentID);
map.put(KEY_HEADINGS, new LinkedList<ScribeHeading>());

// adding headings
Iterator iter = scribe.getScribeHeadings().iterator();
while (iter.hasNext()) {
    ScribeHeading element = (ScribeHeading) iter.next();
    getHeadingList(map).add(element);
}

// sorting headings according to displayOrder.
Collections.sort(getHeadingList(map));

return map;
   }
 
Example 27
Project: lazycat   File: StatusTransformer.java   Source Code and License 7 votes vote down vote up
/**
 * Write JSP monitoring information.
 */
public static void writeJspMonitor(PrintWriter writer, Set<ObjectName> jspMonitorONs, MBeanServer mBeanServer,
		int mode) throws Exception {

	int jspCount = 0;
	int jspReloadCount = 0;

	Iterator<ObjectName> iter = jspMonitorONs.iterator();
	while (iter.hasNext()) {
		ObjectName jspMonitorON = iter.next();
		Object obj = mBeanServer.getAttribute(jspMonitorON, "jspCount");
		jspCount += ((Integer) obj).intValue();
		obj = mBeanServer.getAttribute(jspMonitorON, "jspReloadCount");
		jspReloadCount += ((Integer) obj).intValue();
	}

	if (mode == 0) {
		writer.print("<br>");
		writer.print(" JSPs loaded: ");
		writer.print(jspCount);
		writer.print(" JSPs reloaded: ");
		writer.print(jspReloadCount);
	} else if (mode == 1) {
		// for now we don't write out anything
	}
}
 
Example 28
Project: digital-display-garden-iteration-4-dorfner-v2   File: TestPlantComment.java   Source Code and License 7 votes vote down vote up
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

    Iterator<Document> iter = plants.find(filterDoc).iterator();

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
 
Example 29
Project: scanning   File: SubsetStatus.java   Source Code and License 7 votes vote down vote up
/**
 * Returns true if expected is a subset of returned
 *
 * This is used for JSON serialiser comparisons.
 *
 * @param expected
 * @param returned
 * @return
 */
protected boolean isObjectNodeSubset(ObjectNode expected, ObjectNode returned) {

    Iterator<Entry<String, JsonNode>> expectedChildren = expected.fields();

	for (Map.Entry<String, JsonNode> en; expectedChildren.hasNext();) {
		en = expectedChildren.next();
        String key = en.getKey();
        JsonNode value = en.getValue();

        JsonNode returnedValue = returned.get(key);

        if (returnedValue == null) {
		errorDescription = "Returned JSON does not have key '" + key +"', with expected value:\n" + value.toString();
		return false;
        } else if (!isJsonNodeSubset(value, returnedValue)) {
		return false;
        }
	}
    return true;
}
 
Example 30
Project: unitimes   File: ExamSolver.java   Source Code and License 7 votes vote down vote up
private ExamPlacement getPlacement(Exam exam, ExamPlacement placement) {
    ExamPeriodPlacement period = null;
    for (ExamPeriodPlacement p: exam.getPeriodPlacements()) {
        if (placement.getPeriod().equals(p.getPeriod())) {
            period = p; break;
        }
    }
    if (period==null) {
        iProgress.warn("WARNING: Period "+placement.getPeriod()+" is not available for class "+exam.getName());
        return null;
    }
    Set rooms = new HashSet();
    for (Iterator f=exam.getRoomPlacements().iterator();f.hasNext();) {
        ExamRoomPlacement r = (ExamRoomPlacement)f.next();
        if (r.isAvailable(period.getPeriod()) && placement.contains(r.getRoom())) {
            rooms.add(r);
        }
    }
    if (rooms.size()!=placement.getRoomPlacements().size()) {
        iProgress.warn("WARNING: Room(s) "+placement.getRoomPlacements()+" are not available for exam "+exam.getName());
        return null;
    }
    return new ExamPlacement(exam,period,rooms);
}
 
Example 31
Project: unitimes   File: Solution.java   Source Code and License 7 votes vote down vote up
private void deleteObjects(org.hibernate.Session hibSession, String objectName, String idQuery) {
	Iterator idIterator = hibSession.createQuery(idQuery).setLong("solutionId",getUniqueId()).iterate();
	StringBuffer ids = new StringBuffer();
	int idx = 0;
	while (idIterator.hasNext()) {
		ids.append(idIterator.next()); idx++;
		if (idx==100) {
			hibSession.createQuery("delete "+objectName+" as x where x.uniqueId in ("+ids+")").executeUpdate();
			ids = new StringBuffer();
			idx = 0;
		} else if (idIterator.hasNext()) {
			ids.append(",");
		}
	}
	if (idx>0)
		hibSession.createQuery("delete "+objectName+" as x where x.uniqueId in ("+ids+")").executeUpdate();
}
 
Example 32
Project: Reer   File: Dom4JUtility.java   Source Code and License 6 votes vote down vote up
/**
 * Thie returns the node that is a child of hte specified parent that has the specified attribute with the specified value. This is similar to the above getChild, but no tag name is required.
 */
public static List<Element> getChildren(Element parent, String attribute, String attributeValue) {
    List<Element> children = new ArrayList<Element>();

    Iterator iterator = parent.elements().iterator();
    while (iterator.hasNext()) {
        Element childElement = (Element) iterator.next();
        String actualValue = childElement.attributeValue(attribute);
        if (attributeValue.equals(actualValue)) {
            children.add(childElement);
        }
    }

    return children;
}
 
Example 33
Project: lams   File: AbstractTransactSQLDialect.java   Source Code and License 6 votes vote down vote up
@Override
public String applyLocksToSql(String sql, LockOptions aliasedLockOptions, Map<String, String[]> keyColumnNames) {
	// TODO:  merge additional lockoptions support in Dialect.applyLocksToSql
	final Iterator itr = aliasedLockOptions.getAliasLockIterator();
	final StringBuilder buffer = new StringBuilder( sql );
	int correction = 0;
	while ( itr.hasNext() ) {
		final Map.Entry entry = (Map.Entry) itr.next();
		final LockMode lockMode = (LockMode) entry.getValue();
		if ( lockMode.greaterThan( LockMode.READ ) ) {
			final String alias = (String) entry.getKey();
			int start = -1;
			int end = -1;
			if ( sql.endsWith( " " + alias ) ) {
				start = ( sql.length() - alias.length() ) + correction;
				end = start + alias.length();
			}
			else {
				int position = sql.indexOf( " " + alias + " " );
				if ( position <= -1 ) {
					position = sql.indexOf( " " + alias + "," );
				}
				if ( position > -1 ) {
					start = position + correction + 1;
					end = start + alias.length();
				}
			}

			if ( start > -1 ) {
				final String lockHint = appendLockHint( lockMode, alias );
				buffer.replace( start, end, lockHint );
				correction += ( lockHint.length() - alias.length() );
			}
		}
	}
	return buffer.toString();
}
 
Example 34
Project: smile_1.5.0_java7   File: Math.java   Source Code and License 6 votes vote down vote up
/**
 * Find unique elements of vector.
 * @param x an array of strings.
 * @return the same values as in x but with no repetitions.
 */
public static String[] unique(String[] x) {
    HashSet<String> hash = new HashSet<>(Arrays.asList(x));

    String[] y = new String[hash.size()];

    Iterator<String> keys = hash.iterator();
    for (int i = 0; i < y.length; i++) {
        y[i] = keys.next();
    }

    return y;
}
 
Example 35
Project: CPG   File: JSONObject.java   Source Code and License 6 votes vote down vote up
/**
 * Produce a JSONArray containing the names of the elements of this
 * JSONObject.
 *
 * @return A JSONArray containing the key strings, or null if the JSONObject
 *         is empty.
 */
public JSONArray names() {
    JSONArray ja = new JSONArray();
    Iterator<String> keys = this.keys();
    while (keys.hasNext()) {
        ja.put(keys.next());
    }
    return ja.length() == 0 ? null : ja;
}
 
Example 36
Project: hanlpStudy   File: PinyinKey.java   Source Code and License 6 votes vote down vote up
public PinyinKey(String sentence)
{
    Pair<List<Pinyin>, List<Boolean>> pair = String2PinyinConverter.convert2Pair(sentence, true);
    pinyinArray = PinyinUtil.convertList2Array(pair.getKey());
    List<Boolean> booleanList = pair.getValue();
    int pinyinSize = 0;
    for (Boolean yes : booleanList)
    {
        if (yes)
        {
            ++pinyinSize;
        }
    }
    int firstCharSize = 0;
    for (Pinyin pinyin : pinyinArray)
    {
        if (pinyin != Pinyin.none5)
        {
            ++firstCharSize;
        }
    }

    pyOrdinalArray = new int[pinyinSize];
    firstCharArray = new char[firstCharSize];
    pinyinSize = 0;
    firstCharSize = 0;
    Iterator<Boolean> iterator = booleanList.iterator();
    for (int i = 0; i < pinyinArray.length; ++i)
    {
        if (iterator.next())
        {
            pyOrdinalArray[pinyinSize++] = pinyinArray[i].ordinal();
        }
        if (pinyinArray[i] != Pinyin.none5)
        {
            firstCharArray[firstCharSize++] = pinyinArray[i].getFirstChar();
        }
    }
}
 
Example 37
Project: javaide   File: FilteredMemberList.java   Source Code and License 6 votes vote down vote up
public Iterator<Symbol> iterator() {
    return new Iterator<Symbol>() {

        /** The next entry to examine, or null if none. */
        private Scope.Entry nextEntry = scope.elems;

        private boolean hasNextForSure = false;

        public boolean hasNext() {
            if (hasNextForSure) {
                return true;
            }
            while (nextEntry != null && unwanted(nextEntry.sym)) {
                nextEntry = nextEntry.sibling;
            }
            hasNextForSure = (nextEntry != null);
            return hasNextForSure;
        }

        public Symbol next() {
            if (hasNext()) {
                Symbol result = nextEntry.sym;
                nextEntry = nextEntry.sibling;
                hasNextForSure = false;
                return result;
            } else {
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example 38
Project: kourami   File: HLAGraph.java   Source Code and License 6 votes vote down vote up
public void updateEdgeWeightProb(){
Set<CustomWeightedEdge> eSet = g.edgeSet();
Iterator<CustomWeightedEdge> itr = eSet.iterator();
CustomWeightedEdge e = null;
while(itr.hasNext()){
    e = itr.next();
    e.computeGroupErrorProb();
    //HLA.log.appendln(e.toString());
}
   }
 
Example 39
Project: RRFramework-Android   File: HashBiMap.java   Source Code and License 6 votes vote down vote up
public K getKey(Object value) {
    Iterator iter = entrySet().iterator();
    while (iter.hasNext()) {
        Entry entry = (Entry) iter.next();
        Object val = entry.getValue();
        if (val.equals(value)) {
            return (K) entry.getKey();
        }
    }
    return null;
}
 
Example 40
Project: Tangram-Android   File: MVResolver.java   Source Code and License 6 votes vote down vote up
private void parseBizParams(BaseCell cell, JSONObject json) {
    if (json == null) {
        return;
    }

    Iterator<String> iterator = json.keys();
    while (iterator.hasNext()) {
        String key = iterator.next();
        cell.addBizParam(key, json.opt(key));
    }
}
 
Example 41
Project: lams   File: PersistentClass.java   Source Code and License 5 votes vote down vote up
public Iterator getDeclaredPropertyIterator() {
	ArrayList iterators = new ArrayList();
	iterators.add( declaredProperties.iterator() );
	for ( int i = 0; i < joins.size(); i++ ) {
		Join join = ( Join ) joins.get( i );
		iterators.add( join.getDeclaredPropertyIterator() );
	}
	return new JoinedIterator( iterators );
}
 
Example 42
Project: SparkSeq   File: QualQuantizer.java   Source Code and License 5 votes vote down vote up
/**
 * Helper function that finds and merges together the lowest penalty pair of intervals
 * @param intervals
 */
private void mergeLowestPenaltyIntervals(final TreeSet<QualInterval> intervals) {
    // setup the iterators
    final Iterator<QualInterval> it1 = intervals.iterator();
    final Iterator<QualInterval> it1p = intervals.iterator();
    it1p.next(); // skip one

    // walk over the pairs of left and right, keeping track of the pair with the lowest merge penalty
    QualInterval minMerge = null;
    if ( logger.isDebugEnabled() ) logger.debug("mergeLowestPenaltyIntervals: " + intervals.size());
    int lastMergeOrder = 0;
    while ( it1p.hasNext() ) {
        final QualInterval left = it1.next();
        final QualInterval right = it1p.next();
        final QualInterval merged = left.merge(right);
        lastMergeOrder = Math.max(Math.max(lastMergeOrder, left.mergeOrder), right.mergeOrder);
        if ( minMerge == null || (merged.getPenalty() < minMerge.getPenalty() ) ) {
            if ( logger.isDebugEnabled() ) logger.debug("  Updating merge " + minMerge);
            minMerge = merged;
        }
    }

    // now actually go ahead and merge the minMerge pair
    if ( logger.isDebugEnabled() ) logger.debug("  => final min merge " + minMerge);
    intervals.removeAll(minMerge.subIntervals);
    intervals.add(minMerge);
    minMerge.mergeOrder = lastMergeOrder + 1;
    if ( logger.isDebugEnabled() ) logger.debug("updated intervals: " + intervals);
}
 
Example 43
Project: openjdk-jdk10   File: DQTMarkerSegment.java   Source Code and License 5 votes vote down vote up
protected Object clone() {
    DQTMarkerSegment newGuy = (DQTMarkerSegment) super.clone();
    newGuy.tables = new ArrayList<>(tables.size());
    Iterator<Qtable> iter = tables.iterator();
    while (iter.hasNext()) {
        Qtable table = iter.next();
        newGuy.tables.add((Qtable) table.clone());
    }
    return newGuy;
}
 
Example 44
Project: incubator-netbeans   File: DummyWindowManager.java   Source Code and License 5 votes vote down vote up
public void close(TopComponent tc) {
    java.util.Iterator it = modes.values().iterator();

    while (it.hasNext()) {
        M m = (M) it.next();
        m.close(tc);
    }
}
 
Example 45
Project: alvisnlp   File: FunctionLibrary.java   Source Code and License 5 votes vote down vote up
public static <L extends FunctionLibrary> L load(Class<L> klass) throws ResolverException {
//		ServiceLoader<L> serviceLoader = ServiceLoader.load(klass);
		ServiceLoader<L> serviceLoader = ServiceLoader.load(klass, FunctionLibrary.class.getClassLoader());
		Iterator<L> iterator = serviceLoader.iterator();
		if (iterator.hasNext())
			return iterator.next();
		throw new ResolverException("could not find library");
	}
 
Example 46
Project: Logisim   File: TableSorter.java   Source Code and License 5 votes vote down vote up
@Override
public int compareTo(Row o) {
	int row1 = modelIndex;
	int row2 = o.modelIndex;

	for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) {
		Directive directive = it.next();
		int column = directive.column;

		Object o1 = tableModel.getValueAt(row1, column);
		Object o2 = tableModel.getValueAt(row2, column);

		int comparison = 0;
		// Define null less than everything, except null.
		if (o1 == null && o2 == null) {
			comparison = 0;
		} else if (o1 == null) {
			comparison = -1;
		} else if (o2 == null) {
			comparison = 1;
		} else {
			comparison = getComparator(column).compare(o1, o2);
		}
		if (comparison != 0) {
			return directive.direction == DESCENDING ? -comparison : comparison;
		}
	}
	return 0;
}
 
Example 47
Project: tuxguitar   File: GTPOutputStream.java   Source Code and License 5 votes vote down vote up
protected boolean isPercussionChannel( TGSong song, int channelId ){
	Iterator<TGChannel> it = song.getChannels();
	while( it.hasNext() ){
		TGChannel channel = (TGChannel)it.next();
		if( channel.getChannelId() == channelId ){
			return channel.isPercussionChannel();
		}
	}
	return false;
}
 
Example 48
Project: alvisnlp   File: StringLibrary.java   Source Code and License 5 votes vote down vote up
@Function
public static final String join(EvaluationContext ctx, @SuppressWarnings("unused") Element elt, Iterator<Element> items, Evaluator string, String separator) {
	StringCat strcat = new StringCat();
	boolean notFirst = false;
	while (items.hasNext()) {
		Element e = items.next();
		if (notFirst)
			strcat.append(separator);
		else
			notFirst = true;
		strcat.append(string.evaluateString(ctx, e));
	}
	return strcat.toString();
}
 
Example 49
Project: dxram   File: SuperpeerStorage.java   Source Code and License 5 votes vote down vote up
@Override
public byte[] receiveMetadataInRange(final short p_bound1, final short p_bound2) {
    int size;
    int currentSize = 0;
    int id;
    byte[] currentData;
    ByteBuffer data;
    Iterator<Entry<Integer, byte[]>> iter;

    size = m_allocatedSizeBytes + m_entryCount * (Integer.BYTES + Integer.BYTES);
    data = ByteBuffer.allocate(size);

    iter = m_storage.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<Integer, byte[]> pair = iter.next();
        id = pair.getKey();
        currentData = pair.getValue();

        if (OverlayHelper.isHashInSuperpeerRange(CRC16.hash(id), p_bound1, p_bound2)) {
            // #if LOGGER == TRACE
            LOGGER.trace("Including superpeer storage: %d <-> %d", id, currentData.length);
            // #endif /* LOGGER == TRACE */

            data.putInt(id);
            data.putInt(currentData.length);
            data.put(currentData);
            currentSize += 2 * Integer.BYTES + currentData.length;
        }
    }

    return Arrays.copyOfRange(data.array(), 0, currentSize);
}
 
Example 50
Project: Tarski   File: mxSelectionCellsHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 
 */
public void mouseMoved(MouseEvent e) {
  if (graphComponent.isEnabled() && isEnabled()) {
    Iterator<mxCellHandler> it = handlers.values().iterator();

    while (it.hasNext() && !e.isConsumed()) {
      it.next().mouseMoved(e);
    }
  }
}
 
Example 51
Project: unitimes   File: ExamSuggestions.java   Source Code and License 5 votes vote down vote up
private void tryPlacement(ExamPlacement placement, int depth) {
    if (placement.equals(iAssignment.getValue(placement.variable()))) return;
    if (placement.variable().equals(iExam) && !match(placement.getPeriod().toString()+" "+placement.getRoomName(", "))) return;
    Set conflicts = iModel.conflictValues(iAssignment, placement);
    tryPlacement(placement, depth, conflicts);
    if (iConflictsToResolve.size()+conflicts.size()<depth) {
        Exam exam = (Exam)placement.variable();
        HashSet adepts = new HashSet();
        for (ExamStudent s: exam.getStudents()) {
            Set exams = s.getExams(iAssignment, placement.getPeriod());
            for (Iterator i=exams.iterator();i.hasNext();) {
                ExamPlacement conf = iAssignment.getValue((Exam)i.next());
                if (conf==null || conflicts.contains(conf)) continue;
                if (iResolvedExams.contains((Exam)conf.variable())) continue;
                adepts.add(conf);
            }
        }
        for (Iterator i=adepts.iterator();i.hasNext();) {
            ExamPlacement adept = (ExamPlacement)i.next();
            conflicts.add(adept);
            tryPlacement(placement, depth, conflicts);
            conflicts.remove(adept);
        }
        if (iConflictsToResolve.size()+conflicts.size()+1<depth) {
            for (Iterator i1=adepts.iterator();i1.hasNext();) {
                ExamPlacement a1 = (ExamPlacement)i1.next();
                conflicts.add(a1);
                for (Iterator i2=adepts.iterator();i2.hasNext();) {
                    ExamPlacement a2 = (ExamPlacement)i2.next();
                    if (a2.variable().getId()>=a1.variable().getId()) continue;
                    conflicts.add(a2);
                    tryPlacement(placement, depth, conflicts);
                    conflicts.remove(a2);
                }
                conflicts.remove(a1);
            }
        }
    }
}
 
Example 52
Project: incubator-netbeans   File: ActionFilterNode.java   Source Code and License 5 votes vote down vote up
@Override
public Project remove() {
    if (!removeFromProject) {
        return null;
    }
    // The caller has write access to ProjectManager
    // and ensures the project will be saved.
     boolean found = false;
     final List<ClassPathSupport.Item> resources = getClassPathItems();
     for (Iterator i = resources.iterator(); i.hasNext();) {
         ClassPathSupport.Item item = (ClassPathSupport.Item)i.next();
         if (entryId.equals(CommonProjectUtils.getAntPropertyName(item.getReference()))) {
             lastRef.set(item.getReference());
             i.remove();
             ClassPathPackageAccessor.getInstance().removeUnusedReference(item, classPathId, helper, rh);
             found = true;
         }
     }
     if (found) {
         String[] itemRefs = cs.encodeToStrings(resources, webModuleElementName);
         final EditableProperties props = helper.getProperties (AntProjectHelper.PROJECT_PROPERTIES_PATH);    //Reread the properties, PathParser changes them
         props.setProperty (classPathId, itemRefs);
         helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
        return FileOwnerQuery.getOwner(helper.getAntProjectHelper().getProjectDirectory());
    } else {
        return null;
    }
}
 
Example 53
Project: parabuild-ci   File: SessionImpl.java   Source Code and License 5 votes vote down vote up
public void afterTransactionCompletion(boolean success) {

		log.trace("transaction completion");

		isCurrentTransaction = false;

		// Downgrade locks
		Iterator iter = entityEntries.values().iterator();
		while ( iter.hasNext() ) {
			( (EntityEntry) iter.next() ).lockMode = LockMode.NONE;
		}

		// Release cache softlocks
		int size = executions.size();
		final boolean invalidateQueryCache = factory.isQueryCacheEnabled();
		for ( int i=0; i<size; i++ ) {
			try {
				Executable exec = (Executable) executions.get(i);
				try {
					exec.afterTransactionCompletion(success);
				}
				finally {
					if (invalidateQueryCache) factory.getUpdateTimestampsCache().invalidate( exec.getPropertySpaces() );
				}
			}
			catch (CacheException ce) {
				log.error("could not release a cache lock", ce);
				// continue loop
			}
			catch (Exception e) {
				throw new AssertionFailure("Exception releasing cache locks", e);
			}
		}
		executions.clear();

	}
 
Example 54
Project: OpenJSharp   File: Axis.java   Source Code and License 5 votes vote down vote up
private Iterator<XSAttributeDecl> attributeHolder(final XSAttContainer atts) {
    // TODO: check spec. is this correct?
    return new Iterators.Adapter<XSAttributeDecl,XSAttributeUse>(atts.iterateAttributeUses()) {
        protected XSAttributeDecl filter(XSAttributeUse u) {
            return u.getDecl();
        }
    };
}
 
Example 55
Project: fresco_floodlight   File: ForwardingBase.java   Source Code and License 5 votes vote down vote up
/**
 * Write packetout message to sw with output actions to one or more
 * output ports with inPort/outPorts passed in.
 * @param packetData
 * @param sw
 * @param inPort
 * @param ports
 * @param cntx
 */
public void packetOutMultiPort(byte[] packetData, IOFSwitch sw, 
		OFPort inPort, Set<OFPort> outPorts, FloodlightContext cntx) {
	//setting actions
	List<OFAction> actions = new ArrayList<OFAction>();

	Iterator<OFPort> j = outPorts.iterator();

	while (j.hasNext()) {
		actions.add(sw.getOFFactory().actions().output(j.next(), 0));
	}

	OFPacketOut.Builder pob = sw.getOFFactory().buildPacketOut();
	pob.setActions(actions);

	pob.setBufferId(OFBufferId.NO_BUFFER);
	pob.setInPort(inPort);

	pob.setData(packetData);

	try {
		if (log.isTraceEnabled()) {
			log.trace("write broadcast packet on switch-id={} " +
					"interfaces={} packet-out={}",
					new Object[] {sw.getId(), outPorts, pob.build()});
		}
		messageDamper.write(sw, pob.build());

	} catch (IOException e) {
		log.error("Failure writing packet out", e);
	}
}
 
Example 56
Project: DStream   File: PredictorHotKeyUtil.java   Source Code and License 5 votes vote down vote up
/**
 * New Words in Hot Words Random Dump
 */
public void SynopsisHashMapRandomDump(DumpRemoveHandler dumpRemoveHandler) {
    int size=predictHotKeyMap.size;
    long startTimeSystemTime=System.currentTimeMillis();
    Iterator<Map.Entry<String, BitSet>> iterator = predictHotKeyMap.newEntryIterator();
    while (iterator.hasNext()){
        Map.Entry<String, BitSet> next = iterator.next();
        if (random.nextDouble()> Threshold_p){
            continue;
        }
        BitSet bitm = next.getValue();
        String key = next.getKey();
        if(key!=null){
            long[] lo = bitm.toLongArray();
            if(lo.length > 0){
                for(int j=0;j<lo.length - 1;j++){
                    lo[j] = lo[j] >>> 1;
                    lo[j] = lo[j] | (lo[j+1] << 63);
                }
                lo[lo.length-1] = lo[lo.length-1] >>> 1;
            }
            bitm = BitSet.valueOf(lo);
            if (bitm.isEmpty()) {
                iterator.remove();
                dumpRemoveHandler.dumpRemove(key);
            }else
                next.setValue(bitm);
        }
    }
}
 
Example 57
Project: jerrydog   File: MemoryUser.java   Source Code and License 5 votes vote down vote up
/**
 * Return the set of {@link Role}s assigned specifically to this user.
 */
public Iterator getRoles() {

    synchronized (roles) {
        return (roles.iterator());
    }

}
 
Example 58
Project: org.mybatis.generator.core-1.3.5   File: BlobColumnListElementGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public void addElements(XmlElement parentElement) {
    XmlElement answer = new XmlElement("sql"); //$NON-NLS-1$

    answer.addAttribute(new Attribute("id", //$NON-NLS-1$
            introspectedTable.getBlobColumnListId()));

    context.getCommentGenerator().addComment(answer);

    StringBuilder sb = new StringBuilder();

    Iterator<IntrospectedColumn> iter = introspectedTable.getBLOBColumns()
            .iterator();
    while (iter.hasNext()) {
        sb.append(MyBatis3FormattingUtilities.getSelectListPhrase(iter
                .next()));

        if (iter.hasNext()) {
            sb.append(", "); //$NON-NLS-1$
        }

        if (sb.length() > 80) {
            answer.addElement(new TextElement(sb.toString()));
            sb.setLength(0);
        }
    }

    if (sb.length() > 0) {
        answer.addElement(new TextElement(sb.toString()));
    }

    if (context.getPlugins().sqlMapBlobColumnListElementGenerated(
            answer, introspectedTable)) {
        parentElement.addElement(answer);
    }
}
 
Example 59
Project: VASSAL-src   File: Restricted.java   Source Code and License 5 votes vote down vote up
public Object visitStack(Stack s) {
  Command c = new NullCommand();
  for (Iterator<GamePiece> it = s.getPiecesIterator(); it.hasNext();) {
    c = c.append((Command)visitDefault(it.next()));
  }
  return c;
}
 
Example 60
Project: uniquecrops   File: EntityItemHourglass.java   Source Code and License 5 votes vote down vote up
@Override
public void onUpdate() {
	
	super.onUpdate();
	if (this.worldObj != null && this.ticksExisted % 300 == 0) {
		Iterable<BlockPos> poslist = BlockPos.getAllInBox(getPosition().add(-range, -range, -range), getPosition().add(range, range, range));
		Iterator it = poslist.iterator();
		while (it.hasNext()) {
			BlockPos posit = (BlockPos)it.next();
			if (!worldObj.isRemote && !worldObj.isAirBlock(posit)) {
				Block loopblock = worldObj.getBlockState(posit).getBlock();
				boolean flag = rand.nextInt(10) == 0;
				if (loopblock == Blocks.GRASS && flag) {
					setOldBlock(worldObj, posit, UCBlocks.oldGrass); break;
				}
				if (loopblock == Blocks.COBBLESTONE && flag) {
					setOldBlock(worldObj, posit, UCBlocks.oldCobble); break;
				}
				if (loopblock == Blocks.MOSSY_COBBLESTONE && flag) {
					setOldBlock(worldObj, posit, UCBlocks.oldCobbleMoss); break;
				}
				if (loopblock == Blocks.BRICK_BLOCK && flag) {
					setOldBlock(worldObj, posit, UCBlocks.oldBrick); break;
				}
				if (loopblock == Blocks.GRAVEL && flag) {
					setOldBlock(worldObj, posit, UCBlocks.oldGravel); break;
				}
			}
		}
	}
}