Example usage for java.util TreeMap entrySet

List of usage examples for java.util TreeMap entrySet

Introduction

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

Prototype

EntrySet entrySet

To view the source code for java.util TreeMap entrySet.

Click Source Link

Document

Fields initialized to contain an instance of the entry set view the first time this view is requested.

Usage

From source file:org.apache.hadoop.hbase.stargate.client.RemoteHTable.java

public void put(List<Put> puts) throws IOException {
    // this is a trick: Stargate accepts multiple rows in a cell set and
    // ignores the row specification in the URI

    // separate puts by row
    TreeMap<byte[], List<KeyValue>> map = new TreeMap<byte[], List<KeyValue>>(Bytes.BYTES_COMPARATOR);
    for (Put put : puts) {
        byte[] row = put.getRow();
        List<KeyValue> kvs = map.get(row);
        if (kvs == null) {
            kvs = new ArrayList<KeyValue>();
            map.put(row, kvs);/*from   w w w .  ja  v a2s  .  c om*/
        }
        for (List<KeyValue> l : put.getFamilyMap().values()) {
            kvs.addAll(l);
        }
    }

    // build the cell set
    CellSetModel model = new CellSetModel();
    for (Map.Entry<byte[], List<KeyValue>> e : map.entrySet()) {
        RowModel row = new RowModel(e.getKey());
        for (KeyValue kv : e.getValue()) {
            row.addCell(new CellModel(kv));
        }
        model.addRow(row);
    }

    // build path for multiput
    StringBuilder sb = new StringBuilder();
    sb.append('/');
    if (accessToken != null) {
        sb.append(accessToken);
        sb.append('/');
    }
    sb.append(Bytes.toStringBinary(name));
    sb.append("/$multiput"); // can be any nonexistent row
    for (int i = 0; i < maxRetries; i++) {
        Response response = client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF,
                model.createProtobufOutput());
        int code = response.getCode();
        switch (code) {
        case 200:
            return;
        case 509:
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
            }
            break;
        default:
            throw new IOException("multiput request failed with " + code);
        }
    }
    throw new IOException("multiput request timed out");
}

From source file:com.wattzap.view.graphs.DistributionGraph.java

public void updateValues(int scale, boolean keepZeroes) {
    da.setBucketSize(scale);/*from   w  ww .  j  a va  2  s.  c o m*/
    da.setKeepZeroes(keepZeroes);

    long totalTime = 0;
    TreeMap<Integer, Long> data = new TreeMap<Integer, Long>();
    for (int i = 0; i < telemetry.length; i++) {
        Telemetry last = null;
        for (Telemetry t : telemetry[i]) {

            if (last == null) {
                // first time through
                last = t;
            } else {
                int key = da.getKey(t);
                if (key != -1) {
                    if (data.containsKey(key)) {
                        // add time to current key
                        long time = data.get(key);
                        data.put(key, time + (t.getTime() - last.getTime()));
                    } else {
                        data.put(key, t.getTime() - last.getTime());
                    }
                    totalTime += t.getTime() - last.getTime();

                }
                last = t;
            }
        } // for
    } // for

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (Entry<Integer, Long> entry : data.entrySet()) {
        int key = entry.getKey();
        double p = ((double) entry.getValue() * 100 / totalTime);
        if (p > 0.5) {
            dataset.addValue(p, "", da.getValueLabel(key));
        }

    } // for

    plot.setDataset(dataset);
    chartPanel.revalidate();
}

From source file:com.act.biointerpretation.mechanisminspection.MechanisticValidator.java

private Reaction runEROsOnReaction(Reaction rxn, Long newId) throws IOException {
    projector.clearInchiCache(); // Mew reaction probably doesn't have repeat chemicals, and we don't want a huge cache
    // Apply the EROs and save the results in the reaction object.
    TreeMap<Integer, List<Ero>> scoreToListOfRos;
    try {//from   ww  w  . j a v a2  s. co  m
        /* api.writeToOutKnowledgeGraph doesn't update the id of the written reaction, so we have to pass it as a
         * separate parameter. :(  I would fix the MongoDB behavior, but don't know what that might break!!! */
        scoreToListOfRos = findBestRosThatCorrectlyComputeTheReaction(rxn, newId);
    } catch (IOException e) {
        // Log some information about the culprit when validation fails.
        LOGGER.error("Caught IOException when applying ROs to rxn %d): %s", newId, e.getMessage());
        throw e;
    }

    if (scoreToListOfRos != null && scoreToListOfRos.size() > 0) {
        JSONObject matchingEros = new JSONObject();
        for (Map.Entry<Integer, List<Ero>> entry : scoreToListOfRos.entrySet()) {
            for (Ero e : entry.getValue()) {
                matchingEros.put(e.getId().toString(), entry.getKey().toString());
            }
        }
        rxn.setMechanisticValidatorResult(matchingEros);
        eroHitCounter++;
    }

    return rxn;
}

