javatips.net counter

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: BreadthFirstIterator.java View source code
/**
     * Initialize (or re-initialize) this iterator.
     * @param o Either a source node or iterator over source nodes
     * @param depth the maximum graph distance to traverse
     * @param traversal the traversal type, one of
     * [email protected] prefuse.Constants#NODE_TRAVERSAL},
     * [email protected] prefuse.Constants#EDGE_TRAVERSAL}, or
     * [email protected] prefuse.Constants#NODE_AND_EDGE_TRAVERSAL}
     */
public void init(Object o, int depth, int traversal) {
    // initialize the member variables
    m_queue.clear();
    m_depth = depth;
    if (traversal < 0 || traversal >= Constants.TRAVERSAL_COUNT)
        throw new IllegalArgumentException("Unrecognized traversal type: " + traversal);
    m_traversal = traversal;
    m_includeNodes = (traversal == Constants.NODE_TRAVERSAL || traversal == Constants.NODE_AND_EDGE_TRAVERSAL);
    m_includeEdges = (traversal == Constants.EDGE_TRAVERSAL || traversal == Constants.NODE_AND_EDGE_TRAVERSAL);
    // TODO: clean this up? (use generalized iterator?)
    if (m_includeNodes) {
        if (o instanceof Node) {
            m_queue.add(o, 0);
        } else {
            Iterator tuples = (Iterator) o;
            while (tuples.hasNext()) m_queue.add(tuples.next(), 0);
        }
    } else {
        if (o instanceof Node) {
            Node n = (Node) o;
            m_queue.visit(n, 0);
            Iterator edges = getEdges(n);
            while (edges.hasNext()) {
                Edge e = (Edge) edges.next();
                Node nn = e.getAdjacentNode(n);
                m_queue.visit(nn, 1);
                if (m_queue.getDepth(e) < 0)
                    m_queue.add(e, 1);
            }
        } else {
            Iterator tuples = (Iterator) o;
            while (tuples.hasNext()) {
                // TODO: graceful error handling when non-node in set?
                Node n = (Node) tuples.next();
                m_queue.visit(n, 0);
                Iterator edges = getEdges(n);
                while (edges.hasNext()) {
                    Edge e = (Edge) edges.next();
                    Node nn = e.getAdjacentNode(n);
                    m_queue.visit(nn, 1);
                    if (m_queue.getDepth(e) < 0)
                        m_queue.add(e, 1);
                }
            }
        }
    }
}
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: OntologyUtils.java View source code
private static void dumpSchemas(Ontology ontology, Iterator iter, String prefix) throws OntologyException {
    String name;
    ObjectSchema os;
    while (iter.hasNext()) {
        name = (String) iter.next();
        os = ontology.getSchema(name);
        System.out.print("  " + prefix + " " + name);
        ObjectSchema[] superSchemas = os.getSuperSchemas();
        if (superSchemas != null && superSchemas.length > 0) {
            System.out.print(" [ superschemas: ");
            for (int j = 0; j < superSchemas.length; j++) {
                System.out.print(superSchemas[j] + " ");
            }
            System.out.print("]");
        }
        System.out.println(" ::= {");
        String[] names = os.getNames();
        for (int i = 0; i < names.length; i++) {
            System.out.print("    " + names[i] + ": ");
            ObjectSchema schema = os.getSchema(names[i]);
            if (schema == null) {
                System.out.println("ERROR: no schema!");
            } else {
                System.out.println(schema.getTypeName());
            }
        }
        System.out.println("  }");
    }
}
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: MultiCertStoreSpi.java View source code
public Collection engineGetCertificates(CertSelector certSelector) throws CertStoreException {
    boolean searchAllStores = params.getSearchAllStores();
    Iterator iter = params.getCertStores().iterator();
    List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
    while (iter.hasNext()) {
        CertStore store = (CertStore) iter.next();
        Collection certs = store.getCertificates(certSelector);
        if (searchAllStores) {
            allCerts.addAll(certs);
        } else if (!certs.isEmpty()) {
            return certs;
        }
    }
    return allCerts;
}
Example 18
Project: teiid-designer-master  File: EmfContainerSetup.java View source code
//############################################################################################################################
//# Instance Methods                                                                                                         #
//############################################################################################################################
/**
     * Creates the list of containers named by the keys within the specified map, marking the one, if any, that matches the
     * specified primary container as such.  The values for each map entry contain a list of model names that are then added to
     * each respective container.
     * @param primaryContainer The name of the primary container, if any.  May be null.
     * @since 3.1
     */
public void containerSetUp(final Map containers, final String primaryContainer) {
    final Set set = containers.entrySet();
    for (final Iterator ctnrIter = set.iterator(); ctnrIter.hasNext(); ) {
        final Entry entry = (Entry) ctnrIter.next();
        final String ctnr = (String) entry.getKey();
        EmfContainerUtils.createContainer(ctnr, ctnr.equals(primaryContainer));
        final List models = (List) entry.getValue();
        for (final Iterator modelIter = models.iterator(); modelIter.hasNext(); ) {
            EmfContainerUtils.addModel((String) modelIter.next(), ctnr);
        }
    }
}
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: MixAllThread.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();
        String source = recFile._path;
        String mix = _config.getString("mixFile");
        double fac = _config.getDouble("mixFactor");
        String mixExt = _config.getString("mixExtension");
        String out = FileUtil.addNamePart(recFile._path, mixExt);
        new SoundMixer().mix(source, mix, out, fac);
        _logger.debug("mixing " + source + " and " + mix + " with factor " + fac + " to " + out);
    }
    System.out.println("finished mixing all files!");
    _isRunning = false;
}
Example 21
Project: cdo-master  File: CompareActionDelegate.java View source code
@Override
protected void doRun(IProgressMonitor progressMonitor) throws Exception {
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection ssel = (IStructuredSelection) selection;
        List<TARGET> targets = new ArrayList<TARGET>();
        @SuppressWarnings("unchecked") Iterator<Object> iterator = ssel.iterator();
        while (iterator.hasNext()) {
            Object element = iterator.next();
            TARGET target = AdapterUtil.adapt(element, targetClass);
            if (target != null) {
                targets.add(target);
            }
        }
        run(targets, progressMonitor);
    }
}
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: FileSystemNodeTest.java View source code
/**
     * Just test it doesn't raise an error.
     * TODO : move tests from shapefile.
     */
