Example usage for java.util Iterator remove

List of usage examples for java.util Iterator remove

Introduction

In this page you can find the example usage for java.util Iterator remove.

Prototype

default void remove() 

Source Link

Document

Removes from the underlying collection the last element returned by this iterator (optional operation).

Usage

From source file:de.micromata.genome.gwiki.plugin.vfolder_1_0.GWikiVFolderUtils.java

/**
 * //  w ww. j  a v a 2  s . c om
 * @param wikiContext
 * @param vfolderElement vfolder element
 * @param node
 * @param cache
 * @param increment
 * @return
 */
public static boolean updateFolders(GWikiContext wikiContext, GWikiElement vfolderElement,
        GWikiVFolderNode node, GWikiVFolderCachedFileInfos cache, boolean increment) {
    Map<String, FsObject> newFiles = new TreeMap<String, FsObject>();
    Map<String, FsObject> allFiles = new HashMap<String, FsObject>();
    List<FsObject> files = node.getFileSystem().listFilesByPattern("", node.getMatcherRule(), null, true);
    for (FsObject file : files) {
        String name = file.getName();
        if (name.startsWith("/") == true) {
            name = name.substring(1);
        }

        allFiles.put(name, file);
        // System.out.println(name);
        GWikiElementInfo ei = cache.getElementInfoByLocalName(name);
        if (increment == false || ei == null) {
            newFiles.put(name, file);
            continue;
        }
        Date d = file.getModifiedAt();
        if (ObjectUtils.equals(d, ei.getModifiedAt()) == false) {
            newFiles.put(name, file);
        }
    }
    boolean deletedSome = false;
    Iterator<String> it = cache.getLocalNames().iterator();
    for (; it.hasNext();) {
        // for (String ts : cache.getLocalNames()) {
        String ts = it.next();
        if (allFiles.containsKey(ts) == false) {
            deletedSome = true;
            it.remove();
            // TODO next
            // wikiContext.getWikiWeb().getDaoContext().getPageCache().removePageInfo(pageId)
        }
    }
    for (Map.Entry<String, FsObject> me : newFiles.entrySet()) {
        GWikiElementInfo ei = createElementInfo(wikiContext, me.getKey(), vfolderElement, node, me.getValue());
        cache.addElement(me.getKey(), ei);
    }
    return newFiles.isEmpty() == false || deletedSome == true;
}

From source file:com.krawler.database.DbPool.java

/**
 * return a connection to use for the Krawler database.
 * /*from   w  w w .  j a  v  a2 s . co  m*/
 * @param
 * @return
 * @throws ServiceException
 */
public static Connection getConnection() throws ServiceException {
    java.sql.Connection conn = null;

    long start = KrawlerPerf.STOPWATCH_DB_CONN.start();

    try {
        conn = sPoolingDataSource.getConnection();

        if (conn.getAutoCommit() != false)
            conn.setAutoCommit(false);

        // We want READ COMMITTED transaction isolation level for duplicate
        // handling code in BucketBlobStore.newBlobInfo().
        conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
    } catch (SQLException e) {
        throw ServiceException.FAILURE("getting database connection", e);
    }

    // If the connection pool is overutilized, warn about potential leaks
    int numActive = sConnectionPool.getNumActive();
    int maxActive = sConnectionPool.getMaxActive();

    if (numActive > maxActive * 0.75) {
        String stackTraceMsg = "Turn on debug logging for KrawlerLog.dbconn to see stack "
                + "traces of connections not returned to the pool.";
        if (KrawlerLog.dbconn.isDebugEnabled()) {
            StringBuffer buf = new StringBuffer();
            synchronized (sConnectionStackCounter) {
                Iterator i = sConnectionStackCounter.iterator();
                while (i.hasNext()) {
                    String stackTrace = (String) i.next();
                    int count = sConnectionStackCounter.getCount(stackTrace);
                    if (count == 0) {
                        i.remove();
                    } else {
                        buf.append(count + " connections allocated at " + stackTrace + "\n");
                    }
                }
            }
            stackTraceMsg = buf.toString();
        }
        KrawlerLog.dbconn.warn("Connection pool is 75% utilized.  " + numActive
                + " connections out of a maximum of " + maxActive + " in use.  " + stackTraceMsg);
    }

    if (KrawlerLog.sqltrace.isDebugEnabled() || KrawlerLog.perf.isDebugEnabled()) {
        // conn = new DebugConnection(conn); //TODO: uncomment later[BS]
    }
    Connection krawlerCon = new Connection(conn);

    // If we're debugging, update the counter with the current stack trace
    if (KrawlerLog.dbconn.isDebugEnabled()) {
        Throwable t = new Throwable();
        krawlerCon.setStackTrace(t);

        String stackTrace = SystemUtil.getStackTrace(t);
        synchronized (sConnectionStackCounter) {
            sConnectionStackCounter.increment(stackTrace);
        }
    }

    KrawlerPerf.STOPWATCH_DB_CONN.stop(start);
    return krawlerCon;
}