From source file:com.fdu.jira.plugin.report.timesheet.TimeSheet.java

private Map<String, List<Worklog>> getWorklogMapByUser(List<Worklog> worklogObjects) {
    TreeMap<String, List<Worklog>> presult = new TreeMap<String, List<Worklog>>();
    for (Worklog w : worklogObjects) {
        List<Worklog> worklogs = presult.get(w.getAuthor());
        if (worklogs == null) {
            worklogs = new ArrayList<Worklog>();
            presult.put(w.getAuthor(), worklogs);
        }/*from  www .  ja va2 s . c o  m*/
        worklogs.add(w);
    }
    LinkedHashMap<String, List<Worklog>> result = new LinkedHashMap<String, List<Worklog>>();
    List<Map.Entry<String, List<Worklog>>> keyList = new ArrayList<Map.Entry<String, List<Worklog>>>(
            presult.entrySet());
    final UserManager userManager = ComponentAccessor.getUserManager();
    if (userManager != null)
        Collections.sort(keyList, new Comparator<Map.Entry<String, List<Worklog>>>() {
            public int compare(Map.Entry<String, List<Worklog>> e1, Map.Entry<String, List<Worklog>> e2) {
                User user1 = userManager.getUser(e1.getKey());
                User user2 = userManager.getUser(e2.getKey());
                String userFullName1 = (user1 != null) ? user1.getDisplayName() : e1.getKey();
                String userFullName2 = (user1 != null) ? user2.getDisplayName() : e2.getKey();
                return userFullName1.compareTo(userFullName2);
            }
        });
    for (Map.Entry<String, List<Worklog>> e : keyList) {
        result.put(e.getKey(), e.getValue());
    }
    return result;
}

From source file:org.apache.openmeetings.web.room.wb.WbPanel.java

@Override
void internalWbLoad(StringBuilder sb) {
    Long langId = rp.getClient().getUser().getLanguageId();
    if (!wbm.contains(roomId) && rp.getRoom().getFiles() != null && !rp.getRoom().getFiles().isEmpty()) {
        if (wbm.tryLock(roomId)) {
            try {
                TreeMap<Long, List<BaseFileItem>> files = new TreeMap<>();
                for (RoomFile rf : rp.getRoom().getFiles()) {
                    List<BaseFileItem> bfl = files.get(rf.getWbIdx());
                    if (bfl == null) {
                        files.put(rf.getWbIdx(), new ArrayList<>());
                        bfl = files.get(rf.getWbIdx());
                    }/*from   w w  w .ja  va2 s . co  m*/
                    bfl.add(rf.getFile());
                }
                Whiteboards _wbs = wbm.get(roomId, langId);
                for (Map.Entry<Long, List<BaseFileItem>> e : files.entrySet()) {
                    Whiteboard wb = wbm.add(roomId, langId);
                    _wbs.setActiveWb(wb.getId());
                    for (BaseFileItem fi : e.getValue()) {
                        sendFileToWb(fi, false);
                    }
                }
            } finally {
                wbm.unlock(roomId);
            }
        }
    }
    Whiteboards wbs = wbm.get(roomId, langId);
    loadWhiteboards(sb, rp.getClient(), wbs, wbm.list(roomId));
    JSONObject wbj = getWbJson(wbs.getActiveWb());
    sb.append("WbArea.activateWb(").append(wbj).append(");");
    Whiteboard wb = wbs.get(wbs.getActiveWb());
    if (wb != null) {
        sb.append("WbArea.setSlide(").append(wbj.put(ATTR_SLIDE, wb.getSlide())).append(");");
    }
    sb.append("WbArea.loadVideos();");
}

From source file:org.lockss.servlet.DisplayContentStatus.java

/**
 * Handle a request// w ww. j a va  2s.  co m
 *
 * @throws IOException
 */
