Java Examples for java.util.Iterator

The following java examples will help you to understand the usage of java.util.Iterator. These source code samples are taken from different open source projects.

Example 1
Project: sosies-generator-master  File: ObjectGraphIteratorTest.java View source code
@Test(timeout = 1000)
public void testIteratorConstructor_null1() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testIteratorConstructor_null1");
    final Iterator<java.lang.Object> it = new ObjectGraphIterator<java.lang.Object>(null);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 4120, it, 4119, it.hasNext());
    try {
        it.next();
        it.next();
    } catch (final NoSuchElementException ex) {
    }
    try {
        it.remove();
    } catch (final IllegalStateException ex) {
    }
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 2
Project: Technomap-master  File: EulerIntegrator.java View source code
/**
     * @see prefuse.util.force.Integrator#integrate(prefuse.util.force.ForceSimulator, long)
     */
public void integrate(ForceSimulator sim, long timestep) {
    float speedLimit = sim.getSpeedLimit();
    Iterator iter = sim.getItems();
    while (iter.hasNext()) {
        ForceItem item = (ForceItem) iter.next();
        item.location[0] += timestep * item.velocity[0];
        item.location[1] += timestep * item.velocity[1];
        float coeff = timestep / item.mass;
        item.velocity[0] += coeff * item.force[0];
        item.velocity[1] += coeff * item.force[1];
        float vx = item.velocity[0];
        float vy = item.velocity[1];
        float v = (float) Math.sqrt(vx * vx + vy * vy);
        if (v > speedLimit) {
            item.velocity[0] = speedLimit * vx / v;
            item.velocity[1] = speedLimit * vy / v;
        }
    }
}
Example 3
Project: codemap-master  File: Interval.java View source code
[email protected]
public final Iterator<Integer> iterator() {
    return new Iterator<Integer>() {

        private int index = start;

        public final boolean hasNext() {
            return step > 0 ? index < end : index > end;
        }

        public final Integer next() {
            if (!hasNext())
                throw new NoSuchElementException();
            int current = index;
            index += step;
            return current;
        }

        public final void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
Example 4
Project: xapi-master  File: TestCodegen.java View source code
@Test
public void testGenericImports() {
    final SourceBuilder<Object> b = new SourceBuilder<Object>("public static abstract class Test");
    b.setPackage("xapi.test");
    b.getClassBuffer().addGenerics("K", "V extends java.util.Date, ? extends java.lang.String, ? super xapi.test.Thing").addInterfaces("java.util.Iterator");
    String src = b.toSource();
    Assert.assertTrue("Must contain import java.util.Date;\n" + src, src.contains("import java.util.Date;"));
    Assert.assertTrue("Must contain import java.util.Iterator;\n" + src, b.toString().contains("import java.util.Iterator;"));
}
Example 5
Project: sqlpower-library-master  File: RmiTest.java View source code
public static void main(String[] args) {
    Collection message = null;
    DBConnectionSpecServer obj = null;
    try {
        obj = (DBConnectionSpecServer) Naming.lookup("//arthur/DBConnectionSpecServer");
        message = obj.getAvailableDatabases();
        Iterator messageIt = message.iterator();
        while (messageIt.hasNext()) {
            System.out.println(messageIt.next());
        }
        System.out.println("passcheck: " + obj.checkPassword("mo"));
        obj.setAvailableDatabases(message, "cow", "cow");
    } catch (Exception e) {
        System.out.println("exception: " + e.getMessage());
        e.printStackTrace();
    }
}
Example 6
Project: extension-aws-master  File: BshScriptRunner.java View source code
@Override
public Object exec(Script inScript, Map variableMap) throws OpenEditException {
    String path = inScript.getPage().getPath();
    try {
        Interpreter i = new Interpreter();
        for (Iterator iterator = variableMap.keySet().iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            i.set(key, variableMap.get(key));
        }
        Object obj = i.source(inScript.getPage().getContentItem().getAbsolutePath());
        return obj;
    } catch (TargetError e) {
        throw new OpenEditException("line: " + e.getErrorLineNumber() + " " + path + " " + e.getTarget(), e.getTarget(), path);
    } catch (EvalError e2) {
        throw new OpenEditException(e2.getMessage(), e2, path);
    } catch (OpenEditException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new OpenEditException(ex);
    }
}
Example 7
Project: Klyph-master  File: TagSerializer.java View source code
public void serializeMap(Map<String, List<Tag>> tags, JSONObject json, String field) {
    JSONObject tagObject = new JSONObject();
    for (Iterator<String> iterator = tags.keySet().iterator(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        List<Tag> tag = tags.get(key);
        try {
            tagObject.put(key, super.serializeArray(tag));
        } catch (JSONException e) {
            Log.d("TagSerializer", "JsonException " + e.getMessage());
        }
    }
    try {
        json.put(field, tagObject);
    } catch (JSONException e) {
        Log.d("TagSerializer", "JsonException " + e.getMessage());
    }
}
Example 8
Project: spring-framework-2.5.x-master  File: UpdateCartQuantitiesController.java View source code
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class);
    Iterator cartItems = cart.getAllCartItems();
    while (cartItems.hasNext()) {
        CartItem cartItem = (CartItem) cartItems.next();
        String itemId = cartItem.getItem().getItemId();
        try {
            int quantity = Integer.parseInt(request.getParameter(itemId));
            cart.setQuantityByItemId(itemId, quantity);
            if (quantity < 1) {
                cartItems.remove();
            }
        } catch (NumberFormatException ex) {
        }
    }
    request.getSession().setAttribute("sessionCart", cart);
    return new ModelAndView("Cart", "cart", cart);
}
Example 9
Project: O2OMobile_Android-master  File: Transmitter.java View source code
public static void transmit(Command c, Map h, String b, java.io.OutputStream out) throws IOException {
    StringBuffer message = new StringBuffer(c.toString());
    message.append("\n");
    if (h != null) {
        for (Iterator keys = h.keySet().iterator(); keys.hasNext(); ) {
            String key = (String) keys.next();
            String value = (String) h.get(key);
            message.append(key);
            message.append(":");
            message.append(value);
            message.append("\n");
        }
    }
    message.append("\n");
    if (b != null)
        message.append(b);
    message.append("\000");
    out.write(message.toString().getBytes(Command.ENCODING));
}
Example 10
Project: openjdk-master  File: XMLEventFactoryImpl.java View source code
public javax.xml.stream.events.EndElement createEndElement(String prefix, String namespaceUri, String localName, java.util.Iterator namespaces) {
    EndElementEvent event = new EndElementEvent(prefix, namespaceUri, localName);
    if (namespaces != null) {
        while (namespaces.hasNext()) event.addNamespace((Namespace) namespaces.next());
    }
    if (location != null)
        event.setLocation(location);
    return event;
}
Example 11
Project: jade_agents-master  File: HashSet.java View source code
public Iterator iterator() {
    return new Iterator() {

        java.util.Iterator it = internalHashSet.iterator();

        /**
			 * @see jade.util.leap.Iterator interface
			 */
        public boolean hasNext() {
            return it.hasNext();
        }

        /**
			 * @see jade.util.leap.Iterator interface
			 */
        public Object next() {
            return it.next();
        }

        /**
			 * @see jade.util.leap.Iterator interface
			 */
        public void remove() {
            it.remove();
        }
    };
}
Example 12
Project: extFM-Tooling-master  File: MtextInterruptibleEcoreResolver.java View source code
/**
	 * Searches for all unresolved proxy objects in the given resource.
	 * 
	 * @param resource
	 * 
	 * @return all proxy objects that are not resolvable
	 */
public java.util.Set<org.eclipse.emf.ecore.EObject> findUnresolvedProxies(org.eclipse.emf.ecore.resource.Resource resource) {
    java.util.Set<org.eclipse.emf.ecore.EObject> unresolvedProxies = new java.util.LinkedHashSet<org.eclipse.emf.ecore.EObject>();
    for (java.util.Iterator<org.eclipse.emf.ecore.EObject> elementIt = org.eclipse.emf.ecore.util.EcoreUtil.getAllContents(resource, true); elementIt.hasNext(); ) {
        org.eclipse.emf.ecore.InternalEObject nextElement = (org.eclipse.emf.ecore.InternalEObject) elementIt.next();
        if (terminate) {
            return unresolvedProxies;
        }
        if (nextElement.eIsProxy()) {
            unresolvedProxies.add(nextElement);
        }
        for (org.eclipse.emf.ecore.EObject crElement : nextElement.eCrossReferences()) {
            if (terminate) {
                return unresolvedProxies;
            }
            crElement = org.eclipse.emf.ecore.util.EcoreUtil.resolve(crElement, resource);
            if (crElement.eIsProxy()) {
                unresolvedProxies.add(crElement);
            }
        }
    }
    return unresolvedProxies;
}
Example 13
Project: openmap-master  File: SoloMapComponentReplacePolicy.java View source code
/**
     * @return true if the object can be added to the MapHandler, and
     *         will have removed the previous duplicate from the
     *         MapHandler.
     */
public boolean canAdd(BeanContextSupport bc, Object obj) throws MultipleSoloMapComponentException {
    if (obj == null) {
        return false;
    }
    // the previous one, too.
    if (obj instanceof SoloMapComponent) {
        Class firstClass = obj.getClass();
        for (Iterator it = bc.iterator(); it.hasNext(); ) {
            Object someObj = it.next();
            if (someObj instanceof SoloMapComponent) {
                Class secondClass = someObj.getClass();
                if (firstClass == secondClass || firstClass.isAssignableFrom(secondClass) || secondClass.isAssignableFrom(firstClass)) {
                    bc.remove(someObj);
                    break;
                }
            }
        }
    }
    return true;
}
Example 14
Project: OrganicBuilder-master  File: InsertAtomValidator.java View source code
@Override
public String evaluate(final Collection<? extends Atom> atoms, final LevelMessages messages) {
    final LinkedList<Atom> joined = new LinkedList<Atom>();
    chainStart.getAllConnectedAtoms(joined);
    if (joined.size() != 11) {
        return messages.getError(1);
    }
    final int n_bonds[] = { 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 };
    final AtomType types[] = { BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.B, BasicType.E, BasicType.E, BasicType.E, BasicType.E, BasicType.E };
    int i = 0;
    final Iterator<Atom> it = joined.iterator();
    while (it.hasNext()) {
        final Atom a = it.next();
        if (a.getBonds().size() != n_bonds[i]) {
            return messages.getError(2);
        }
        if (a.getType() != types[i]) {
            return messages.getError(3);
        }
        i++;
    }
    return null;
}
Example 15
Project: GeoGig-master  File: StagingDbCompositionHelper.java View source code
public static Iterator<RevObject> getAll(final ObjectDatabase objectDb, final ObjectDatabase stagingDb, final Iterable<ObjectId> ids, final BulkOpListener listener) {
    final List<ObjectId> missingInStaging = Lists.newLinkedList();
    final int limit = 10000;
    final BulkOpListener stagingListener = new BulkOpListener.ForwardingListener(listener) {

        @Override
        public void notFound(ObjectId id) {
            missingInStaging.add(id);
        }
    };
    final Iterator<RevObject> foundInStaging = stagingDb.getAll(ids, stagingListener);
    Iterator<RevObject> compositeIterator = new AbstractIterator<RevObject>() {

        Iterator<RevObject> forwardedToObjectDb = Iterators.emptyIterator();

        @Override
        protected RevObject computeNext() {
            if (forwardedToObjectDb.hasNext()) {
                return forwardedToObjectDb.next();
            }
            if (missingInStaging.size() >= limit) {
                List<ObjectId> missing = new ArrayList<ObjectId>(missingInStaging);
                missingInStaging.clear();
                forwardedToObjectDb = objectDb.getAll(missing, listener);
                return computeNext();
            }
            if (foundInStaging.hasNext()) {
                return foundInStaging.next();
            } else if (forwardedToObjectDb.hasNext()) {
                return forwardedToObjectDb.next();
            } else if (!missingInStaging.isEmpty()) {
                List<ObjectId> missing = new ArrayList<ObjectId>(missingInStaging);
                missingInStaging.clear();
                forwardedToObjectDb = objectDb.getAll(missing, listener);
                return computeNext();
            }
            return endOfData();
        }
    };
    return compositeIterator;
}
Example 16
Project: yarep-master  File: VFSRevisionIterator.java View source code
/**
     * @see java.util.Iterator#hasNext()
     */
public boolean hasNext() {
    if (currentRevision == null) {
        // INFO: Iterator is still at the beginning
        if (pointInTime != null) {
            // TODO: What exactly means 'reverse' when using pointInTime?!
            try {
                if (dis.getRevision(pointInTime) != null) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                log.error(e, e);
                return false;
            }
        } else {
            if (reverse) {
                if (dis.getOldestRevision() != null) {
                    return true;
                } else {
                    log.warn("No revisions at all.");
                    return false;
                }
            } else {
                if (dis.getMostRecentRevision() != null) {
                    return true;
                } else {
                    log.warn("No revisions at all.");
                    return false;
                }
            }
        }
    } else {
        try {
            log.debug("Check if there is another revision older than: " + format(currentRevision.getCreationDate()));
            if (reverse) {
                if (dis.getRevisionYoungerThan(currentRevision.getCreationDate()) != null) {
                    return true;
                } else {
                    log.debug("No revision younger than '" + currentRevision.getCreationDate() + "', hence stop iteration.");
                    return false;
                }
            } else {
                if (dis.getRevisionOlderThan(currentRevision.getCreationDate()) != null) {
                    return true;
                } else {
                    log.debug("No revision older than '" + currentRevision.getCreationDate() + "', hence stop iteration.");
                    return false;
                }
            }
        } catch (Exception e) {
            log.error(e, e);
            return false;
        }
    }
}
Example 17
Project: oobd-master  File: JcaCRLStore.java View source code
private static Collection convertCRLs(Collection collection) throws CRLException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object crl = it.next();
        if (crl instanceof X509CRL) {
            try {
                list.add(new X509CRLHolder(((X509CRL) crl).getEncoded()));
            } catch (IOException e) {
                throw new CRLException("cannot read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CRLHolder) crl);
        }
    }
    return list;
}
Example 18
Project: teiid-designer-master  File: CompositorBasedBuilderStrategy.java View source code
@Override
protected boolean shouldContainMappingClass(EObject node) {
    boolean result = false;
    if (mapper.allowsMappingClass(node)) {
        // see if the structure is similar to that of a complex type
        Collection children = tree.getChildren(node);
        for (Iterator iter = children.iterator(); iter.hasNext(); ) {
            EObject child = (EObject) iter.next();
            if (mapper.isContainerNode(child)) {
                result = true;
                break;
            }
        }
        if (!result) {
            // see if the node is directly under a choice
            EObject parent = tree.getParent(node);
            result = tree.isChoiceNode(parent);
        }
    }
    return result;
}
Example 19
Project: SmartAndroidSource-master  File: Verifi.java View source code
public boolean isValid(String value) {
    boolean result = true;
    this._message = new String();
    Iterator<AbstractVerifior> it = this._validators.iterator();
    while (it.hasNext()) {
        AbstractVerifior validator = it.next();
        try {
            if (!validator.isValid(value)) {
                this._message = validator.getMessage();
                result = false;
                break;
            }
        } catch (VerifiorException e) {
            System.err.println(e.getMessage());
            System.err.println(e.getStackTrace());
            this._message = e.getMessage();
            result = false;
            break;
        }
    }
    return result;
}
Example 20
Project: speechalyzer-master  File: JudgeAllThread.java View source code
/**
	 * called by thread.start();
	 */
public void run() {
    _isRunning = true;
    for (Iterator<RecFile> iter = _afm.getAudioFiles().iterator(); iter.hasNext(); ) {
        RecFile recFile = (RecFile) iter.next();
        _extractor.extractFeatures(recFile._file.getAbsolutePath());
        ClassificationResult cr = _classifier.classify();
        //			logger.info("Modus: judge file " + filePath + " emotionally: "
        //					+ cr.toString());
        recFile.storePred(cr);
        _afm.updateAudioFile(recFile._path);
    }
    System.out.println("finished judging all files!");
    _isRunning = false;
}
Example 21
Project: cdo-master  File: SelectionHandler.java View source code
protected List<Object> getSelectedObjects(ExecutionEvent event) {
    List<Object> objects = new ArrayList<Object>();
    ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
    if (selection != null & selection instanceof IStructuredSelection) {
        IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        for (@SuppressWarnings("unchecked") Iterator<Object> iterator = structuredSelection.iterator(); iterator.hasNext(); ) {
            Object element = iterator.next();
            objects.add(element);
        }
    }
    return objects;
}
Example 22
Project: btpka3.github.com-master  File: PinyinAbbrTokenizerTest.java View source code
private void print(TokenStream ts) throws IOException {
    Iterator<Class<? extends Attribute>> it = ts.getAttributeClassesIterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    CharTermAttribute termAtt = ts.getAttribute(CharTermAttribute.class);
    PositionIncrementAttribute posIncrAtt = ts.getAttribute(PositionIncrementAttribute.class);
    PositionLengthAttribute posLenAtt = ts.getAttribute(PositionLengthAttribute.class);
    TypeAttribute typeAtt = ts.getAttribute(TypeAttribute.class);
    OffsetAttribute offsetAtt = ts.getAttribute(OffsetAttribute.class);
    TermToBytesRefAttribute byteRefAtt = ts.getAttribute(TermToBytesRefAttribute.class);
    ts.reset();
    while (ts.incrementToken()) {
        System.out.printf("%3d ~ %3d : %15s : %3d : %3d : '%s' - '%s' : %n", offsetAtt.startOffset(), offsetAtt.endOffset(), typeAtt.type(), posIncrAtt.getPositionIncrement(), posLenAtt.getPositionLength(), new String(byteRefAtt.getBytesRef().bytes), termAtt.toString());
    }
}
Example 23
Project: geotoolkit-master  File: FindProcessDemo.java View source code
public static void main(String[] args) throws NoSuchIdentifierException {
    Demos.init();
    //Get an iterator on all process factory
    final Iterator<ProcessingRegistry> factoryIte = ProcessFinder.getProcessFactories();
    while (factoryIte.hasNext()) {
        //Get a factory
        final ProcessingRegistry registry = factoryIte.next();
        System.out.println("Registry : " + registry.getIdentification().getCitation().getTitle().toString());
        //Get factory process descriptor in order to find the description of all process of this factory.
        final List<ProcessDescriptor> descriptorList = registry.getDescriptors();
        for (ProcessDescriptor descriptor : descriptorList) {
            System.out.println("    Process : " + descriptor.getIdentifier().getCode());
        }
        System.out.println("---------------------------------------------------------------------------");
    }
    ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("demo", "addition");
    System.out.println(desc);
}
Example 24
Project: hibernate-core-ogm-master  File: TestDirtyCheckExecutable.java View source code
public void execute() {
    Session s = getFactory().openSession();
    Transaction t = s.beginTransaction();
    Folder pics = new Folder();
    pics.setName("pics");
    Folder docs = new Folder();
    docs.setName("docs");
    s.persist(docs);
    s.persist(pics);
    t.commit();
    s.close();
    s = getFactory().openSession();
    t = s.beginTransaction();
    List list = s.createCriteria(Folder.class).list();
    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Folder f = (Folder) iter.next();
        Assert.assertFalse(f.nameWasread);
    }
    t.commit();
    s.close();
    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Folder f = (Folder) iter.next();
        Assert.assertFalse(f.nameWasread);
    }
    s = getFactory().openSession();
    t = s.beginTransaction();
    s.createQuery("delete from Folder").executeUpdate();
    t.commit();
    s.close();
}
Example 25
Project: hdt-java-master  File: MergedIteratorTest.java View source code
@Test
public void testOneEmpty() {
    Iterator<Integer> it = new MergedIterator<Integer>(listA.iterator(), listB.iterator(), new Comparator<Integer>() {

        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    });
    Iterator<Integer> itE = listC.iterator();
    while (it.hasNext()) {
        assertEquals(itE.hasNext(), it.hasNext());
        int val = it.next();
        int valE = itE.next();
        //			System.out.println(val);
        assertEquals(val, valE);
    }
    assertEquals(itE.hasNext(), it.hasNext());
}
Example 26
Project: mldht-master  File: XMLUtils.java View source code
public static XPathExpression buildXPath(String path, Map<String, String> map) {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    if (map != null)
        xpath.setNamespaceContext(new NamespaceContext() {

            public Iterator getPrefixes(String namespaceURI) {
                throw new UnsupportedOperationException();
            }

            public String getPrefix(String namespaceURI) {
                throw new UnsupportedOperationException();
            }

            public String getNamespaceURI(String prefix) {
                Objects.requireNonNull(prefix);
                if (map.containsKey(prefix))
                    return map.get(prefix);
                return XMLConstants.NULL_NS_URI;
            }
        });
    try {
        return xpath.compile(path);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}
Example 27
Project: jeboorker-master  File: ImageFetcherTest.java View source code
public void testFetcherBigBooksIterator() {
    try {
        IImageFetcher imageFetcher = ImageWebSearchFetcherFactory.getInstance().getImageFetcher("Big Book Search");
        imageFetcher.setSearchTerm("Der Fänger");
        Iterator<IImageFetcherEntry> searchImages = imageFetcher.getEntriesIterator();
        for (int i = 0; searchImages.hasNext(); i++) {
            IImageFetcherEntry next = searchImages.next();
            System.out.println(next.getImageURL());
            if (i == 25) {
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 28
Project: sphereMiners-master  File: Pacifist.java View source code
@Override
protected void playTurn() {
    // first check if we could split
    List<Sphere> splits = new ArrayList<>();
    for (Sphere s : ownSpheres) {
        if (s.getSize() > getConstants().getMinSplittingsize()) {
            splits.add(s);
        }
    }
    split(splits);
    // then change directions
    Sphere ownSphere = null;
    Iterator<Sphere> ownIt = ownSpheres.iterator();
    Map<Sphere, Position> newDirections = new HashMap<>();
    while (ownIt.hasNext()) {
        ownSphere = ownIt.next();
        Iterator<Sphere> dotsIt = dots.iterator();
        Sphere nextDot = dotsIt.next();
        double minDist = ownSphere.getPosition().dist(nextDot.getPosition());
        while (dotsIt.hasNext()) {
            Sphere tmpSphere = dotsIt.next();
            double tmpDist = ownSphere.getPosition().dist(tmpSphere.getPosition());
            if (tmpDist < minDist) {
                minDist = tmpDist;
                nextDot = tmpSphere;
            }
        }
        final Position moveTo = nextDot.getPosition().sub(ownSphere.getPosition());
        newDirections.put(ownSphere, moveTo);
    }
    changeMoveDirection(newDirections);
}
Example 29
Project: eclipselink.runtime-master  File: DescriptorInitTest.java View source code
public void test() {
    for (java.util.Iterator iterator = project.getDescriptors().values().iterator(); iterator.hasNext(); ) {
        ClassDescriptor descriptor = (ClassDescriptor) iterator.next();
        String className = descriptor.getJavaClass().toString();
        String part1;
        String part2;
        Character ch = new Character(className.charAt(className.length() - 2));
        if (ch.equals(new Character('0'))) {
            //Class100
            part1 = className.substring(6, className.length() - 3);
            part2 = className.substring(className.length() - 3);
        } else if (Character.isDigit(ch.charValue())) {
            //Class##
            part1 = className.substring(6, className.length() - 2);
            part2 = className.substring(className.length() - 2);
        } else {
            //Class#
            part1 = className.substring(6, className.length() - 1);
            part2 = className.substring(className.length() - 1);
        }
        String interfaceName = part1 + "I" + part2;
        try {
            descriptor.getInterfacePolicy().addParentInterface(Class.forName(interfaceName));
        } catch (Throwable e) {
            throw new TestErrorException("Specified class was not found: " + interfaceName);
        }
    }
    dbsession.login();
    dbsession.logout();
}
Example 30
Project: raylew_algorithm-master  File: 统计字符.java View source code
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total = (Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
Example 31
Project: beowulf-master  File: FilteredCollection.java View source code
public Iterator iterator() {
    final Iterator sourceIterator = this.sourceCollection.iterator();
    return new Iterator() {

        private Boolean hasNext;

        private Object next;

        private void scanNext() {
            while (sourceIterator.hasNext()) {
                Object item = filter.decode(sourceIterator.next());
                if (item != null) {
                    hasNext = Boolean.TRUE;
                    this.next = item;
                }
            }
            hasNext = Boolean.FALSE;
        }

        /*
			 * (non-Javadoc)
			 * 
			 * @see java.util.Iterator#hasNext()
			 */
        public boolean hasNext() {
            if (this.hasNext == null) {
                scanNext();
            }
            return this.hasNext.booleanValue();
        }

        /*
			 * (non-Javadoc)
			 * 
			 * @see java.util.Iterator#next()
			 */
        public Object next() {
            if (this.hasNext == null) {
                scanNext();
            }
            if (Boolean.FALSE.equals(this.hasNext)) {
                throw new NoSuchElementException();
            }
            Object next = this.next;
            this.hasNext = null;
            return next;
        }

        /*
			 * (non-Javadoc)
			 * 
			 * @see java.util.Iterator#remove()
			 */
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
Example 32
Project: researchzilla-master  File: PicCrop.java View source code
public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ImageInputStream imageInputStream = null;
    try {
        fileInputStream = new FileInputStream("/home/yumingzhe/a.jpg");
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader imageReader = (ImageReader) iterator.next();
        imageInputStream = ImageIO.createImageInputStream(fileInputStream);
        imageReader.setInput(imageInputStream, true);
        ImageReadParam param = imageReader.getDefaultReadParam();
        Rectangle rect = new Rectangle(0, 0, 100, 100);
        param.setSourceRegion(rect);
        BufferedImage bi = imageReader.read(0, param);
        ImageIO.write(bi, "jpg", new File("/home/yumingzhe/b.jpg"));
        imageInputStream.close();
        fileInputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 33
Project: Restlib-master  File: JSONRestRequest.java View source code
@Override
public boolean setContent(HashMap<String, Object> data) {
    if (this.getMethod() == RestRequest.GET_METHOD)
        buildGetURI(data);
    try {
        JSONStringer holder = new JSONStringer().object();
        Iterator<Entry<String, Object>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> e = it.next();
            holder.key(e.getKey().toString()).value(e.getValue());
        }
        holder.endObject();
        content = holder.toString();
    } catch (Exception e) {
        return false;
    }
    return true;
}
Example 34
Project: ldbc_snb_datagen-master  File: UniformPostGenerator.java View source code
@Override
protected PostInfo generatePostInfo(Random randomTag, Random randomDate, final Forum forum, final ForumMembership membership) {
    PostInfo postInfo = new PostInfo();
    postInfo.tags = new TreeSet<Integer>();
    Iterator<Integer> it = forum.tags().iterator();
    while (it.hasNext()) {
        Integer value = it.next();
        if (postInfo.tags.isEmpty()) {
            postInfo.tags.add(value);
        } else {
            if (randomTag.nextDouble() < 0.05) {
                postInfo.tags.add(value);
            }
        }
    }
    postInfo.date = Dictionaries.dates.randomDate(randomDate, membership.creationDate() + DatagenParams.deltaTime);
    //if( postInfo.date > Dictionaries.dates.getEndDateTime() ) return null;
    return postInfo;
}
Example 35
Project: sitebricks-master  File: RegexNegotiator.java View source code
public boolean shouldCall(Map<String, String> negotiations, Request request) {
    Multimap<String, String> headers = request.headers();
    for (Map.Entry<String, String> negotiate : negotiations.entrySet()) {
        Collection<String> collectionOfHeader = headers.get(negotiate.getKey());
        if (null == collectionOfHeader)
            continue;
        Iterator<String> headerValues = collectionOfHeader.iterator();
        String match = negotiate.getValue();
        // Guaranteed never to throw NPE
        boolean shouldFire = false;
        while (headerValues.hasNext()) {
            String value = headerValues.next();
            shouldFire |= value.matches(match);
            for (String val : value.split(",[ ]*")) {
                shouldFire |= val.matches(match);
            }
        }
        if (!shouldFire) {
            return false;
        }
    }
    return true;
}
Example 36
Project: XposedGELSettings-master  File: OnPackagesUpdatedHook.java View source code
// http://androidxref.com/4.4.2_r1/xref/packages/apps/Launcher3/src/com/android/launcher3/AppsCustomizePagedView.java#432
// public void onPackagesUpdated(ArrayList<Object> widgetsAndShortcuts)
@SuppressWarnings("unchecked")
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
    if (DEBUG)
        log(param, "Hide Widgets");
    ArrayList<Object> widgets = (ArrayList<Object>) param.args[0];
    Iterator it = widgets.iterator();
    while (it.hasNext()) {
        Object widget = it.next();
        String cmp;
        if (widget instanceof AppWidgetProviderInfo) {
            cmp = ((AppWidgetProviderInfo) widget).provider.flattenToString();
        } else if (widget instanceof ResolveInfo) {
            ResolveInfo item = (ResolveInfo) widget;
            cmp = new ComponentName(item.activityInfo.packageName, item.activityInfo.loadLabel(Common.LAUNCHER_CONTEXT.getPackageManager()).toString()).flattenToString();
        } else {
            continue;
        }
        if (PreferencesHelper.hiddenWidgets.contains(cmp)) {
            it.remove();
        }
    }
    param.args[0] = widgets;
}
Example 37
Project: framework-master  File: TabGetAndReplaceComponent.java View source code
@Override
protected void setup() {
    final TabSheet tabs = new TabSheet();
    tabs.addTab(new Label("Content 1"), "Content 1", null);
    tabs.addTab(new Label("Content 2"), "Content 2", null);
    tabs.addTab(new Label("Content 3"), "Content 3", null);
    tabs.addTab(new Label("Content 4"), "Content 4", null);
    tabs.addTab(new Label("Content 5"), "Content 5", null);
    addComponent(tabs);
    Button replace2 = new Button("Replace Content 2", new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            Iterator<Component> iter = tabs.getComponentIterator();
            iter.next();
            Component content2 = iter.next();
            Tab tab = tabs.getTab(content2);
            // Replace content
            tabs.replaceComponent(tab.getComponent(), new Label("Replacement 2"));
        }
    });
    addComponent(replace2);
}
Example 38
Project: org.openntf.domino-master  File: ScatterPipe.java View source code
public E processNextStart() {
    while (true) {
        if (this.tempIterator.hasNext()) {
            return this.tempIterator.next();
        } else {
            final Object object = this.starts.next();
            if (object instanceof Iterator)
                this.tempIterator = (Iterator<E>) object;
            else if (object instanceof Iterable)
                this.tempIterator = ((Iterable<E>) object).iterator();
            else if (object instanceof Map)
                this.tempIterator = (Iterator<E>) ((Map) object).entrySet().iterator();
            else
                return (E) object;
        }
    }
}
Example 39
Project: jadira-master  File: IterableEnumerationTest.java View source code
private void testValues(Iterator<String> myIter) {
    assertTrue(myIter.hasNext());
    assertEquals("FOO", myIter.next());
    assertTrue(myIter.hasNext());
    assertEquals("BAR", myIter.next());
    assertTrue(myIter.hasNext());
    assertEquals("THE_END", myIter.next());
    assertFalse(myIter.hasNext());
    try {
        myIter.next();
        fail("Should throw NoSuchElementException");
    } catch (NoSuchElementException e) {
    }
}
Example 40
Project: katharsis-core-master  File: RequestBodyDeserializer.java View source code
@Override
public RequestBody deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jp.readValueAsTree();
    if (node == null) {
        return null;
    }
    RequestBody requestBody = new RequestBody();
    JsonNode data = node.get("data");
    Object value;
    if (data != null) {
        if (data.isArray()) {
            Iterator<JsonNode> nodeIterator = data.iterator();
            List<DataBody> dataBodies = new LinkedList<>();
            while (nodeIterator.hasNext()) {
                DataBody newLinkage = jp.getCodec().treeToValue(nodeIterator.next(), DataBody.class);
                dataBodies.add(newLinkage);
            }
            value = dataBodies;
        } else if (data.isObject()) {
            value = jp.getCodec().treeToValue(data, DataBody.class);
        } else if (data.isNull()) {
            value = null;
        } else {
            throw new RuntimeException("data field has wrong type: " + data.toString());
        }
        requestBody.setData(value);
    }
    return requestBody;
}
Example 41
Project: eclipse.jdt.ui-master  File: ConvertIterableLoopQuickFixTest.java View source code
public void testSimplestSmokeCase() throws Exception {
    IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test;\r\n");
    buf.append("import java.util.Collection;\r\n");
    buf.append("import java.util.Iterator;\r\n");
    buf.append("public class A {\r\n");
    buf.append("	Collection<String> c;\r\n");
    buf.append("	public A() {\r\n");
    buf.append("		for (final Iterator<String> iterator= c.iterator(); iterator.hasNext();) {\r\n");
    buf.append("			String test= iterator.next();\r\n");
    buf.append("			System.out.println(test);\r\n");
    buf.append("		}\r\n");
    buf.append("	}\r\n");
    buf.append("}");
    ICompilationUnit unit = pack.createCompilationUnit("A.java", buf.toString(), false, null);
    List<IJavaCompletionProposal> proposals = fetchConvertingProposal(buf, unit);
    assertNotNull(fConvertLoopProposal);
    assertCorrectLabels(proposals);
    String preview = getPreviewContent(fConvertLoopProposal);
    buf = new StringBuffer();
    buf.append("package test;\r\n");
    buf.append("import java.util.Collection;\r\n");
    buf.append("public class A {\r\n");
    buf.append("	Collection<String> c;\r\n");
    buf.append("	public A() {\r\n");
    buf.append("		for (String test : c) {\r\n");
    buf.append("			System.out.println(test);\r\n");
    buf.append("		}\r\n");
    buf.append("	}\r\n");
    buf.append("}");
    String expected = buf.toString();
    assertEqualString(preview, expected);
}
Example 42
Project: eclipse.jdt.core-master  File: ForeachStatementTest.java View source code
public void test022() throws Exception {
    this.runConformTest(new String[] { "X.java", "import java.util.ArrayList;\n" + "\n" + "public class X {\n" + "	public static void main(String[] args) {\n" + "		ArrayList<Integer> arrayList = new ArrayList<Integer>();\n" + "		for (int i = 0; i < 10; i++) {\n" + "			arrayList.add(new Integer(i));\n" + "		}\n" + "		int sum = 0;\n" + "		for (Integer e : arrayList) {\n" + "			sum += e.intValue();\n" + "		}\n" + "		System.out.println(sum);\n" + "	}\n" + "}" }, "45");
    String expectedOutput = "  // Method descriptor #15 ([Ljava/lang/String;)V\n" + "  // Stack: 4, Locals: 5\n" + "  public static void main(java.lang.String[] args);\n" + "     0  new java.util.ArrayList [16]\n" + "     3  dup\n" + "     4  invokespecial java.util.ArrayList() [18]\n" + "     7  astore_1 [arrayList]\n" + "     8  iconst_0\n" + "     9  istore_2 [i]\n" + "    10  goto 29\n" + "    13  aload_1 [arrayList]\n" + "    14  new java.lang.Integer [19]\n" + "    17  dup\n" + "    18  iload_2 [i]\n" + "    19  invokespecial java.lang.Integer(int) [21]\n" + "    22  invokevirtual java.util.ArrayList.add(java.lang.Object) : boolean [24]\n" + "    25  pop\n" + "    26  iinc 2 1 [i]\n" + "    29  iload_2 [i]\n" + "    30  bipush 10\n" + "    32  if_icmplt 13\n" + "    35  iconst_0\n" + "    36  istore_2 [sum]\n" + "    37  aload_1 [arrayList]\n" + "    38  invokevirtual java.util.ArrayList.iterator() : java.util.Iterator [28]\n" + "    41  astore 4\n" + "    43  goto 64\n" + "    46  aload 4\n" + "    48  invokeinterface java.util.Iterator.next() : java.lang.Object [32] [nargs: 1]\n" + "    53  checkcast java.lang.Integer [19]\n" + "    56  astore_3 [e]\n" + "    57  iload_2 [sum]\n" + "    58  aload_3 [e]\n" + "    59  invokevirtual java.lang.Integer.intValue() : int [38]\n" + "    62  iadd\n" + "    63  istore_2 [sum]\n" + "    64  aload 4\n" + "    66  invokeinterface java.util.Iterator.hasNext() : boolean [42] [nargs: 1]\n" + "    71  ifne 46\n" + "    74  getstatic java.lang.System.out : java.io.PrintStream [46]\n" + "    77  iload_2 [sum]\n" + "    78  invokevirtual java.io.PrintStream.println(int) : void [52]\n" + "    81  return\n" + "      Line numbers:\n" + "        [pc: 0, line: 5]\n" + "        [pc: 8, line: 6]\n" + "        [pc: 13, line: 7]\n" + "        [pc: 26, line: 6]\n" + "        [pc: 35, line: 9]\n" + "        [pc: 37, line: 10]\n" + "        [pc: 57, line: 11]\n" + "        [pc: 64, line: 10]\n" + "        [pc: 74, line: 13]\n" + "        [pc: 81, line: 14]\n" + "      Local variable table:\n" + "        [pc: 0, pc: 82] local: args index: 0 type: java.lang.String[]\n" + "        [pc: 8, pc: 82] local: arrayList index: 1 type: java.util.ArrayList\n" + "        [pc: 10, pc: 35] local: i index: 2 type: int\n" + "        [pc: 37, pc: 82] local: sum index: 2 type: int\n" + "        [pc: 57, pc: 64] local: e index: 3 type: java.lang.Integer\n" + "      Local variable type table:\n" + "        [pc: 8, pc: 82] local: arrayList index: 1 type: java.util.ArrayList<java.lang.Integer>\n";
    File f = new File(OUTPUT_DIR + File.separator + "X.class");
    byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(f);
    ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
    String result = disassembler.disassemble(classFileBytes, "\n", ClassFileBytesDisassembler.DETAILED);
    int index = result.indexOf(expectedOutput);
    if (index == -1 || expectedOutput.length() == 0) {
        System.out.println(Util.displayString(result, 3));
    }
    if (index == -1) {
        assertEquals("Wrong contents", expectedOutput, result);
    }
}
Example 43
Project: yarn-comment-master  File: IndexUpdateCombiner.java View source code
/* (non-Javadoc)
   * @see org.apache.hadoop.mapred.Reducer#reduce(java.lang.Object, java.util.Iterator, org.apache.hadoop.mapred.OutputCollector, org.apache.hadoop.mapred.Reporter)
   */
public void reduce(Shard key, Iterator<IntermediateForm> values, OutputCollector<Shard, IntermediateForm> output, Reporter reporter) throws IOException {
    String message = key.toString();
    IntermediateForm form = null;
    while (values.hasNext()) {
        IntermediateForm singleDocForm = values.next();
        long formSize = form == null ? 0 : form.totalSizeInBytes();
        long singleDocFormSize = singleDocForm.totalSizeInBytes();
        if (form != null && formSize + singleDocFormSize > maxSizeInBytes) {
            closeForm(form, message);
            output.collect(key, form);
            form = null;
        }
        if (form == null && singleDocFormSize >= nearMaxSizeInBytes) {
            output.collect(key, singleDocForm);
        } else {
            if (form == null) {
                form = createForm(message);
            }
            form.process(singleDocForm);
        }
    }
    if (form != null) {
        closeForm(form, message);
        output.collect(key, form);
    }
}
Example 44
Project: deep-spark-master  File: DeepRDD.java View source code
@Override
public Iterator<T> compute(Partition split, TaskContext context) {
    initExtractorClient();
    extractorClient.initIterator(split, config.getValue());
    context.addTaskCompletionListener(new AbstractFunction1<TaskContext, BoxedUnit>() {

        @Override
        public BoxedUnit apply(TaskContext v1) {
            extractorClient.close();
            return null;
        }
    });
    java.util.Iterator<T> iterator = new java.util.Iterator<T>() {

        @Override
        public boolean hasNext() {
            return extractorClient.hasNext();
        }

        @Override
        public T next() {
            return extractorClient.next();
        }

        @Override
        public void remove() {
            throw new DeepIOException("Method not implemented (and won't be implemented anytime soon!!!)");
        }
    };
    return new InterruptibleIterator<>(context, asScalaIterator(iterator));
}
Example 45
Project: ijoyplus-android-master  File: CollectionSerializer.java View source code
/*
    /**********************************************************
    /* Actual serialization
    /**********************************************************
     */
@Override
public void serializeContents(Collection<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
    if (_elementSerializer != null) {
        serializeContentsUsing(value, jgen, provider, _elementSerializer);
        return;
    }
    Iterator<?> it = value.iterator();
    if (!it.hasNext()) {
        return;
    }
    PropertySerializerMap serializers = _dynamicSerializers;
    final TypeSerializer typeSer = _valueTypeSerializer;
    int i = 0;
    try {
        do {
            Object elem = it.next();
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
            } else {
                Class<?> cc = elem.getClass();
                JsonSerializer<Object> serializer = serializers.serializerFor(cc);
                if (serializer == null) {
                    // To fix [JACKSON-508]
                    if (_elementType.hasGenericTypes()) {
                        serializer = _findAndAddDynamic(serializers, provider.constructSpecializedType(_elementType, cc), provider);
                    } else {
                        serializer = _findAndAddDynamic(serializers, cc, provider);
                    }
                    serializers = _dynamicSerializers;
                }
                if (typeSer == null) {
                    serializer.serialize(elem, jgen, provider);
                } else {
                    serializer.serializeWithType(elem, jgen, provider, typeSer);
                }
            }
            ++i;
        } while (it.hasNext());
    } catch (Exception e) {
        wrapAndThrow(provider, e, value, i);
    }
}
Example 46
Project: SimpleRep-master  File: SoapHelper.java View source code
public static int getLastSequenceID(SOAPHeader soapHeader) {
    Iterator headers = soapHeader.getHeadersToProcess(null, "http://www.w3.org/2005/08/addressing");
    int seqId = -1;
    int lastSeqId = -1;
    boolean isReset = false;
    SOAPHeaderBlock referenceParametersHeaderBlock = null;
    while (headers.hasNext()) {
        SOAPHeaderBlock soapHeaderBlock = (SOAPHeaderBlock) headers.next();
        String localName = soapHeaderBlock.getLocalName();
        if (localName.equals("SequenceID")) {
            try {
                seqId = Integer.parseInt(soapHeaderBlock.getText());
            } catch (NumberFormatException e) {
                return -1;
            }
            return seqId;
        }
    }
    return -1;
}
Example 47
Project: freemind-mmx-master  File: AddLinkToMapAction.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * freemind.extensions.NodeHookAdapter#invoke(freemind.modes.MindMapNode)
	 */
public void invoke(MindMapNode pNode) {
    List selecteds = getMindMapController().getSelecteds();
    for (Iterator it = selecteds.iterator(); it.hasNext(); ) {
        MindMapNode node = (MindMapNode) it.next();
        MapNodePositionHolder hook = MapNodePositionHolder.getHook(node);
        if (hook != null) {
            if (node.getLink() != null) {
                // TODO: ask user if should overwrite?
                continue;
            }
            getMindMapController().setLink(node, FreeMindMapController.getLink(hook));
        }
    }
}
Example 48
Project: lucene-solr-master  File: RejectingUpdateConflictResolver.java View source code
@Override
public Iterator<SolrInputDocument> orderUpdates(Text key, Iterator<SolrInputDocument> updates, Context ctx) {
    SolrInputDocument firstUpdate = null;
    while (updates.hasNext()) {
        if (firstUpdate == null) {
            firstUpdate = updates.next();
            assert firstUpdate != null;
        } else {
            throw new IllegalArgumentException("Update conflict! Documents with the same unique key are forbidden: " + key);
        }
    }
    assert firstUpdate != null;
    return Collections.singletonList(firstUpdate).iterator();
}
Example 49
Project: molgenis-master  File: AbstractRepositoryEntityAnnotator.java View source code
@Override
@Transactional
@RunAsSystem
public Iterator<Entity> annotate(final Iterable<Entity> sourceIterable, boolean updateMode) {
    Iterator<Entity> source = sourceIterable.iterator();
    return new Iterator<Entity>() {

        int current = 0;

        int size = 0;

        List<Entity> results;

        Entity result;

        @Override
        public boolean hasNext() {
            return current < size || source.hasNext();
        }

        @Override
        public Entity next() {
            Entity sourceEntity = null;
            if (current >= size) {
                if (source.hasNext()) {
                    try {
                        sourceEntity = source.next();
                        results = annotateEntity(sourceEntity, updateMode);
                    } catch (Exception e) {
                        throw new AnnotationException(sourceEntity, current + 1, getRequiredAttributes(), getSimpleName(), e);
                    }
                    size = results.size();
                }
                current = 0;
            }
            if (results.size() > 0) {
                result = results.get(current);
            } else {
                result = sourceEntity;
            }
            ++current;
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
Example 50
Project: flink-master  File: StormStreamSelectorTest.java View source code
@Test
public void testSelector() {
    StormStreamSelector<Object> selector = new StormStreamSelector<Object>();
    SplitStreamType<Object> tuple = new SplitStreamType<Object>();
    Iterator<String> result;
    tuple.streamId = "stream1";
    result = selector.select(tuple).iterator();
    Assert.assertEquals("stream1", result.next());
    Assert.assertFalse(result.hasNext());
    tuple.streamId = "stream2";
    result = selector.select(tuple).iterator();
    Assert.assertEquals("stream2", result.next());
    Assert.assertFalse(result.hasNext());
    tuple.streamId = "stream1";
    result = selector.select(tuple).iterator();
    Assert.assertEquals("stream1", result.next());
    Assert.assertFalse(result.hasNext());
}
Example 51
Project: wpcleaner-master  File: ApiXmlRandomPagesResult.java View source code
/**
   * Execute random pages request.
   * 
   * @param properties Properties defining request.
   * @param list List to be filled with random pages.
   * @throws APIException
   */
@Override
public void executeRandomList(Map<String, String> properties, List<Page> list) throws APIException {
    try {
        Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);
        // Get random list
        XPathExpression<Element> xpa = XPathFactory.instance().compile("/api/query/random/page", Filters.element());
        List<Element> results = xpa.evaluate(root);
        Iterator<Element> iter = results.iterator();
        while (iter.hasNext()) {
            Element currentNode = iter.next();
            Page page = DataManager.getPage(getWiki(), currentNode.getAttributeValue("title"), null, null, null);
            page.setNamespace(currentNode.getAttributeValue("ns"));
            page.setPageId(currentNode.getAttributeValue("pageid"));
            list.add(page);
        }
    } catch (JDOMException e) {
        log.error("Error loading random list", e);
        throw new APIException("Error parsing XML", e);
    }
}