@Test
public void testNoerror() throws Exception {
    final File file = new File("src/test/resources/org/geotoolkit/index/sample.qix");
    final FileSystemIndexStore store = new FileSystemIndexStore(file);
    final DataReader reader = new DataReader() {

        @Override
        public Data read(final int id) throws IOException {
            return new DefaultData(DATA_DEFINITION) {

                @Override
                public String toString() {
                    return Integer.toString(id);
                }
            };
        }

        @Override
        public void close() throws IOException {
        }

        @Override
        public void read(int[] ids, Data[] buffer, int size) throws IOException {
            for (int i = 0; i < size; i++) {
                buffer[i] = read(ids[i]);
            }
        }
    };
    final QuadTree tree = store.load();
    assertEquals(10, tree.getMaxDepth());
    assertEquals(new Envelope(-8.86966023318779, 3.188061808903407, 36.113981340792286, 43.55971524165336), tree.getRoot().getBounds(new Envelope()));
    assertEquals(3602, tree.getNumShapes());
    final AbstractNode root = tree.getRoot();
    for (int i = 0; i < 4; i++) {
        root.getSubNode(i);
    }
    CloseableCollection col = tree.search(reader, new Envelope(-8, 3, 37, 40));
    Iterator ite = col.iterator();
    while (ite.hasNext()) {
        ite.next();
    }
}
Example 24
Project: hibernate-core-ogm-master  File: MckoiCaseFragment.java View source code
public String toFragmentString() {
    StringBuffer buf = new StringBuffer(cases.size() * 15 + 10);
    StringBuffer buf2 = new StringBuffer(cases.size());
    Iterator iter = cases.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry me = (Map.Entry) iter.next();
        buf.append(" if(").append(me.getKey()).append(" is not null").append(", ").append(me.getValue()).append(", ");
        buf2.append(")");
    }
    buf.append("null");
    buf.append(buf2);
    if (returnColumnName != null) {
        buf.append(" as ").append(returnColumnName);
    }
    return buf.toString();
}
Example 25
Project: hdt-java-master  File: MultiMergeTest.java View source code
@Test
public void testCase() {
    List<Iterator<Integer>> list = new ArrayList<>();
    list.add(listA.iterator());
    list.add(listB.iterator());
    list.add(listC.iterator());
    Iterator<Integer> it = new MultiMerge<Integer>(list.iterator(), new IntegerComparator());
    it = new SortedReduceIterator<>(it, new ReducerLeft<Integer>());
    Iterator<Integer> itE = listOutB.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: ApiXmlTokensResult.java View source code
/**
   * Execute tokens request.
   * 
   * @param properties Properties defining request.
   * @throws APIException
   */
@Override
public void executeTokens(Map<String, String> properties) throws APIException {
    try {
        Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);
        // Get recent changes list
        XPathExpression<Element> xpa = XPathFactory.instance().compile("/api/tokens", Filters.element());
        List<Element> results = xpa.evaluate(root);
        Iterator<Element> iter = results.iterator();
        while (iter.hasNext()) {
            Element currentNode = iter.next();
            String deleteToken = currentNode.getAttributeValue("deletetoken");
            if (deleteToken != null) {
                getWiki().getConnection().setDeleteToken(deleteToken);
            }
            String editToken = currentNode.getAttributeValue("edittoken");
            if (editToken != null) {
                getWiki().getConnection().setEditToken(editToken);
            }
        }
    } catch (JDOMException e) {
        log.error("Error retrieving tokens", e);
        throw new APIException("Error parsing XML", e);
    }
}
Example 52
Project: androiddevice.info-master  File: OtacertsProperty.java View source code
@Override
public Object getProperty() throws JSONException {
    JSONObject result = new JSONObject();
    try {
        Iterator<Map.Entry<String, X509Certificate>> certs = getTrustedCerts(new File("/system/etc/security/otacerts.zip")).entrySet().iterator();
        while (certs.hasNext()) {
            Map.Entry<String, X509Certificate> cert = certs.next();
            result.put(cert.getKey(), encodeToString(cert.getValue().getEncoded(), Base64.DEFAULT));
        }
    } catch (IOException e) {
        return JSONObject.NULL;
    } catch (GeneralSecurityException e) {
        return JSONObject.NULL;
    }
    return result;
}
Example 53
Project: mkgmap-master  File: BoundaryLister.java View source code
/**
	 * @param args
	 * @throws IOException 
	 */
public static void main(String[] args) throws IOException {
    String boundsdir = args[0];
    String outDirName = boundsdir;
    if (args.length >= 2)
        outDirName = args[1];
    File outDir = new File(outDirName);
    if (outDir.exists()) {
        if (outDir.isDirectory() == false) {
            System.err.println("target is not a directory, output is written to bounds.txt");
            outDir = new File(".");
        }
    }
    List<String> bndFileNames = BoundaryUtil.getBoundaryDirContent(boundsdir);
    PrintWriter out = new PrintWriter(new File(outDir, "bounds.txt"), "UTF-8");
    //uk.me.parabola.imgfmt.app.Area searchBbox = new uk.me.parabola.imgfmt.app.Area (0,0,0,0);
    for (String bndFile : bndFileNames) {
        out.println(bndFile + "****************");
        BoundaryQuadTree bqt = BoundaryUtil.loadQuadTree(boundsdir, bndFile);
        if (bqt == null)
            break;
        Map<String, Tags> map = bqt.getTagsMap();
        for (Entry<String, Tags> entry : map.entrySet()) {
            TreeMap<String, String> btree = new TreeMap<String, String>();
            String line = bndFile + ":" + entry.getKey();
            Iterator<Entry<String, String>> tagIter = entry.getValue().entryIterator();
            while (tagIter.hasNext()) {
                Entry<String, String> tag = tagIter.next();
                btree.put(tag.getKey(), tag.getValue());
            }
            // print sorted tags
            for (Entry<String, String> e : btree.entrySet()) {
                out.println(line + ";" + e);
            }
        }
    }
    out.close();
}
Example 54
Project: MyFramework-master  File: JsonUtil.java View source code
/**
	 * 针对DWZ的下拉框返回的数据格式
	 * 例如:[["a","b"]]
	 * @param map
	 * @param isAdd 判断是否为添加界面
	 * @return
	 */