public void lockssHandleRequest() throws IOException {
    if (!StringUtil.isNullString(req.getParameter("isDaemonReady"))) {
        if (pluginMgr.areAusStarted()) {
            resp.setStatus(200);
            PrintWriter wrtr = resp.getWriter();
            resp.setContentType("text/plain");
            wrtr.println("true");
        } else {
            PrintWriter wrtr = resp.getWriter();
            resp.setContentType("text/plain");
            wrtr.println("false");
            resp.sendError(202, "Not ready");
        }
        return;
    }

    action = req.getParameter(ACTION_TAG);
    auName = req.getParameter(AU_TO_REMOVE);
    if ("Delete selected".equals(req.getParameter("submit"))) {
        String[] deleteAUs = req.getParameterValues("deleteAu");
        if (deleteAUs != null) {
            log.error("AUs: " + Arrays.asList(deleteAUs));
            doRemoveAus(Arrays.asList(deleteAUs));
        } else {
            log.error("No AUs selected");
            deleteMessage = "No AUs selected!";
        }
    }

    String publisher = req.getParameter("deletePublisher");
    if (!StringUtil.isNullString(publisher)) {
        TreeMap<String, TreeMap<String, TreeSet<ArchivalUnit>>> auMap = DisplayContentTab
                .getAusByPublisherName();
        ArrayList<String> auIds = new ArrayList<String>();
        if (auMap.containsKey(publisher)) {
            Iterator it = auMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry) it.next();
                String publisherString = pairs.getKey().toString();
                log.error("Publisher: " + publisher);
                log.error("Publisher string: " + publisherString);
                if (publisher.equals(publisherString)) {
                    TreeMap<String, TreeSet<ArchivalUnit>> titleMap = (TreeMap<String, TreeSet<ArchivalUnit>>) pairs
                            .getValue();
                    Iterator titleIterator = titleMap.entrySet().iterator();
                    while (titleIterator.hasNext()) {
                        Map.Entry titlePairs = (Map.Entry) titleIterator.next();
                        TreeSet<ArchivalUnit> auSet = (TreeSet<ArchivalUnit>) titlePairs.getValue();
                        for (ArchivalUnit au : auSet) {
                            auIds.add(au.getAuId());
                        }
                    }
                }
            }
            doRemoveAus(auIds);
        }
    }

    if (action != null && auName != null) {
        String auString = URLDecoder.decode(auName, "UTF-8");
        java.util.List<String> auList = new ArrayList<String>();
        auList.add(auString);
        doRemoveAus(auList);
    }

    if (StringUtil.isNullString(action)) {
        try {
            getMultiPartRequest();
            if (multiReq != null) {
                action = multiReq.getString(ACTION_TAG);
            }
        } catch (FormDataTooLongException e) {
            errMsg = "Uploaded file too large: " + e.getMessage();
            // leave action null, will call displayAuSummary() below
        }
    }

    outputFmt = OUTPUT_HTML; // default output is html

    String outputParam = req.getParameter("output");
    if (!StringUtil.isNullString(outputParam)) {
        if ("html".equalsIgnoreCase(outputParam)) {
            outputFmt = OUTPUT_HTML;
        } else if ("xml".equalsIgnoreCase(outputParam)) {
            outputFmt = OUTPUT_XML;
        } else if ("text".equalsIgnoreCase(outputParam)) {
            outputFmt = OUTPUT_TEXT;
        } else if ("csv".equalsIgnoreCase(outputParam)) {
            outputFmt = OUTPUT_CSV;
        } else {
            log.warning("Unknown output format: " + outputParam);
        }
    }
    String optionsParam = req.getParameter("options");

    tableOptions = new BitSet();

    if (isDebugUser()) {
        log.debug2("Debug user.  Setting OPTION_DEBUG_USER");
        tableOptions.set(StatusTable.OPTION_DEBUG_USER);
    }

    for (Iterator iter = StringUtil.breakAt(optionsParam, ',').iterator(); iter.hasNext();) {
        String s = (String) iter.next();
        if ("norows".equalsIgnoreCase(s)) {
            tableOptions.set(StatusTable.OPTION_NO_ROWS);
        }
    }

    tableName = req.getParameter("table");
    tableKey = req.getParameter("key");
    if (StringUtil.isNullString(tableName)) {
        tableName = "AuOverview";
    }
    if (StringUtil.isNullString(tableKey)) {
        tableKey = null;
    }
    sortKey = req.getParameter("sort");
    if (StringUtil.isNullString(sortKey)) {
        sortKey = null;
    }
    groupKey = req.getParameter("group");
    if (StringUtil.isNullString(groupKey)) {
        groupKey = "publisher";
    }
    typeKey = req.getParameter("type");
    filterKey = req.getParameter("filterKey");
    tabKey = req.getParameter("tab");
    timeKey = req.getParameter("timeKey");

    switch (outputFmt) {
    case OUTPUT_HTML:
        doHtmlStatusTable();
        break;
    case OUTPUT_XML:
        try {
            doXmlStatusTable();
        } catch (Exception e) {
            throw new IOException("Error building XML", e);
        }
        break;
    case OUTPUT_TEXT:
        doTextStatusTable();
        break;
    case OUTPUT_CSV:
        doCsvStatusTable();
        break;
    }
}