From source file:net.yacy.search.query.QueryGoal.java

private static void parseQuery(String s, Collection<String> include_string, Collection<String> exclude_string) {
    while (s.length() > 0) {
        // parse query
        int p = 0;
        while (p < s.length() && s.charAt(p) == space)
            p++;/*  w ww  .j  a  v a  2  s  .  c o m*/
        s = s.substring(p);
        if (s.length() == 0)
            return;

        // parse phrase
        boolean inc = true;
        if (s.charAt(0) == '-') {
            inc = false;
            s = s.substring(1);
        } else if (s.charAt(0) == '+') {
            inc = true;
            s = s.substring(1);
        }
        if (s.length() == 0)
            return;

        // parse string
        char stop = space;
        if (s.charAt(0) == dq) {
            stop = s.charAt(0);
            s = s.substring(1);
        } else if (s.charAt(0) == sq) {
            stop = s.charAt(0);
            s = s.substring(1);
        }
        p = 0;
        while (p < s.length() && s.charAt(p) != stop)
            p++;
        String string = s.substring(0, p);
        p++; // go behind the stop character (eats up space, sq and dq)
        s = p < s.length() ? s.substring(p) : "";
        if (string.length() > 0) {
            if (inc) {
                if (!include_string.contains(string))
                    include_string.add(string);
            } else {
                if (!exclude_string.contains(string))
                    exclude_string.add(string);
            }
        }
    }
    // in case that the include_string contains several entries including 1-char tokens and also more-than-1-char tokens,
    // then remove the 1-char tokens to prevent that we are to strict. This will make it possible to be a bit more fuzzy
    // in the search where it is appropriate
    boolean contains_single = false, contains_multiple = false;
    for (String token : include_string) {
        if (token.length() == 1)
            contains_single = true;
        else
            contains_multiple = true;
    }
    if (contains_single && contains_multiple) {
        Iterator<String> i = include_string.iterator();
        while (i.hasNext())
            if (i.next().length() == 1)
                i.remove();
    }
}

From source file:com.alkacon.opencms.newsletter.CmsNewsletterManager.java

/**
 * Returns the organizational units that can contain mailing lists to display.<p>
 * // w w  w  .j  a  va 2  s. co  m
 * @param cms the current cms context
 * 
 * @return the organizational units
 * 
 * @throws CmsException if something goes wrong
 */