public static String toDWZComboxData(Map<String, String> map, String isSelect) {
    StringBuffer comBoxStr = new StringBuffer("");
    if (StringUtils.equalsIgnoreCase(isSelect, "true")) {
        comBoxStr.append("[[\"\",\"全部\"]");
    } else {
        comBoxStr.append("[[\"\",\"请选择\"]");
    }
    if (map != null && map.size() > 0) {
        @SuppressWarnings("rawtypes") Iterator item = map.entrySet().iterator();
        while (item.hasNext()) {
            @SuppressWarnings("unchecked") Entry<String, String> entry = (Entry<String, String>) item.next();
            comBoxStr.append(",");
            comBoxStr.append("[\"" + entry.getKey() + "\",\"" + entry.getValue() + "\"]");
        }
    }
    comBoxStr.append("]");
    return comBoxStr.toString();
}
Example 55
Project: rascal-master  File: FCA.java View source code
// rel[&Object, &Attribute] fc, set[&Object] objects 
public ISet sigma(ISet fc, ISet objects) {
    ISetRelation<ISet> fcRelation = fc.asRelation();
    if (objects.isEmpty()) {
        return fcRelation.range();
    }
    ISetWriter result = vf.setWriter();
    for (Iterator<IValue> attributes = fcRelation.range().iterator(); attributes.hasNext(); ) {
        IValue attr = attributes.next();
        boolean all = true;
        for (Iterator<IValue> objs = objects.iterator(); objs.hasNext(); ) {
            IValue obj = objs.next();
            all &= fc.contains(vf.tuple(obj, attr));
            if (!all) {
                break;
            }
        }
        if (all) {
            result.insert(attr);
        }
    }
    return result.done();
}
Example 56
Project: magnificent-mileage-master  File: TestJoinedList.java View source code
@SuppressWarnings("unchecked")
public void testJoinedList() {
    ArrayList<Integer> list1 = new ArrayList<Integer>();
    list1.add(0);
    list1.add(1);
    list1.add(2);
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2.add(3);
    list2.add(4);
    list2.add(5);
    JoinedList<Integer> joined = new JoinedList<Integer>(list1, list2);
    assertTrue(joined.get(0) == 0);
    assertTrue(joined.get(3) == 3);
    Iterator<Integer> it = joined.iterator();
    for (int i = 0; i < 6; ++i) {
        assertTrue(it.hasNext());
        assertTrue(it.next() == i);
    }
    assertFalse(it.hasNext());
}
Example 57
Project: kabeja-master  File: Demo.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    Parser parser = DXFParserBuilder.createDefaultParser();
    try {
        DraftDocument doc = parser.parse(new FileInputStream("/home/simon/Desktop/kabeja/test4martin.dxf"), new HashMap());
        Layer layer = doc.getLayer("0");
        List solids = layer.getEntitiesByType(Type.TYPE_3DSOLID);
        Iterator i = solids.iterator();
        while (i.hasNext()) {
            Solid3D solid = (Solid3D) i.next();
            List acisData = solid.getACISDATA();
            Iterator lines = acisData.iterator();
            System.out.println("ACISData from=" + solid.getID() + ">>>>>>>>");
            while (lines.hasNext()) {
                System.out.println(lines.next());
            }
            System.out.println("<<<<<<<<<<<<<<");
        }
    } catch (Exception e) {
    }
}
Example 58
Project: bigpetstore-master  File: MetricsRecordFiltered.java View source code
public Iterable<Metric> metrics() {
    return new Iterable<Metric>() {

        final Iterator<Metric> it = delegate.metrics().iterator();

        public Iterator<Metric> iterator() {
            return new TryIterator<Metric>() {

                public Metric tryNext() {
                    if (it.hasNext())
                        do {
                            Metric next = it.next();
                            if (filter.accepts(next.name())) {
                                return next;
                            }
                        } while (it.hasNext());
                    return done();
                }
            };
        }
    };
}
Example 59
Project: erlide-master  File: ErlcMessageParser.java View source code
/**
     * Parses messages from erlc and creates the markers on the appropriate
     * resource. Returns true if any marker was created.
     *
     * Format is filename:line: message
     *
     */
@Override
public boolean createMarkers(final String msg) {
    boolean result = false;
    final Iterable<String> pars = Splitter.on(':').limit(3).split(msg);
    if (pars.iterator().next().equals("ERROR")) {
        MarkerUtils.createProblemMarker(project, null, pars.iterator().next(), -1, IMarker.SEVERITY_ERROR);
        result = true;
    } else {
        final Iterator<String> iterator = pars.iterator();
        try {
            final String filename = iterator.next();
            final int line = Integer.parseInt(iterator.next());
            final String rawmessage = iterator.next().trim();
            String message;
            int severity;
            if (rawmessage.startsWith("Warning: ")) {
                message = rawmessage.substring("Warning: ".length());
                severity = IMarker.SEVERITY_WARNING;
            } else {
                message = rawmessage;
                severity = IMarker.SEVERITY_ERROR;
            }
            final IResource resource = project.findMember(filename);
            if (resource != null) {
                MarkerUtils.createProblemMarker(resource, null, message, line, severity);
                result = true;
            }
        } catch (final Exception e) {
        }
    }
    return result;
}
Example 60
Project: liferay-ide-master  File: VelocityAnnotationHover.java View source code
/**
     * Returns one marker which includes the ruler's line of activity.
     */
protected IMarker getMarkerForLine(ISourceViewer aViewer, int aLine) {
    IMarker marker = null;
    IAnnotationModel model = aViewer.getAnnotationModel();
    if (model != null) {
        Iterator e = model.getAnnotationIterator();
        while (e.hasNext()) {
            Object o = e.next();
            if (o instanceof MarkerAnnotation) {
                MarkerAnnotation a = (MarkerAnnotation) o;
                if (compareRulerLine(model.getPosition(a), aViewer.getDocument(), aLine) != 0) {
                    marker = a.getMarker();
                }
            }
        }
    }
    return marker;
}
Example 61
Project: tcf-master  File: DetachHandler.java View source code
/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
        Iterator<?> iterator = ((IStructuredSelection) selection).iterator();
        while (iterator.hasNext()) {
            final Object candidate = iterator.next();
            if (candidate instanceof IProcessContextNode) {
                Runnable runnable = new Runnable() {

                    @Override
                    public void run() {
                        DetachStep step = new DetachStep();
                        step.executeDetach((IProcessContextNode) candidate, null);
                    }
                };
                Protocol.invokeLater(runnable);
            }
        }
    }
    return null;
}
Example 62
Project: Biota-master  File: BlockTransformer.java View source code
@Override
public byte[] transform(String transformedName, byte[] clazz) {
    //Biota.logger.debug("Transforming: " + transformedName);
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(clazz);
    classReader.accept(classNode, 0);
    for (MethodNode methodNode : classNode.methods) {
        if (methodNode.name.equals(REGISTER) && methodNode.desc.equals(REGISTER_DESC)) {
            Iterator<AbstractInsnNode> iterator = methodNode.instructions.iterator();
            while (iterator.hasNext()) {
                AbstractInsnNode node = iterator.next();
                if (node instanceof LdcInsnNode) {
                    if ("grass".equals(((LdcInsnNode) node).cst)) {
                        node = node.getNext();
                        ((TypeInsnNode) node).desc = "com/dynious/biota/block/BlockNewGrass";
                        node = node.getNext().getNext();
                        ((MethodInsnNode) node).owner = "com/dynious/biota/block/BlockNewGrass";
                        break;
                    }
                }
            }
        }
    }
    ClassWriter classWriter = new ObfRemappingClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    classNode.accept(classWriter);
    return classWriter.toByteArray();
}
Example 63
Project: guava-experimental-master  File: UnmodifiableIteratorTest.java View source code
public void testRemove() {
    final String[] array = { "a", "b", "c" };
    Iterator<String> iterator = new UnmodifiableIterator<String>() {

        int i;

        @Override
        public boolean hasNext() {
            return i < array.length;
        }

        @Override
        public String next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return array[i++];
        }
    };
    assertTrue(iterator.hasNext());
    assertEquals("a", iterator.next());
    try {
        iterator.remove();
        fail();
    } catch (UnsupportedOperationException expected) {
    }
}
Example 64
Project: streamline-master  File: RemoteProxyEntryProducer.java View source code
@Override
public void execute() {
    Iterator<Map.Entry<String, DataType<?>>> iterator = inData.iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, DataType<?>> entry = iterator.next();
        if (entry.getValue() instanceof DataTypeNull) {
            try {
                removeValue(entry.getKey());
            } catch (Exception e) {
                stm.logError(e.getMessage(), e);
            }
        } else {
            DataType<?> data = entry.getValue();
            if (data instanceof DataTypeRef) {
                addReference(entry.getKey(), (DataTypeRef) data);
            } else {
                putValue(entry.getKey(), data);
            }
        }
    }
}
Example 65
Project: pcgen-master  File: SkillListModsToken.java View source code
/**
	 * @see pcgen.io.exporttoken.Token#getToken(java.lang.String, pcgen.core.PlayerCharacter, pcgen.io.ExportHandler)
	 */
