Example usage for java.util TreeMap isEmpty

List of usage examples for java.util TreeMap isEmpty

Introduction

In this page you can find the example usage for java.util TreeMap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.smartitengineering.cms.api.impl.type.FieldDefImpl.java

@Override
public VariationDef getVariationDefForMimeType(String mimeType) {
    TreeMap<String, VariationDef> map = new TreeMap<String, VariationDef>();
    for (VariationDef def : variationDefs) {
        if (def.getMIMEType().equals(mimeType)) {
            map.put(def.getName(), def);
        }//w  w  w .  jav a  2s  . c o m
    }
    if (map.isEmpty()) {
        return null;
    } else {
        return map.firstEntry().getValue();
    }
}

From source file:com.romeikat.datamessie.core.sync.service.template.withIdAndVersion.EntityWithIdAndVersionSynchronizer.java

private boolean createOrUpdateBatch(final TaskExecution taskExecution, final MutableLong firstId)
        throws TaskCancelledException {
    final TaskExecutionWork work = taskExecution.startWork();

    // Load LHS/*from w  w  w. jav a2 s. com*/
    final TreeMap<Long, Long> lhsIdsWithVersion = dao
            .getIdsWithVersion(lhsSessionProvider.getStatelessSession(), firstId.getValue(), batchSizeIds);
    if (lhsIdsWithVersion.isEmpty()) {
        lhsSessionProvider.closeStatelessSession();
        rhsSessionProvider.closeStatelessSession();
        return false;
    }

    // Feedback
    final long lastId = lhsIdsWithVersion.lastKey();
    final String msg = String.format("Processing batch from %s to %s",
            LongConverter.INSTANCE.convertToString(firstId.getValue()),
            LongConverter.INSTANCE.convertToString(lastId));
    taskExecution.reportWorkStart(work, msg);

    // Create or update RHS
    createOrUpdate(lhsIdsWithVersion, lhsSessionProvider.getStatelessSession(),
            rhsSessionProvider.getStatelessSession(), taskExecution);
    firstId.setValue(lastId + 1);

    lhsSessionProvider.closeStatelessSession();
    rhsSessionProvider.closeStatelessSession();
    taskExecution.reportWorkEnd(work);
    taskExecution.checkpoint();
    return true;
}

From source file:com.edmunds.etm.runtime.api.ApplicationSeries.java

/**
 * Removes an application version from this series.
 *
 * @param application the application to remove
 * @return the previous application of the same version, or null if there was no entry for the version
 *///from   w  ww.  j a  v  a2 s.  c  o  m
public ApplicationSeries remove(Application application) {
    final TreeMap<ApplicationVersion, Application> temp = Maps.newTreeMap(applicationsByVersion);

    Application previous = temp.remove(application.getVersion());

    // There is no such thing as an empty series (just return null);
    if (temp.isEmpty()) {
        return null;
    }

    // If previous version didn't exist there is no point making a copy.
    if (previous == null) {
        return this;
    }

    updateActiveVersion(temp);

    return new ApplicationSeries(name, temp);
}

From source file:org.motechproject.mobile.omi.manager.SMSMessageFormatter.java

private String formatCommunityDefaulterMessage(TreeMap<String, TreeMap<String, List<String>>> defaulters) {

    if (defaulters == null || defaulters.isEmpty()) {
        return "\nNo defaulters found for this clinic";
    }//from   ww  w  . j a v a2  s  .  c o m

    String message = "";

    Set<NameValuePair> data = new HashSet<NameValuePair>();

    TreeSet<String> communities = new TreeSet<String>(defaulters.keySet());
    for (String c : communities) {
        TreeMap<String, List<String>> patientDefaulters = defaulters.get(c);
        message += "\n" + c;

        message += formatDefaulterMessage(patientDefaulters);
    }

    return message;
}

From source file:io.openmessaging.rocketmq.consumer.LocalMessageCache.java