From source file:com.asakusafw.directio.hive.parquet.DataModelMaterializer.java

private List<Mapping> computeMapping(DataModelDescriptor descriptor, MessageType schema,
        DataModelMapping configuration) {
    List<Mapping> mappings;
    switch (configuration.getFieldMappingStrategy()) {
    case NAME:/*from  w  w w  .ja  va2  s .c o m*/
        mappings = computeMappingByName(descriptor, schema);
        break;
    case POSITION:
        mappings = computeMappingByPosition(descriptor, schema);
        break;
    default:
        throw new AssertionError(configuration.getFieldMappingStrategy());
    }
    TreeMap<Integer, Mapping> propertyMap = new TreeMap<>();
    for (Mapping mapping : mappings) {
        if (checkMapping(descriptor, mapping, configuration)) {
            assert mapping.source != null;
            assert mapping.target != null;
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Map Parquet column: {0}:{1} -> {2}:{3}", //$NON-NLS-1$
                        mapping.source.getPath()[0], mapping.source.getType(), mapping.target.getFieldName(),
                        mapping.target.getTypeInfo()));
            }
            int index = schema.getFieldIndex(mapping.source.getPath()[0]);
            propertyMap.put(index, mapping);
        }
    }
    int lastIndex = -1;
    if (propertyMap.isEmpty() == false) {
        lastIndex = propertyMap.lastKey();
    }
    Mapping[] results = new Mapping[lastIndex + 1];
    for (Map.Entry<Integer, Mapping> entry : propertyMap.entrySet()) {
        results[entry.getKey()] = entry.getValue();
    }
    return Arrays.asList(results);
}

From source file:com.chinamobile.bcbsp.comm.CombinerTool.java

/** combine the message queues.
 * @param outgoingQueue/*from   w  w w . j  av a 2s .c  o  m*/
 */
private ConcurrentLinkedQueue<IMessage> combine(ConcurrentLinkedQueue<IMessage> outgoingQueue) {
    // Map of outgoing queues indexed by destination vertex ID.
    TreeMap<String, ConcurrentLinkedQueue<IMessage>> outgoingQueues = new TreeMap<String, ConcurrentLinkedQueue<IMessage>>();
    ConcurrentLinkedQueue<IMessage> tempQueue = null;
    IMessage tempMessage = null;
    // Traverse the outgoing queue and put the messages with the same
    // dstVertexID into the same queue in the tree map.
    Iterator<IMessage> iter = outgoingQueue.iterator();
    String dstVertexID = null;
    /**The result queue for return.*/
    ConcurrentLinkedQueue<IMessage> resultQueue = new ConcurrentLinkedQueue<IMessage>();
    while (iter.hasNext()) {
        tempMessage = iter.next();
        dstVertexID = tempMessage.getDstVertexID();
        tempQueue = outgoingQueues.get(dstVertexID);
        if (tempQueue == null) {
            tempQueue = new ConcurrentLinkedQueue<IMessage>();
        }
        tempQueue.add(tempMessage);
        outgoingQueues.put(dstVertexID, tempQueue);
    }
    // Do combine operation for each of the outgoing queues.
    for (Entry<String, ConcurrentLinkedQueue<IMessage>> entry : outgoingQueues.entrySet()) {
        tempQueue = entry.getValue();
        tempMessage = (IMessage) this.combiner.combine(tempQueue.iterator());
        resultQueue.add(tempMessage);
    }
    outgoingQueue.clear();
    outgoingQueues.clear();
    return resultQueue;
}

From source file:org.lockss.servlet.DisplayContentTab.java

/**
 * Creates the relevant content for each of the tabs
 *
 * @param divTable The table object to add to
 * @param sortName Name of the publisher or plugin
 * @param auSet    TreeSet of archival units
 * @throws java.io.UnsupportedEncodingException
 *
 *///from  ww  w  .j  av  a2 s  .c o  m
private void createTabContent(Table divTable, String sortName, TreeMap<String, TreeSet<ArchivalUnit>> auSet)
        throws UnsupportedEncodingException {
    if (auSet != null) {
        String cleanNameString = cleanName(sortName);
        createTitleRow(divTable, sortName, auSet.size());
        for (Map.Entry<String, TreeSet<ArchivalUnit>> filteredAu : auSet.entrySet()) {
            createAuRow(divTable, filteredAu, cleanNameString);
        }
        addClearRow(divTable, cleanNameString, false);
    }
}