public static List<CmsOrganizationalUnit> getOrgUnits(CmsObject cms) throws CmsException {

    List<CmsOrganizationalUnit> ous = OpenCms.getRoleManager().getOrgUnitsForRole(cms,
            CmsRole.ACCOUNT_MANAGER.forOrgUnit(""), true);
    Iterator<CmsOrganizationalUnit> it = ous.iterator();
    while (it.hasNext()) {
        CmsOrganizationalUnit ou = it.next();
        if (!ou.getSimpleName().startsWith(NEWSLETTER_OU_NAMEPREFIX)) {
            it.remove();
        }
    }
    return ous;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.annotator.OnlyFilesMatchingPredictionsReader.java

/**
 * Finds the labeled sequence given exact match with tokens in the jcas.
 *
 * @param jCas  jcas/*from   www  .ja va 2s .  c o  m*/
 * @param cache cache
 * @return sequence sequence
 * @throws java.util.NoSuchElementException if no such sequence exists
 */
public static Sequence findSequence(JCas jCas, Map<String, List<Sequence>> cache)
        throws NoSuchElementException {
    List<Token> tokens = JCasUtil2.selectTokensAsList(jCas);
    String firstToken = tokens.get(0).getCoveredText();

    //        Sequence result = null;
    if (firstToken == null) {
        //            throw new IllegalStateException("First token is null");
        return null;
    }

    List<Sequence> candidateSequence = cache.get(firstToken);

    if (candidateSequence == null) {
        //            throw new IllegalStateException(
        //                    "Cannot find sentence starting with token " + firstToken);
        return null;
    }

    List<Sequence> resultCandidates = new ArrayList<>(candidateSequence);
    int tokenIndex = 1;

    //        while (resultCandidates.size() > 1) {
    while (tokenIndex < tokens.size() && resultCandidates.size() > 0) {
        String jCasToken = tokens.get(tokenIndex).getCoveredText();

        // iterate over all candidates
        Iterator<Sequence> iterator = resultCandidates.iterator();
        while (iterator.hasNext()) {
            Sequence sequence = iterator.next();

            String token = null;

            if (tokenIndex < sequence.getTokens().size()) {
                TokenEntry tokenEntry = sequence.getTokens().get(tokenIndex);
                token = tokenEntry.getToken();
            }

            if (token == null || !token.equals(jCasToken)) {
                iterator.remove();
            }
        }

        tokenIndex++;
    }

    if (resultCandidates.isEmpty()) {
        return null;
    }

    Sequence result = resultCandidates.get(0);

    if (result.getTokens().size() != tokens.size()) {
        System.err.println(result);
        System.err.println(jCas.getDocumentText().substring(tokens.get(0).getBegin(),
                tokens.get(tokens.size() - 1).getEnd()));
        throw new IllegalStateException("Number of tokens in sentence (" + tokens.size()
                + ") differs from number of tokens in sequence (" + result.getTokens().size() + ")");
    }

    return result;
}

From source file:com.wolvereness.overmapped.lib.WellOrdered.java

public static <T, C extends List<? super T>> C process(final C out, final Iterable<? extends T> in,
        final Informer<T> informer) throws WellOrderedException {
    Validate.notNull(out, "Collection out cannot be null");
    Validate.notNull(in, "Token in cannot be null");
    Validate.notNull(informer, "Informer cannot be null");

    final Map<T, Collection<T>> preceding = newHashMap();
    final Map<T, Collection<T>> required = newHashMap();
    final Set<T> pending = newLinkedHashSet(in);

    { // Preprocessing of information from specified informer
        final List<T> buffer = newArrayList();
        for (final T token : pending) {

            // Preferred preceding elements
            informer.addPrecedingPreferencesTo(token, buffer);
            addToAsLinkedList(token, preceding, buffer);
            buffer.clear();//from www  . j  a  v a 2  s.  co m

            // Required preceding elements
            informer.addPrecedingTo(token, buffer);
            if (!pending.containsAll(buffer))
                throw new UnmetPrecedingTokenException(token + " cannot be proceded by one of " + buffer
                        + " with only " + pending + " available");
            addToAsLinkedList(token, required, buffer);
            buffer.clear();

            // Preferred proceeding elements
            informer.addProceedingPreferencesTo(token, buffer);
            addToAllLinkedLists(buffer, preceding, token);
            buffer.clear();
        }
    }

    int size = pending.size();
    while (size != 0) {

        { // Start normal processing
            final Iterator<T> tokenIterator = pending.iterator();
            while (tokenIterator.hasNext()) {
                final T token = tokenIterator.next();
                if (
                // Use preceding as primary/first check;
                // required is covered by the fall-back
                handleTokens(token, preceding, pending) && handleTokens(token, required, pending)) {
                    tokenIterator.remove();
                    out.add(token);
                }
            }
        }

        if (size == (size = pending.size())) {
            // Fall-back situation when we can't find a token that's ready
            final Iterator<T> tokenIterator = pending.iterator();
            while (tokenIterator.hasNext()) {
                final T token = tokenIterator.next();
                // At this point, we ignore preferences
                if (handleTokens(token, required, pending)) {
                    tokenIterator.remove();
                    preceding.remove(token);
                    out.add(token);
                    break;
                }
            }

            if (size == (size = pending.size())) {
                // We made no progress; it's circular
                break;
            }
        }
    }

    if (size != 0)
        throw new CircularOrderException("Failed to resolve circular preceding requirements in " + required);

    return out;
}

From source file:com.nec.harvest.bean.mapping.PurchaseBean.java

/**
 * Filter a collection by type (any type)
 * //from w  w  w.  j a  v a 2  s . c  o m
 * @param collection
 * @param filter
 * @return
 */
public static List<PurchaseBean> filter(Collection<PurchaseBean> collection, FilterType filterType,
        String filter) {
    if (CollectionUtils.isEmpty(collection)) {
        return (List<PurchaseBean>) collection;
    }

    if (StringUtils.isEmpty(filter)) {
        return (List<PurchaseBean>) collection;
    }

    Iterator<PurchaseBean> itr = collection.iterator();
    while (itr.hasNext()) {
        PurchaseBean obj = itr.next();
        String filterTypeValue = null;
        if (filterType.getValue() == 1) {
            filterTypeValue = obj.getCtgCode();
        } else if (filterType.getValue() == 2) {
            filterTypeValue = obj.getSrsCode();
        } else if (filterType.getValue() == 3) {
            filterTypeValue = obj.getWakuNum();
        }

        if (!filter.equals(filterTypeValue)) {
            itr.remove();
        }
    }
    return (List<PurchaseBean>) collection;
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * Delete the file now -- but in the event of failure, keep trying
 * in the future. //from  www  . j a v  a  2 s  .c o m
 * 
 * VERY IMPORTANT: Do not use with any file whose name/path may be 
 * reused, because the lagged delete could then wind up deleting the
 * newer file. Essentially, only to be used with uniquely-named temp
 * files. 
 * 
 * Necessary because some platforms (looking at you, 
 * JVM-on-Windows) will have deletes fail because of things like 
 * file-mapped buffers remaining, and there's no explicit way to 
 * unmap a buffer. (See 6-year-old Sun-stumping Java bug
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 )
 * We just have to wait and retry. 
 * 
 * (Why not just File.deleteOnExit? There could be an arbitrary, 
 * unbounded number of files in such a situation, that are only 
 * deletable a few seconds or minutes after our first attempt.
 * Waiting for JVM exist could mean disk exhaustion. It's also
 * unclear if the native FS class implementations of deleteOnExit
 * use RAM per pending file.)
 * 
 * @param fileToDelete
 */
public static synchronized void deleteSoonerOrLater(File fileToDelete) {
    pendingDeletes.add(fileToDelete);
    // if things are getting out of hand, force gc/finalization
    if (pendingDeletes.size() > 50) {
        LOGGER.warning(">50 pending Files to delete; forcing gc/finalization");
        System.gc();
        System.runFinalization();
    }
    // try all pendingDeletes
    Iterator<File> iter = pendingDeletes.listIterator();
    while (iter.hasNext()) {
        File pending = iter.next();
        if (pending.delete()) {
            iter.remove();
        }
    }
    // if things are still out of hand, complain loudly
    if (pendingDeletes.size() > 50) {
        LOGGER.severe(">50 pending Files to delete even after gc/finalization");
    }
}

From source file:com.evolveum.midpoint.web.util.ExpressionUtil.java

public static void removeEvaluatorByName(ExpressionType expression, QName elementName) {
    if (isEmpty(expression) || elementName == null) {
        return;//from  www .j  a v  a2  s . c om
    }
    Iterator<JAXBElement<?>> it = expression.getExpressionEvaluator().iterator();
    while (it.hasNext()) {
        JAXBElement<?> element = it.next();
        if (element != null && element.getName().equals(elementName)) {
            it.remove();
        }
    }
}

From source file:com.joseflavio.unhadegato.Concentrador.java

/**
 * {@link CopaibaGerenciador#iniciar() Iniciar}, {@link CopaibaGerenciador#atualizar(String, int, boolean, boolean, String, String, int) atualizar}
 * e/ou {@link CopaibaGerenciador#encerrar() encerrar} {@link CopaibaGerenciador}'s.
 * @param arquivo Arquivo de configurao de {@link CopaibaConexao}'s.
 *//*from   w  ww  . j  a va2s  . c om*/
private static void executarCopaibas(File arquivo) {

    try {

        if (!arquivo.exists()) {
            try (InputStream is = Concentrador.class.getResourceAsStream("/copaibas.conf");
                    OutputStream os = new FileOutputStream(arquivo);) {
                IOUtils.copy(is, os);
            }
        }

        Properties props = new Properties();

        try (FileInputStream fis = new FileInputStream(arquivo)) {
            props.load(fis);
        }

        for (Object chave : props.keySet()) {

            try {

                String nome = chave.toString();

                String[] p = props.getProperty(nome).split("\",\"");

                String endereco = p[0].substring(1);
                int porta = Integer.parseInt(p[1]);
                boolean segura = p[2].equals("TLS") || p[2].equals("SSL");
                boolean ignorarCert = p[3].equals("S");
                String usuario = p[4];
                String senha = p.length >= 7 ? p[5] : p[5].substring(0, p[5].length() - 1);
                int conexoes = p.length >= 7 ? Integer.parseInt(p[6].substring(0, p[6].length() - 1)) : 5;

                CopaibaGerenciador gerenciador = gerenciadores.get(nome);

                if (gerenciador == null) {
                    log.info(Util.getMensagem("copaiba.iniciando", nome));
                    gerenciador = new CopaibaGerenciador(nome, endereco, porta, segura, ignorarCert, usuario,
                            senha, conexoes);
                    gerenciadores.put(nome, gerenciador);
                    gerenciador.iniciar();
                    log.info(Util.getMensagem("copaiba.iniciada", nome));
                } else {
                    log.info(Util.getMensagem("copaiba.verificando", nome));
                    if (gerenciador.atualizar(endereco, porta, segura, ignorarCert, usuario, senha, conexoes)) {
                        log.info(Util.getMensagem("copaiba.atualizada", nome));
                    } else {
                        log.info(Util.getMensagem("copaiba.inalterada", nome));
                    }
                }

                try (CopaibaConexao cc = new CopaibaConexao(endereco, porta, segura, ignorarCert, usuario,
                        senha)) {
                    cc.verificar();
                    log.info(Util.getMensagem("copaiba.conexao.teste.exito", nome));
                } catch (Exception e) {
                    log.info(Util.getMensagem("copaiba.conexao.teste.erro", nome, e.getMessage()));
                    log.error(e.getMessage(), e);
                }

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        }

        Iterator<CopaibaGerenciador> it = gerenciadores.values().iterator();
        while (it.hasNext()) {
            CopaibaGerenciador gerenciador = it.next();
            String nome = gerenciador.getNome();
            if (!props.containsKey(nome)) {
                try {
                    log.info(Util.getMensagem("copaiba.encerrando", nome));
                    it.remove();
                    gerenciador.encerrar();
                    log.info(Util.getMensagem("copaiba.encerrada", nome));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}