private void cleanExpireMsg() {
    for (final Map.Entry<MessageQueue, ProcessQueue> next : rocketmqPullConsumer.getDefaultMQPullConsumerImpl()
            .getRebalanceImpl().getProcessQueueTable().entrySet()) {
        ProcessQueue pq = next.getValue();
        MessageQueue mq = next.getKey();
        ReadWriteLock lockTreeMap = getLockInProcessQueue(pq);
        if (lockTreeMap == null) {
            log.error("Gets tree map lock in process queue error, may be has compatibility issue");
            return;
        }//from ww w  .j  a  v  a 2s.  c  o  m

        TreeMap<Long, MessageExt> msgTreeMap = pq.getMsgTreeMap();

        int loop = msgTreeMap.size();
        for (int i = 0; i < loop; i++) {
            MessageExt msg = null;
            try {
                lockTreeMap.readLock().lockInterruptibly();
                try {
                    if (!msgTreeMap.isEmpty()) {
                        msg = msgTreeMap.firstEntry().getValue();
                        if (System.currentTimeMillis()
                                - Long.parseLong(MessageAccessor.getConsumeStartTimeStamp(msg)) > clientConfig
                                        .getRmqMessageConsumeTimeout() * 60 * 1000) {
                            //Expired, ack and remove it.
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                } finally {
                    lockTreeMap.readLock().unlock();
                }
            } catch (InterruptedException e) {
                log.error("Gets expired message exception", e);
            }

            try {
                rocketmqPullConsumer.sendMessageBack(msg, 3);
                log.info("Send expired msg back. topic={}, msgId={}, storeHost={}, queueId={}, queueOffset={}",
                        msg.getTopic(), msg.getMsgId(), msg.getStoreHost(), msg.getQueueId(),
                        msg.getQueueOffset());
                ack(mq, pq, msg);
            } catch (Exception e) {
                log.error("Send back expired msg exception", e);
            }
        }
    }
}

From source file:org.motechproject.mobile.omi.manager.SMSMessageFormatter.java

private String formatDefaulterMessage(TreeMap<String, List<String>> defaulters) {
    String message = "";

    if (defaulters == null || defaulters.isEmpty()) {
        return "\nNo defaulters found for this clinic";
    }/*from  w  ww .j  a va  2  s.co  m*/

    TreeSet<String> keys = new TreeSet<String>(defaulters.keySet());
    for (String p : keys) {
        List<String> defaultedCareList = defaulters.get(p);

        if (defaultedCareList == null || defaultedCareList.isEmpty()) {
            continue;
        }

        String defaultedCare = StringUtils.join(defaultedCareList.toArray(), ",");

        message += String.format("\n%s (%s)", p, defaultedCare);
    }

    return message;
}

From source file:org.cloudata.core.client.Row.java

/**
 * Return first Cell object in specified column<BR>
 * @param columnName//from ww w.j  a  v  a 2s  .c  o m
 * @return
 */
public Cell getFirst(String columnName) {
    TreeMap<Cell.Key, Cell> cellMap = cells.get(columnName);
    if (cellMap == null || cellMap.isEmpty()) {
        return null;
    }

    return cellMap.firstEntry().getValue();
}

From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java

/**
 * This does the hard work of sorting - called as a shutdown hook.
 * TODO: consider recursion.//from  ww  w . ja va 2 s .  c o  m
 * @param outputName name for the output file.
 * @param files list of MiniSEED files to multiplex.
 * @param cleanup flag indicating whether to cleanup after ourselves or not.
 * @throws IOException
 */
public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty)
        throws IOException {
    ArrayList<File> cleanupFiles = new ArrayList<File>(files);
    ArrayList<File> moreFiles = new ArrayList<File>();

    File outputFile = new File(outputName);
    File tempOutputFile = new File(outputName + ".tmp");

    do {
        // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...?
        if (!moreFiles.isEmpty()) {
            logger.info("more files left to multiplex...");
            FileUtils.deleteQuietly(tempOutputFile);
            FileUtils.moveFile(outputFile, tempOutputFile);

            cleanupFiles.add(tempOutputFile);
            moreFiles.add(tempOutputFile);
            files = moreFiles;
            moreFiles = new ArrayList<File>();
        }

        logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}",
                new Object[] { files.size(), outputName });
        BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile));

        // The hard part, sorting the temp files...
        TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>(
                new MiniSeedTimeOnlyComparator());
        // Prime the TreeMap
        logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files);
        for (File file : files) {
            logger.log(Level.INFO, "Reading first block from {0}", file.toString());
            try {
                FileInputStream fs = FileUtils.openInputStream(file);
                MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty);
                if (ms != null) {
                    blks.put(ms, fs);
                } else {
                    logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString());
                }
            } catch (IOException ex) {
                // Catch "Too many open files" i.e. hitting ulimit, throw anything else.
                if (ex.getMessage().contains("Too many open files")) {
                    logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString());
                    moreFiles.add(file);
                } else
                    throw ex;
            }
        }

        while (!blks.isEmpty()) {
            MiniSeed next = blks.firstKey();
            out.write(next.getBuf(), 0, next.getBlockSize());

            FileInputStream fs = blks.remove(next);
            next = getNextValidMiniSeed(fs, allowEmpty);
            if (next != null) {
                blks.put(next, fs);
            } else {
                fs.close();
            }
        }

        out.close();
    } while (!moreFiles.isEmpty());

    if (cleanup) {
        logger.log(Level.INFO, "Cleaning up...");
        for (File file : cleanupFiles) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java

/**
 * tests using sax to parse an OFX doc.//w w  w  .  j av  a2  s .  c  o  m
 */
public void testSimpleVersion1() throws Exception {
    NanoXMLOFXReader reader = new NanoXMLOFXReader();
    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>();
    TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>();
    aggregateStack.push(root);

    reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack));
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("simple.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());

    TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0);
    assertNotNull(OFX);
    TreeMap<String, List<Object>> SIGNONMSGSRSV1 = (TreeMap<String, List<Object>>) OFX.remove("SIGNONMSGSRSV1")
            .get(0);
    assertNotNull(SIGNONMSGSRSV1);
    TreeMap<String, List<Object>> SONRS = (TreeMap<String, List<Object>>) SIGNONMSGSRSV1.remove("SONRS").get(0);
    assertNotNull(SONRS);
    TreeMap<String, List<Object>> STATUS = (TreeMap<String, List<Object>>) SONRS.remove("STATUS").get(0);
    assertNotNull(STATUS);
    assertEquals("0", STATUS.remove("CODE").get(0).toString().trim());
    assertEquals("INFO", STATUS.remove("SEVERITY").get(0).toString().trim());
    assertTrue(STATUS.isEmpty());
    assertEquals("20071015021529.000[-8:PST]", SONRS.remove("DTSERVER").get(0).toString().trim());
    assertEquals("ENG", SONRS.remove("LANGUAGE").get(0).toString().trim());
    assertEquals("19900101000000", SONRS.remove("DTACCTUP").get(0).toString().trim());
    assertTrue(SONRS.isEmpty());
    assertTrue(SIGNONMSGSRSV1.isEmpty());
    assertTrue(OFX.isEmpty());
    assertTrue(root.isEmpty());
}

From source file:ws.project.languagebasedlexiconanalisys.LexiconProcessor.java

public void writeTimeSeries(TreeMap<String, HashSet<String>> terms, String[] u)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    PrintWriter writer = new PrintWriter(new File("time_series.csv"), "UTF-8");

    writer.write("term;");
    for (String d : u) {
        writer.write(d + ";");
    }//  w  ww.j av  a  2  s. com
    writer.write("\n");

    for (int i = 0; i < 100 || terms.isEmpty(); i++) {
        Entry<String, HashSet<String>> e = terms.pollFirstEntry();
        writer.write(e.getKey() + ";");
        for (String d : u) {
            if (e.getValue().contains(d)) {
                indexer.openReader((String) d);
                writer.write(indexer.getReader().docFreq(new Term("tweet", e.getKey())) + ";");
                indexer.closeReader();
            } else
                writer.write("0;");
        }
        writer.write("\n");
    }

    writer.close();
}