@Override
public String getToken(String tokenSource, PlayerCharacter pc, ExportHandler eh) {
    StringBuilder returnString = new StringBuilder();
    boolean needcomma = false;
    final List<Skill> pcSkills = SkillDisplay.getSkillListInOutputOrder(pc);
    Iterator<Skill> iter = pcSkills.iterator();
    while (iter.hasNext()) {
        Skill sk = iter.next();
        if (!pc.includeSkill(sk, SkillFilter.Usable) || !sk.qualifies(pc, null)) {
            iter.remove();
        }
    }
    for (Skill aSkill : pcSkills) {
        int modSkill = -1;
        CDOMSingleRef<PCStat> statref = aSkill.get(ObjectKey.KEY_STAT);
        if (statref != null) {
            modSkill = SkillModifier.modifier(aSkill, pc).intValue() - pc.getStatModFor(statref.get());
        }
        if ((SkillRankControl.getTotalRank(pc, aSkill).intValue() > 0) || (modSkill > 0)) {
            //final
            int temp = SkillModifier.modifier(aSkill, pc).intValue() + SkillRankControl.getTotalRank(pc, aSkill).intValue();
            if (needcomma) {
                returnString.append(", ");
            }
            needcomma = true;
            returnString.append(OutputNameFormatting.getOutputName(aSkill)).append(temp >= 0 ? " +" : " ").append(Integer.toString(temp));
        }
    }
    return returnString.toString();
}
Example 66
Project: wso2-synapse-master  File: TaskManagerSerializer.java View source code
public static OMElement serializetaskManager(OMElement parent, TaskManager taskManager) {
    OMElement executor = fac.createOMElement("taskManager", synNS);
    if (taskManager.getProviderClass() != null) {
        executor.addAttribute(fac.createOMAttribute("provider", nullNS, taskManager.getProviderClass()));
    } else {
        handleException("Invalid taskManager. Provider is required");
    }
    Iterator iter = taskManager.getConfigurationProperties().keySet().iterator();
    while (iter.hasNext()) {
        String name = (String) iter.next();
        String value = (String) taskManager.getConfigurationProperties().get(name);
        OMElement property = fac.createOMElement("parameter", synNS);
        property.addAttribute(fac.createOMAttribute("name", nullNS, name));
        property.setText(value.trim());
        executor.addChild(property);
    }
    if (parent != null) {
        parent.addChild(executor);
    }
    return executor;
}
Example 67
Project: android_platform_libcore-master  File: OldAbstractSetTest.java View source code
public void testRemoveAll() {
    AbstractSet as = new AbstractSet() {

        @Override
        public Iterator iterator() {
            return new Iterator() {

                public boolean hasNext() {
                    return true;
                }

                public Object next() {
                    return null;
                }

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

        @Override
        public int size() {
            return 10;
        }
    };
    try {
        as.removeAll(null);
        fail("NullPointerException expected");
    } catch (NullPointerException e) {
    }
    Collection c = new Vector();
    c.add(null);
    try {
        as.removeAll(c);
        fail("UnsupportedOperationException expected");
    } catch (UnsupportedOperationException e) {
    }
    as = new Mock_AbstractSet();
    as.removeAll(c);
}
Example 68
Project: jeppetto-master  File: DynamoDBOperator.java View source code
//-------------------------------------------------------------
// Methods - Public
//-------------------------------------------------------------
public DynamoDBConstraint buildConstraint(Iterator argsIterator) {
    switch(argumentCount) {
        case 0:
            return new DynamoDBConstraint(this);
        case 2:
            return new DynamoDBConstraint(this, argsIterator.next(), argsIterator.next());
        default:
            return new DynamoDBConstraint(this, argsIterator.next());
    }
}
Example 69
Project: cloudtm-data-platform-master  File: FenixCheckDisconnectedReportGenerator.java View source code
@Override
protected void generateCheckDisconnected(DomainClass domClass, PrintWriter out) {
    newline(out);
    printMethod(out, "protected", "boolean", "checkDisconnected");
    startMethodBody(out);
    println(out, "java.util.List<String> relationList = new java.util.ArrayList<String>();");
    println(out, "boolean result = checkDisconnected(relationList);");
    println(out, "doCheckDisconnectedAction(relationList);");
    println(out, "return result;");
    endMethodBody(out);
    newline(out);
    printMethod(out, "protected", "boolean", "checkDisconnected", "java.util.List connectedRelationList");
    startMethodBody(out);
    if (domClass.hasSuperclass()) {
        println(out, "super.checkDisconnected(connectedRelationList);");
    }
    Iterator<Role> roleSlotsIter = domClass.getRoleSlots();
    while (roleSlotsIter.hasNext()) {
        Role role = roleSlotsIter.next();
        if (role.getName() != null) {
            onNewline(out);
            print(out, "if (");
            if (role.getMultiplicityUpper() == 1) {
                print(out, "has");
            } else {
                print(out, "hasAny");
            }
            print(out, capitalize(role.getName()));
            println(out, String.format("()) connectedRelationList.add(\"%s\"); ", role.getName()));
        }
    }
    println(out, "return connectedRelationList.isEmpty();");
    endMethodBody(out);
}
Example 70
Project: tuprolog-5-master  File: StructIteratorTestCase.java View source code
@Test
public void multipleNext() {
    Struct list = new Struct(new Term[] { new Int(0), new Int(1), new Int(2), new Int(3), new Int(5), new Int(7) });
    Iterator<Term> i = list.iterator();
    assertTrue(i.hasNext());
    // skip the first term
    i.next();
    assertEquals(new Int(1), i.next());
    assertEquals(new Int(2), i.next());
    assertEquals(new Int(3), i.next());
    assertEquals(new Int(5), i.next());
    assertEquals(new Int(7), i.next());
    // no more terms
    assertFalse(i.hasNext());
    try {
        i.next();
        fail();
    } catch (NoSuchElementException expected) {
    }
}
Example 71
Project: gs-collections-master  File: OrderedIterate.java View source code
public static <S, T> boolean corresponds(OrderedIterable<T> o1, OrderedIterable<S> o2, Predicate2<? super T, ? super S> predicate) {
    if (o1.size() != o2.size()) {
        return false;
    }
    if (o1 instanceof RandomAccess) {
        return RandomAccessListIterate.corresponds((List<T>) o1, o2, predicate);
    }
    if (o2 instanceof RandomAccess) {
        List<S> otherList = (List<S>) o2;
        Iterator<T> iterator = o1.iterator();
        for (int index = 0; index < otherList.size(); index++) {
            if (!predicate.accept(iterator.next(), otherList.get(index))) {
                return false;
            }
        }
        return true;
    }
    Iterator<T> iterator1 = o1.iterator();
    Iterator<S> iterator2 = o2.iterator();
    while (iterator1.hasNext()) {
        if (!predicate.accept(iterator1.next(), iterator2.next())) {
            return false;
        }
    }
    return true;
}
Example 72
Project: tinkerpop-master  File: TraverserGenerator.java View source code
public default <S> Iterator<Traverser.Admin<S>> generateIterator(final Iterator<S> starts, final Step<S, ?> startStep, final long initialBulk) {
    return new Iterator<Traverser.Admin<S>>() {

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

        @Override
        public Traverser.Admin<S> next() {
            return generate(starts.next(), startStep, initialBulk);
        }
    };
}
Example 73
Project: Eclipse-Postfix-Code-Completion-master  File: ExternalFolderChange.java View source code
/*
	 * Update external folders
	 */
public void updateExternalFoldersIfNecessary(boolean refreshIfExistAlready, IProgressMonitor monitor) throws JavaModelException {
    HashSet oldFolders = ExternalFoldersManager.getExternalFolders(this.oldResolvedClasspath);
    IClasspathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
    HashSet newFolders = ExternalFoldersManager.getExternalFolders(newResolvedClasspath);
    if (newFolders == null)
        return;
    ExternalFoldersManager foldersManager = JavaModelManager.getExternalManager();
    Iterator iterator = newFolders.iterator();
    while (iterator.hasNext()) {
        Object folderPath = iterator.next();
        if (oldFolders == null || !oldFolders.remove(folderPath) || foldersManager.removePendingFolder(folderPath)) {
            try {
                foldersManager.createLinkFolder((IPath) folderPath, refreshIfExistAlready, monitor);
            } catch (CoreException e) {
                throw new JavaModelException(e);
            }
        }
    }
// removal of linked folders is done during save
}
Example 74
Project: geoserver-enterprise-master  File: RestDispatcherCallback.java View source code
@Override
public void init(Request request, Response response) {
    if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
        final Iterator<Parameter> it = request.getResourceRef().getQueryAsForm().iterator();
        while (it.hasNext()) {
            Parameter p = it.next();
            if (LOGGER.isLoggable(java.util.logging.Level.INFO)) {
                LOGGER.info("Registering incoming parameter: " + p.toString());
            }
        }
    }
    parameters.set(request.getResourceRef().getQueryAsForm());
// check purge parameter to determine if the underlying file
// should be deleted
// boolean purge = (p != null) ? Boolean.parseBoolean(p) : false;
// catalog.getResourcePool().deleteStyle(s, purge);
// LOGGER.info( "DELETE style " + style);
}
Example 75
Project: tdq-studio-se-master  File: BasicQueryParser.java View source code
/* (non-JavaDoc)
	 * @see net.sourceforge.sqlexplorer.parsers.QueryParser#iterator()
	 */
public Iterator<Query> iterator() {
    return new Iterator<Query>() {

        /* (non-JavaDoc)
			 * @see java.util.Iterator#hasNext()
			 */
        public boolean hasNext() {
            return _sNextQuery != null;
        }

        /* (non-JavaDoc)
			 * @see java.util.Iterator#next()
			 */
        public Query next() {
            return nextQuery();
        }

        /* (non-JavaDoc)
			 * @see java.util.Iterator#remove()
			 */
        public void remove() {
            throw new IllegalAccessError();
        }
    };
}
Example 76
Project: hise-master  File: Client2Test.java View source code
@Test
public void testClient() throws Exception {
    Service destinationService = Service.create(getClass().getResource("/ExampleTasks.wsdl"), QName.valueOf("{http://www.insurance.example.com/claims}ClaimsResolvingService"));
    QName destinationPort = null;
    {
        Iterator<QName> it = destinationService.getPorts();
        while (it.hasNext()) {
            QName p = it.next();
            System.out.println(p);
            destinationPort = p;
        }
    }
    Validate.notNull(destinationPort);
    Dispatch<Source> dispatch;
    dispatch = destinationService.createDispatch(destinationPort, Source.class, Service.Mode.PAYLOAD);
    //        Dispatch<SOAPMessage> dispatch;
    //        dispatch = destinationService.createDispatch(destinationPort, SOAPMessage.class, Service.Mode.PAYLOAD);
    dispatch.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8084/ClaimsResponse/");
    //Tue Jan 12 17:50:56 GMT+01:00 2010:DEBUG:>> "SOAPAction: "http://www.insurance.example.com/claims/approve"[\r][\n]"
    //        dispatch.getRequestContext().put(Dispatch.SOAPACTION_URI_PROPERTY, "http://www.insurance.example.com/claims/approve");
    //        SOAPMessage m;
    //        MessageFactory messageFactory = MessageFactory.newInstance();
    //        m = messageFactory.createMessage();
    Document response = DOMUtils.parse("<cla:resolve xmlns:cla=\"http://www.insurance.example.com/claims\"><ok>true</ok></cla:resolve>");
    //        Document doc = m.getSOAPBody().getOwnerDocument();
    //        m.getSOAPBody().appendChild(doc.importNode(response.getDocumentElement(), true));
    //        m.writeTo(System.out);
    dispatch.invoke(new DOMSource(response));
}
Example 77
Project: flare-spork-master  File: LimitConverter.java View source code
@Override
public Iterator<Tuple> apply(Iterator<Tuple> i) {
    final java.util.Iterator<Tuple> tuples = JavaConversions.asJavaIterator(i);
    return JavaConversions.asScalaIterator(new POOutputConsumerIterator(tuples) {

        protected void attach(Tuple tuple) {
            poLimit.setInputs(null);
            poLimit.attachInput(tuple);
        }

        protected Result getNextResult() throws ExecException {
            return poLimit.getNextTuple();
        }
    });
}
Example 78
Project: keycloak-master  File: StringListMapDeserializer.java View source code
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode jsonNode = jsonParser.readValueAsTree();
    Iterator<Map.Entry<String, JsonNode>> itr = jsonNode.fields();
    Map<String, List<String>> map = new HashMap<>();
    while (itr.hasNext()) {
        Map.Entry<String, JsonNode> e = itr.next();
        List<String> values = new LinkedList<>();
        if (!e.getValue().isArray()) {
            values.add(e.getValue().asText());
        } else {
            ArrayNode a = (ArrayNode) e.getValue();
            Iterator<JsonNode> vitr = a.elements();
            while (vitr.hasNext()) {
                values.add(vitr.next().asText());
            }
        }
        map.put(e.getKey(), values);
    }
    return map;
}
Example 79
Project: Valkyrie-RCP-master  File: ExclusiveCommandGroupSelectionController.java View source code
public void handleSelectionRequest(ToggleCommand delegatingCommand, boolean requestingSelection) {
    if (requestingSelection) {
        ToggleCommand currentSelectedCommand = null;
        for (Iterator iterator = commands.iterator(); iterator.hasNext(); ) {
            ToggleCommand command = (ToggleCommand) iterator.next();
            if (command.isSelected()) {
                currentSelectedCommand = command;
                break;
            }
        }
        if (currentSelectedCommand == null) {
            delegatingCommand.requestSetSelection(true);
        } else {
            currentSelectedCommand.requestSetSelection(false);
            delegatingCommand.requestSetSelection(!currentSelectedCommand.isSelected());
            if (!delegatingCommand.isSelected() && currentSelectedCommand != null) {
                currentSelectedCommand.requestSetSelection(true);
            }
        }
    } else {
        // its a deselection
        if (allowsEmptySelection) {
            delegatingCommand.requestSetSelection(false);
        }
    }
}
Example 80
Project: FTL-Hyperion-master  File: KryoNetTestCase.java View source code
public void waitForThreads() {
    fail = false;
    TimerTask failTask = new TimerTask() {

        public void run() {
            stopEndPoints();
            fail = true;
        }
    };
    timer.schedule(failTask, 11000);
    while (true) {
        for (Iterator iter = threads.iterator(); iter.hasNext(); ) {
            Thread thread = (Thread) iter.next();
            if (!thread.isAlive())
                iter.remove();
        }
        if (threads.isEmpty())
            break;
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
    }
    failTask.cancel();
    if (fail)
        fail("Test did not complete in a timely manner.");
    // Give sockets a chance to close before starting the next test.
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ignored) {
    }
}
Example 81
Project: alien4cloud-master  File: AbstractFieldValueDiscriminatorPolymorphicDeserializer.java View source code
protected T deserializeAfterRead(JsonParser jp, DeserializationContext ctxt, ObjectMapper mapper, ObjectNode root) throws JsonProcessingException {
    Class<? extends T> parameterClass = null;
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = root.fields();
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        String name = element.getKey();
        if (propertyDiscriminatorName.equals(name)) {
            String value = element.getValue().asText();
            if (registry.containsKey(value)) {
                parameterClass = registry.get(value);
                break;
            }
        }
    }
    if (parameterClass == null) {
        return null;
    }
    return mapper.treeToValue(root, parameterClass);
}
Example 82
Project: swtbot-master  File: DefaultChildrenResolver.java View source code
public List getChildren(Widget w) {
    List result = new ArrayList();
    if (!hasChildren(w))
        return result;
    List resolvers = resolver.getResolvers(w.getClass());
    for (Iterator iterator = resolvers.iterator(); iterator.hasNext(); ) {
        IChildrenResolver resolver = (IChildrenResolver) iterator.next();
        if (resolver.canResolve(w) && resolver.hasChildren(w)) {
            List children = resolver.getChildren(w);
            if (children != null) {
                result.addAll(children);
                return result;
            }
        }
    }
    return result;
}
Example 83
Project: dashbuilder-master  File: SchedulerTaskComparator.java View source code
public int compare(Object o1, Object o2) {
    if (o1 instanceof SchedulerTask == false)
        return 1;
    if (o2 instanceof SchedulerTask == false)
        return -1;
    if (o1 == null)
        return 1;
    if (o2 == null)
        return -1;
    SchedulerTask entry1 = (SchedulerTask) o1;
    SchedulerTask entry2 = (SchedulerTask) o2;
    Iterator it = sortCriterias.iterator();
    while (it.hasNext()) {
        Object[] criteriaProps = (Object[]) it.next();
        String criteriaId = (String) criteriaProps[0];
        int ordering = (Integer) criteriaProps[1];
        if (criteriaId.equals(TIME_TO_FIRE)) {
            int compById = ComparatorUtils.compare(entry1.getMillisTimeToFire(), entry2.getMillisTimeToFire(), ordering);
            if (compById != 0)
                return compById;
        }
    }
    // Comparison gives equality.
    return 0;
}
Example 84
Project: OpenClinica-master  File: ClinicalDataCollector.java View source code
public void collectOdmClinicalDataMap() {
    Iterator<OdmStudyBase> it = this.getStudyBaseMap().values().iterator();
    while (it.hasNext()) {
        JobTerminationMonitor.check();
        OdmStudyBase u = it.next();
        ClinicalDataUnit cdata = new ClinicalDataUnit(this.ds, this.dataset, this.getOdmbean(), u.getStudy(), this.getCategory());
        cdata.setCategory(this.getCategory());
        StudySubjectDAO ssdao = new StudySubjectDAO(this.ds);
        cdata.setStudySubjectIds(ssdao.findStudySubjectIdsByStudyIds(u.getStudy().getId() + ""));
        cdata.collectOdmClinicalData();
        odmClinicalDataMap.put(u.getStudy().getOid(), cdata.getOdmClinicalData());
    }
}
Example 85
Project: iaf-master  File: RootHandler.java View source code
protected void startElement(String localName) {
    if (!parsedRequestRoot) {
        parsedRequestRoot = true;
    } else {
        Iterator<JCoParameterList> iterator = parameterLists.iterator();
        while (iterator.hasNext()) {
            JCoParameterList jcoParameterList = (JCoParameterList) iterator.next();
            if (jcoParameterList.getMetaData().getName().equals(localName)) {
                childHandler = new ParameterListHandler(jcoParameterList);
            }
        }
        if (childHandler == null) {
            log.warn("parameter list '" + localName + "' does not exist");
            unknownElementDepth = 1;
        }
    }
}
Example 86
Project: jena-master  File: iri.java View source code
public static void main(String[] args) {
    //IRIFactory iriFactory = IRIFactory.iriImplementation() ;
    IRIFactory iriFactory = IRIResolver.iriFactory;
    boolean first = true;
    for (String iriStr : args) {
        if (iriStr.startsWith("<") && iriStr.endsWith(">"))
            iriStr = iriStr.substring(1, iriStr.length() - 1);
        if (!first)
            System.out.println();
        first = false;
        IRI iri = iriFactory.create(iriStr);
        System.out.println(iriStr + " ==> " + iri);
        if (iri.isRelative())
            System.out.println("Relative: " + iri.isRelative());
        Iterator<Violation> vIter = iri.violations(true);
        for (; vIter.hasNext(); ) {
            System.out.println(vIter.next().getShortMessage());
        }
    }
}
Example 87
Project: Hungry-master  File: HungryListFoodsCommand.java View source code
@Override
public boolean onCommand(CommandSender sender, Command command, String cmdLabel, String[] args) {
    if (sender instanceof Player && !Hungry.permissions.hasGuard((Player) sender, "hungry.player.food.list")) {
        return true;
    }
    sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.MSG_FOOD_LIST_START));
    Iterator<Map.Entry<String, Integer>> itFoods = this.plugin.getConfig().foods.entrySet().iterator();
    while (itFoods.hasNext()) {
        Map.Entry<String, Integer> food = itFoods.next();
        sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.VAR_FOOD_LIST_ITEM, food.getKey(), food.getValue().toString()));
    }
    Iterator<Map.Entry<String, Integer>> itBlocks = this.plugin.getConfig().foodBlocks.entrySet().iterator();
    while (itBlocks.hasNext()) {
        Map.Entry<String, Integer> block = itBlocks.next();
        sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.VAR_FOOD_LIST_ITEM, block.getKey(), block.getValue().toString()));
    }
    sender.sendMessage(this.plugin.getConfig().getMessage(HungryMessages.MSG_FOOD_LIST_END));
    return true;
}
Example 88
Project: xbnjava-master  File: RandomNumberTest.java View source code
public static final void main(String[] ignored) {
    Map<Integer, Integer> randCountMap = new TreeMap<Integer, Integer>();
    for (int i = 0; i < tryCount; i++) {
        int rand = getRandomBetweenInclusive(-10, 10);
        int value = ((!randCountMap.containsKey(rand)) ? 1 : randCountMap.get(rand) + 1);
        randCountMap.put(rand, value);
    }
    Iterator<Integer> allIntItr = randCountMap.keySet().iterator();
    List<NumWithCount> numWcountList = new ArrayList<NumWithCount>(randCountMap.size());
    while (allIntItr.hasNext()) {
        Integer I = allIntItr.next();
        int count = randCountMap.get(I);
        NumWithCount nwc = new NumWithCount(I, count);
        numWcountList.add(nwc);
    }
    Iterator<NumWithCount> intWCountItr = numWcountList.iterator();
    while (intWCountItr.hasNext()) {
        NumWithCount numWCount = intWCountItr.next();
        float pct = (float) numWCount.occurances / tryCount * 100;
        System.out.println(numWCount.num + ": " + numWCount.occurances + "   " + String.format("%.3f", pct) + "%");
    }
}
Example 89
Project: GlowstonePlusPlus-master  File: ItemBucket.java View source code
@Override
public void rightClickAir(GlowPlayer player, ItemStack holding) {
    Iterator<Block> itr = new BlockIterator(player, 5);
    Block target = null;
    // Used to determine the side the block was clicked on:
    Block previousTarget = null;
    BlockType targetBlockType = null;
    boolean validTarget = false;
    // Find the next available non-air liquid block type which is collectible in a radius of 5 blocks
    while (itr.hasNext()) {
        previousTarget = target;
        target = itr.next();
        targetBlockType = ItemTable.instance().getBlock(target.getType());
        if (targetBlockType != null && targetBlockType instanceof BlockLiquid) {
            if (((BlockLiquid) targetBlockType).isCollectible((GlowBlockState) target.getState())) {
                validTarget = true;
                break;
            }
        }
    }
    if (target != null && validTarget) {
        // Get the direction of the bucket fill
        BlockFace face;
        if (previousTarget != null) {
            face = target.getFace(previousTarget);
        } else {
            face = BlockFace.SELF;
        }
        Material replaceWith = ((BlockLiquid) targetBlockType).getBucketType();
        PlayerBucketFillEvent event = EventFactory.callEvent(new PlayerBucketFillEvent(player, target, face, holding.getType(), holding));
        if (event.isCancelled()) {
            return;
        }
        if (player.getGameMode() != GameMode.CREATIVE) {
            if (holding.getAmount() == 1) {
                holding.setType(replaceWith);
            } else {
                holding.setAmount(holding.getAmount() - 1);
                player.getInventory().addItem(new ItemStack(replaceWith));
            }
        }
        target.setType(Material.AIR);
    }
}
Example 90
Project: geotools-old-master  File: LRUEvictionPolicy.java View source code
public boolean evict() {
    synchronized (queue) {
        Iterator<NodeIdentifier> it = queue.keySet().iterator();
        while (it.hasNext()) {
            NodeIdentifier node = it.next();
            if (!node.isLocked()) {
                try {
                    node.writeLock();
                    try {
                        tree.evict(node);
                        queue.remove(node);
                    } finally {
                        node.writeUnLock();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return false;
                }
                return true;
            }
        }
    }
    return false;
}
Example 91
Project: cdt-tests-runner-master  File: TestValueStore.java View source code
/**
	 * ValueStore is expected to consist all the IDs from 
	 * FactoryDefaults. Test the same.
	 */
public void testCompareValueStoreWithTemplateDefaluts() {
    TemplateCore[] templates = TemplateEngineTestsHelper.getTestTemplates();
    for (int i = 0; i < templates.length; i++) {
        Map valueStore = templates[i].getValueStore();
        TemplateDescriptor templateDescriptor = templates[i].getTemplateDescriptor();
        Map templateDefaults = templateDescriptor.getTemplateDefaults(templateDescriptor.getRootElement());
        Iterator defaultsIterator = templateDefaults.keySet().iterator();
        while (defaultsIterator.hasNext()) {
            String key = (String) defaultsIterator.next();
            assertNotNull(valueStore.get(key));
        }
    }
}
Example 92
Project: richfaces-master  File: AutocompleteBean.java View source code
public List<String> autocomplete(String prefix) {
    ArrayList<String> result = new ArrayList<String>();
    if ((prefix == null) || (prefix.length() == 0)) {
        for (int i = 0; i < 10; i++) {
            result.add(capitals.get(i).getState());
        }
    } else {
        Iterator<Capital> iterator = capitals.iterator();
        while (iterator.hasNext()) {
            Capital elem = ((Capital) iterator.next());
            if ((elem.getState() != null && elem.getState().toLowerCase().indexOf(prefix.toLowerCase()) == 0) || "".equals(prefix)) {
                result.add(elem.getState());
            }
        }
    }
    return result;
}
Example 93
Project: torodb-master  File: AbstractMetaDocPartIndex.java View source code
protected boolean hasSameColumns(MetaDocPartIndex docPartIndex, Iterator<? extends MetaDocPartIndexColumn> columnsIterator) {
    Iterator<? extends MetaDocPartIndexColumn> docPartIndexColumnsIterator = docPartIndex.iteratorColumns();
    while (columnsIterator.hasNext() && docPartIndexColumnsIterator.hasNext()) {
        MetaDocPartIndexColumn column = columnsIterator.next();
        MetaDocPartIndexColumn docPartIndexColumn = docPartIndexColumnsIterator.next();
        if (!column.getIdentifier().equals(docPartIndexColumn.getIdentifier()) || column.getOrdering() != docPartIndexColumn.getOrdering()) {
            return false;
        }
    }
    return !columnsIterator.hasNext() && !docPartIndexColumnsIterator.hasNext();
}
Example 94
Project: sonar-java-master  File: DiamondOperatorCheck_java_7.java View source code
void foo() {
    List<Object> myList;
    // Compliant
    myList = new ArrayList<>();
    // Noncompliant [[sc=27;ec=35]]
    myList = new ArrayList<Object>();
    // Compliant
    List<String> strings1 = new ArrayList<>();
    // Noncompliant [[sc=42;ec=50]]
    List<String> strings2 = new ArrayList<String>();
    // Compliant
    Map<String, List<Integer>> map1 = new HashMap<>();
    // Noncompliant [[sc=49;ec=71]]
    Map<String, List<Integer>> map2 = new HashMap<String, List<Integer>>();
    // Compliant
    List myOtherList = new ArrayList<Object>();
    // Compliant
    new A().myList1 = new ArrayList<>();
    // Noncompliant [[sc=36;ec=44]]
    new A().myList1 = new ArrayList<Object>();
    List<Object>[] myArrayOfList = new List[10];
    // Compliant
    myArrayOfList[0] = new ArrayList<>();
    // Noncompliant [[sc=37;ec=45]]
    myArrayOfList[1] = new ArrayList<Object>();
    // Compliant
    new ArrayList<Object>().add(new Object());
    // Noncompliant [[sc=34;ec=42]]
    ((List<Object>) new ArrayList<Object>()).isEmpty();
    // Compliant
    ((List<Object>) new ArrayList<>()).isEmpty();
    Iterator<Object> iterator = new // Compliant - anonymous classes requires to be typed
    Iterator<Object>() {
    };
    // Compliant
    MyUnknownVariable = new ArrayList<Object>();
}
Example 95
Project: dcache-master  File: GridftpList.java View source code
/**
     * @param args the command line arguments
     */
public static void main(String[] args) throws Exception {
    if (args == null || args.length < 1 || args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("-help") || args[0].equalsIgnoreCase("--h") || args[0].equalsIgnoreCase("--help")) {
        System.err.println("usage:\n" + "       gridftplist < gridftp directory url> [<server passive (true or false)> \n" + "  example:" + "       gridftplist gsiftp://host1:2811//dir1/dir-to-list ");
        System.exit(1);
        return;
    }
    String directory = args[0];
    boolean serverPassive = true;
    if (args.length > 1) {
        serverPassive = args[1].equalsIgnoreCase("true");
    }
    URI directory_url = new URI(directory);
    if (!directory_url.getScheme().equals("gsiftp") && !directory_url.getScheme().equals("gridftp")) {
        System.err.println("wrong protocol : " + directory_url.getScheme());
        System.exit(1);
        return;
    }
    GridftpClient client = new GridftpClient(directory_url.getHost(), directory_url.getPort(), PortRange.getGlobusTcpPortRange(), null, new String[0], "/etc/grid-security/certificates", CrlCheckingMode.IF_VALID, NamespaceCheckingMode.EUGRIDPMA_GLOBUS, OCSPCheckingMode.IF_AVAILABLE);
    client.setStreamsNum(1);
    System.out.println(client.list(directory_url.getPath(), serverPassive));
    //for(java.util.Iterator i = paths.iterator(); i.hasNext();) {
    //    String next = (String)i.next();
    //    System.out.println(next);
    //}
    client.close();
}
Example 96
Project: jeql-master  File: MappedGroupRowsBuilder.java View source code
public RowList createRows() {
    ArrayRowList memRL = new ArrayRowList(aggSchema);
    int rowSize = memRL.getSchema().size();
    Collection entries = tupleAggMap.entrySet();
    for (Iterator i = entries.iterator(); i.hasNext(); ) {
        Map.Entry entry = (Map.Entry) i.next();
        Tuple key = (Tuple) entry.getKey();
        Aggregator[] agg = (Aggregator[]) entry.getValue();
        BasicRow row = new BasicRow(rowSize);
        int col = 0;
        for (int iKey = 0; iKey < key.size(); iKey++) {
            row.setValue(col++, key.getValue(iKey));
        }
        for (int iAgg = 0; iAgg < agg.length; iAgg++) {
            row.setValue(col++, agg[iAgg].getResult());
        }
        memRL.add(row);
    }
    return memRL;
}
Example 97
Project: xchain-master  File: CompositeUrlTranslationStrategy.java View source code
public URL translateUrl(URL resourceUrl) {
    if (log.isDebugEnabled()) {
        log.debug("Trying " + translatorList.size() + " translators to resolve url '" + resourceUrl.toExternalForm() + "'.");
    }
    URL translatedUrl = null;
    Iterator<UrlTranslationStrategy> translatorIterator = translatorList.iterator();
    while (translatedUrl == null && translatorIterator.hasNext()) {
        if (log.isDebugEnabled()) {
            log.debug("Attemting to translate url.");
        }
        translatedUrl = translatorIterator.next().translateUrl(resourceUrl);
    }
    if (log.isDebugEnabled()) {
        if (translatedUrl != null) {
            log.debug("Translated url '" + resourceUrl.toExternalForm() + "' into '" + translatedUrl.toExternalForm() + "'.");
        } else {
            log.debug("Could not translated url '" + resourceUrl.toExternalForm() + "'.");
        }
    }
    return translatedUrl;
}
Example 98
Project: rsimulator-master  File: JsonHandler.java View source code
private void escape(StringBuilder sb, JsonNode node, String name) {
    if (node.isArray()) {
        sb.append("\\[");
        Iterator<JsonNode> iterator = node.iterator();
        int n = 0;
        while (iterator.hasNext()) {
            if (n > 0) {
                sb.append(",");
            }
            n++;
            escape(sb, iterator.next(), null);
        }
        sb.append("\\]");
    } else if (node.isObject()) {
        sb.append("\\{");
        Iterator<Entry<String, JsonNode>> fields = node.getFields();
        int n = 0;
        while (fields.hasNext()) {
            if (n > 0) {
                sb.append(",");
            }
            n++;
            Entry<String, JsonNode> field = fields.next();
            escape(sb, field.getValue(), field.getKey());
        }
        sb.append("\\}");
    } else {
        sb.append("\"").append(name).append("\":").append(node.toString());
    }
}
Example 99
Project: node-go-better-than-random-master  File: PointListTest.java View source code
public void testIterate() {
    PointList list = new PointList();
    GoPoint p1 = GoPoint.get(1, 1);
    GoPoint p2 = GoPoint.get(2, 2);
    GoPoint p3 = GoPoint.get(2, 3);
    list.add(p1);
    list.add(p2);
    list.add(p3);
    Iterator<GoPoint> it = list.iterator();
    GoPoint p;
    assertTrue(it.hasNext());
    p = it.next();
    assertEquals(p1, p);
    assertTrue(it.hasNext());
    p = it.next();
    assertEquals(p2, p);
    assertTrue(it.hasNext());
    p = it.next();
    assertEquals(p3, p);
    assertFalse(it.hasNext());
}
Example 100
Project: Disco-Build-System-master  File: HandlerExpandItemSubTree.java View source code
/*=====================================================================================*
	 * PUBLIC METHODS
	 *=====================================================================================*/
/**
	 * The user has selected some elements on a TreeViewer, and we should proceed
	 * to expand those elements (although clearly, they'll only be expanded if they
	 * have children, and are not already expanded).
	 * @param event The event information describing the selection. 
	 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    /* 
		 * Determine the details of the selection, as well as which editor the
		 * selected items are part of.
		 */
    TreeSelection selection = (TreeSelection) HandlerUtil.getCurrentSelection(event);
    ISubEditor subEditor = EclipsePartUtils.getActiveSubEditor();
    /* for each selected item, ask the editor to expand it. */
    for (Iterator<?> iter = selection.iterator(); iter.hasNext(); ) {
        Object node = (Object) iter.next();
        subEditor.expandSubtree(node);
    }
    /* for now, return code is always null */
    return null;
}
Example 101
Project: guava-master  File: AbstractBiMapTest.java View source code
public void testIdentityEntrySetIteratorRemove() {
    BiMap<Integer, String> bimap = new AbstractBiMap<Integer, String>(new IdentityHashMap<Integer, String>(), new IdentityHashMap<String, Integer>()) {
    };
    bimap.put(1, "one");
    bimap.put(2, "two");
    bimap.put(3, "three");
    Iterator<Entry<Integer, String>> iterator = bimap.entrySet().iterator();
    iterator.next();
    iterator.next();
    iterator.remove();
    iterator.next();
    iterator.remove();
    assertEquals(1, bimap.size());
    assertEquals(1, bimap.inverse().size());
}