From source file:org.opendatakit.api.odktables.InstanceFileService.java

@GET
@Path("manifest")
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
public Response getManifest(@Context HttpHeaders httpHeaders,
        @QueryParam(PARAM_AS_ATTACHMENT) String asAttachment)
        throws IOException, ODKTaskLockException, PermissionDeniedException {
    UriBuilder ub = info.getBaseUriBuilder();
    ub.path(OdkTables.class);
    ub.path(OdkTables.class, "getTablesService");
    UriBuilder full = ub.clone().path(TableService.class, "getRealizedTable")
            .path(RealizedTableService.class, "getInstanceFiles")
            .path(InstanceFileService.class, "getManifest");
    URI self = full.build(appId, tableId, schemaETag, rowId);
    String manifestUrl = self.toURL().toExternalForm();

    // retrieve the incoming if-none-match eTag...
    List<String> eTags = httpHeaders.getRequestHeader(HttpHeaders.IF_NONE_MATCH);
    String eTag = (eTags == null || eTags.isEmpty()) ? null : eTags.get(0);
    DbTableInstanceManifestETagEntity eTagEntity = null;
    try {// ww  w  .j  a va  2s . com
        try {
            eTagEntity = DbTableInstanceManifestETags.getRowIdEntry(tableId, rowId, cc);
        } catch (ODKEntityNotFoundException e) {
            // ignore...
        }

        if (eTag != null && eTagEntity != null && eTag.equals(eTagEntity.getManifestETag())) {
            return Response.status(Status.NOT_MODIFIED).header(HttpHeaders.ETAG, eTag)
                    .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true").build();
        }

        InstanceFileManager fm = new InstanceFileManager(appId, cc);

        // get the manifest entries
        final TreeMap<String, FileContentInfo> contents = new TreeMap<String, FileContentInfo>();

        fm.getInstanceAttachments(tableId, rowId, new FileContentHandler() {

            @Override
            public void processFileContent(FileContentInfo content, FetchBlobHandler fetcher) {
                contents.put(content.partialPath, content);

            }
        }, userPermissions);

        // transform to the class used in the REST api
        ArrayList<OdkTablesFileManifestEntry> manifestEntries = new ArrayList<OdkTablesFileManifestEntry>();

        for (Map.Entry<String, FileContentInfo> sfci : contents.entrySet()) {
            // these are in sorted order
            OdkTablesFileManifestEntry entry = new OdkTablesFileManifestEntry();
            entry.filename = sfci.getValue().partialPath;
            entry.contentLength = sfci.getValue().contentLength;
            entry.contentType = sfci.getValue().contentType;
            entry.md5hash = sfci.getValue().contentHash;

            URI getFile = ub.clone().path(TableService.class, "getRealizedTable")
                    .path(RealizedTableService.class, "getInstanceFiles")
                    .path(InstanceFileService.class, "getFile")
                    .build(appId, tableId, schemaETag, rowId, entry.filename);
            String locationUrl = getFile.toURL().toExternalForm();
            entry.downloadUrl = locationUrl;

            manifestEntries.add(entry);
        }
        OdkTablesFileManifest manifest = new OdkTablesFileManifest(manifestEntries);

        String newETag = Integer.toHexString(manifest.hashCode());
        // create a new eTagEntity if there isn't one already...
        if (eTagEntity == null) {
            eTagEntity = DbTableInstanceManifestETags.createNewEntity(tableId, rowId, cc);
            eTagEntity.setManifestETag(newETag);
            eTagEntity.put(cc);
        } else if (!newETag.equals(eTagEntity.getManifestETag())) {
            Log log = LogFactory.getLog(FileManifestService.class);
            log.error("TableInstance (" + tableId + "," + rowId
                    + ") Manifest ETag does not match computed value!");
            eTagEntity.setManifestETag(newETag);
            eTagEntity.put(cc);
        }

        // and whatever the eTag is in that entity is the eTag we should return...
        eTag = eTagEntity.getManifestETag();

        ResponseBuilder rBuild = Response.ok(manifest).header(HttpHeaders.ETAG, eTag)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true");
        if (asAttachment != null && !"".equals(asAttachment)) {
            // Set the filename we're downloading to the disk.
            rBuild.header(WebConsts.CONTENT_DISPOSITION,
                    "attachment; " + "filename=\"" + "manifest.json" + "\"");
        }
        return rBuild.build();
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity("Unable to retrieve manifest of attachments for: " + manifestUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
}