Example usage for java.util TreeMap get

List of usage examples for java.util TreeMap get

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.mmounirou.spotirss.spotify.tracks.SpotifyHrefQuery.java

private XTracks findBestMatchingTrack(List<XTracks> xtracks, final Track track) {
    if (xtracks.size() == 1) {
        return xtracks.get(0);
    }/*from   w  w w.  j a  v  a 2  s  . c  o m*/

    TreeMap<Integer, XTracks> sortedTrack = Maps.newTreeMap();
    for (XTracks xTrack : xtracks) {
        sortedTrack.put(getLevenshteinDistance(xTrack, track), xTrack);
    }

    Integer minDistance = Iterables.get(sortedTrack.keySet(), 0);
    XTracks choosedTrack = sortedTrack.get(minDistance);

    if (minDistance > 1) {
        SpotiRss.LOGGER.info(String.format("(%s:%s) choosed for (%s:%s) with distance %d",
                choosedTrack.getOriginalTrackName(), Joiner.on(",").join(choosedTrack.getAllArtists()),
                track.getSong(), Joiner.on(",").join(track.getArtists()), minDistance));
    } else {
        SpotiRss.LOGGER.debug(String.format("(%s:%s) choosed for (%s:%s) with distance %d",
                choosedTrack.getOriginalTrackName(), Joiner.on(",").join(choosedTrack.getAllArtists()),
                track.getSong(), Joiner.on(",").join(track.getArtists()), minDistance));
    }

    return choosedTrack;
}

From source file:gda.jython.commands.ScannableCommands.java

/**
 * The pos command. Reports the current position of a scannable or moves one or more scannables concurrently.
 * /*from w w  w .  j  a  v  a2s. c  o m*/
 * @param args
 * @return String reporting final positions
 * @throws Exception
 *             - any exception within this method
 */
public static String pos(Object... args) throws Exception {
    if (args.length == 1) {
        if (args[0] == null) {// example: pos None, Jython command: pos([None])
            throw new Exception(
                    "Usage: pos [ScannableName] - returns the position of all Scannables [or the given scannable]");
        } else if (args[0] instanceof IScannableGroup) {
            return ScannableUtils.prettyPrintScannableGroup((IScannableGroup) args[0]);
        } else if (args[0] instanceof ScannableBase) {// example: pos pseudoDeviceName, Jython command:
            // pos([pseudoDeviceName])
            return ((ScannableBase) args[0]).__str__().toString();
        }
        return args[0].toString();
    } else if (args.length >= 2) {// example pos pseudoDeviceName newPosition, Jython command:
        // pos([pseudoDeviceName, newPosition]
        // identify scannables and the positions to move them to
        Scannable[] scannableList = new Scannable[args.length / 2];
        HashMap<Scannable, Object> positionMap = new HashMap<Scannable, Object>();
        int j = 0;
        for (int i = 0; i < args.length; i += 2) {
            if (args[i] instanceof Scannable) {
                scannableList[j] = (Scannable) args[i];
                positionMap.put((Scannable) args[i], args[i + 1]);
                j++;
            }
        }

        // Check positions valid
        for (Scannable scannable : scannableList) {
            Object target = positionMap.get(scannable);
            if (!(scannable instanceof Detector)) {
                raiseDeviceExceptionIfPositionNotValid(scannable, target);
            }
        }

        try {
            // Group by level
            TreeMap<Integer, List<Scannable>> scannablesByLevel = new TreeMap<Integer, List<Scannable>>();
            for (Scannable scn : scannableList) {
                Integer level = scn.getLevel();
                if (!scannablesByLevel.containsKey(level)) {
                    scannablesByLevel.put(level, new ArrayList<Scannable>());
                }
                scannablesByLevel.get(level).add(scn);
            }

            // Move scannables of the same level concurrently
            String output = "Move completed: "; // KLUDGE

            for (Entry<Integer, List<Scannable>> currentLevelScannables : scannablesByLevel.entrySet()) {
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelStart();
                }
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelMoveStart();
                }
                // asynchronousMoveTo()
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    if (scn1 instanceof DetectorSnapper) {
                        Double collectionTime = PositionConvertorFunctions.toDouble(positionMap.get(scn1));
                        ((DetectorSnapper) scn1).prepareForAcquisition(collectionTime);
                        ((DetectorSnapper) scn1).acquire();
                    } else if (scn1 instanceof Detector) {
                        Double collectionTime = PositionConvertorFunctions.toDouble(positionMap.get(scn1));
                        ((Detector) scn1).setCollectionTime(collectionTime);
                        ((Detector) scn1).prepareForCollection();
                        ((Detector) scn1).collectData();
                    } else {
                        scn1.asynchronousMoveTo(positionMap.get(scn1));
                    }
                }
                // **isBusy()**
                // Wait for all moves to complete. If there is a problem with one, then stop the Scannables
                // which may still be moving (those that have not yet been waited for), and _then_ throw the
                // exception.
                Exception exceptionCaughtWhileWaitingOnIsBusy = null;
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    if (exceptionCaughtWhileWaitingOnIsBusy == null) {
                        // normal behaviour
                        try {
                            scn1.waitWhileBusy();
                        } catch (Exception e) {
                            logger.error("Exception occured while waiting for " + scn1.getName()
                                    + " to complete move: ", e.getMessage());
                            // cause future passes through the loop to stop Scannables
                            exceptionCaughtWhileWaitingOnIsBusy = e;
                        }
                    } else {
                        // stop any motors that may be still moving
                        try {
                            logger.info("Stopping " + scn1.getName()
                                    + " due to problem moving previous scannable.");
                            scn1.stop();
                        } catch (DeviceException e) {
                            logger.error("Caught exception while stopping " + scn1.getName() + ": "
                                    + e.getMessage());
                        }
                    }
                }
                if (exceptionCaughtWhileWaitingOnIsBusy != null) {
                    throw exceptionCaughtWhileWaitingOnIsBusy;
                }
                for (Scannable scn1 : currentLevelScannables.getValue()) {
                    scn1.atLevelEnd();
                }
            }

            if (scannableList.length > 1) {
                output += "\n";
            }

            // return position
            for (Scannable scn3 : scannableList) {
                output += ScannableUtils.getFormattedCurrentPosition(scn3) + "\n";
            }
            return output.trim();
        } catch (Exception e) {
            // Call the atCommandFailure() hooks
            for (Scannable scn : scannableList) {
                scn.atCommandFailure();
            }
            throw e;
        }
    }
    return "";
}

From source file:com.sfs.whichdoctor.formatter.PersonFormatter.java

/**
 * Calculate training summary total.// w  w w  .  j a va2 s.com
 *
 * @param summary the summary
 * @param inMonths the in months flag
 * @return the string
 */
private static String calculateTrainingSummaryTotal(final TreeMap<String, AccreditationBean[]> summary,
        final boolean inMonths) {
    StringBuffer value = new StringBuffer();

    int coreTotal = 0;
    int nonCoreTotal = 0;

    if (summary != null) {
        for (String key : summary.keySet()) {
            try {
                AccreditationBean[] details = summary.get(key);

                AccreditationBean core = details[0];
                AccreditationBean nonCore = details[1];

                coreTotal += core.getWeeksCertified();
                nonCoreTotal += nonCore.getWeeksCertified();
            } finally {
            }
        }
    }

    if (inMonths) {
        coreTotal = Formatter.getWholeMonths(coreTotal);
        nonCoreTotal = Formatter.getWholeMonths(nonCoreTotal);
    }

    value.append(coreTotal);
    value.append(" (");
    value.append(nonCoreTotal);
    value.append(")");

    return value.toString();
}

From source file:org.apache.hadoop.hbase.TestSplit.java

private void assertScan(final HRegion r, final String column, final Text firstValue) throws IOException {
    Text[] cols = new Text[] { new Text(column) };
    HInternalScannerInterface s = r.getScanner(cols, HConstants.EMPTY_START_ROW, System.currentTimeMillis(),
            null);//w  ww.j  a v  a  2 s. c o m
    try {
        HStoreKey curKey = new HStoreKey();
        TreeMap<Text, byte[]> curVals = new TreeMap<Text, byte[]>();
        boolean first = true;
        OUTER_LOOP: while (s.next(curKey, curVals)) {
            for (Text col : curVals.keySet()) {
                byte[] val = curVals.get(col);
                Text curval = new Text(val);
                if (first) {
                    first = false;
                    assertTrue(curval.compareTo(firstValue) == 0);
                } else {
                    // Not asserting anything.  Might as well break.
                    break OUTER_LOOP;
                }
            }
        }
    } finally {
        s.close();
    }
}

From source file:org.apache.accumulo.server.problems.ProblemReports.java

public Map<String, Map<ProblemType, Integer>> summarize() {

    TreeMap<String, Map<ProblemType, Integer>> summary = new TreeMap<String, Map<ProblemType, Integer>>();

    for (ProblemReport pr : this) {
        Map<ProblemType, Integer> tableProblems = summary.get(pr.getTableName());
        if (tableProblems == null) {
            tableProblems = new EnumMap<ProblemType, Integer>(ProblemType.class);
            summary.put(pr.getTableName(), tableProblems);
        }//from   ww w .  ja v a  2  s  .  com

        Integer count = tableProblems.get(pr.getProblemType());
        if (count == null) {
            count = 0;
        }

        tableProblems.put(pr.getProblemType(), count + 1);
    }

    return summary;
}

From source file:com.hortonworks.releng.hdpbuildredirect.Resource.java

@Path("/{platform}/{series}/{type}/{version}/{file}")
@GET//from  w w  w . ja v  a  2 s  .c  o  m
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
public Response getRedirect(@PathParam("platform") @DefaultValue("centos6") String platform,
        @PathParam("series") @DefaultValue("x.x") String series,
        @PathParam("type") @DefaultValue("BUILDS") String type,
        @PathParam("version") @DefaultValue("x.x") String version,
        @PathParam("file") @DefaultValue("hdpbn.repo") String file) throws URISyntaxException {
    Response response;
    Map<String, TreeMap<Version, String>> repoInfo = getCachedRepoInfo();
    Version reqVer = new Version(version);
    TreeMap<Version, String> verToUriMap = getVerToUriMap(repoInfo, platform);
    response = Response.status(Response.Status.NOT_FOUND).build();
    for (Version repoVer : verToUriMap.descendingKeySet()) {
        if (Version.match(repoVer, reqVer)) {
            response = Response.temporaryRedirect(new URI(verToUriMap.get(repoVer) + getRepoFileName(platform)))
                    .build();
            break;
        }
    }
    return response;
}

From source file:org.waarp.gateway.kernel.rest.RestArgument.java

/**
 * @param hmacSha256//from  w  ww.j  a v a2s  .co  m
 *            SHA-256 key to create the signature
 * @param extraKey
 *            might be null
 * @param treeMap
 * @param argPath
 * @throws HttpInvalidAuthenticationException
 */
protected static String computeKey(HmacSha256 hmacSha256, String extraKey, TreeMap<String, String> treeMap,
        String argPath) throws HttpInvalidAuthenticationException {
    Set<String> keys = treeMap.keySet();
    StringBuilder builder = new StringBuilder(argPath);
    if (!keys.isEmpty() || extraKey != null) {
        builder.append('?');
    }
    boolean first = true;
    for (String keylower : keys) {
        if (first) {
            first = false;
        } else {
            builder.append('&');
        }
        builder.append(keylower).append('=').append(treeMap.get(keylower));
    }
    if (extraKey != null) {
        if (!keys.isEmpty()) {
            builder.append("&");
        }
        builder.append(REST_ROOT_FIELD.ARG_X_AUTH_INTERNALKEY.field).append("=").append(extraKey);
    }
    try {
        return hmacSha256.cryptToHex(builder.toString());
    } catch (Exception e) {
        throw new HttpInvalidAuthenticationException(e);
    }
}

From source file:my.mavenproject10.FileuploadController.java

@RequestMapping(method = RequestMethod.POST)
ModelAndView upload(HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String fileName = "";
    int size = 0;
    ArrayList<String> result = new ArrayList<String>();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {//from   w w  w .ja  v  a2 s.c o m
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                fileName = item.getName();
                System.out.println("file name " + item.getName());
                JAXBContext jc = JAXBContext.newInstance(CustomersType.class);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                XMLReader xmlReader = spf.newSAXParser().getXMLReader();
                InputSource inputSource = new InputSource(
                        new InputStreamReader(item.getInputStream(), "UTF-8"));
                SAXSource source = new SAXSource(xmlReader, inputSource);
                Unmarshaller unmarshaller = jc.createUnmarshaller();
                CustomersType data2 = (CustomersType) unmarshaller.unmarshal(source);
                //System.out.println("size " + data2.getCustomer().size());
                size = data2.getCustomer().size();
                for (CustomerType customer : data2.getCustomer()) {
                    System.out.println(customer.toString());
                }
                //  
                double summ = 0.0;
                HashMap<Integer, Float> ordersMap = new HashMap<Integer, Float>();
                for (CustomerType customer : data2.getCustomer()) {
                    for (OrderType orderType : customer.getOrders().getOrder()) {
                        Float summPerOrder = 0.0f;
                        //System.out.println(orderType);
                        for (PositionType positionType : orderType.getPositions().getPosition()) {
                            //System.out.println(positionType);
                            summPerOrder += positionType.getCount() * positionType.getPrice();
                            summ += positionType.getCount() * positionType.getPrice();
                        }
                        ordersMap.put(orderType.getId(), summPerOrder);
                    }
                }
                summ = new BigDecimal(summ).setScale(2, RoundingMode.UP).doubleValue();
                System.out.println("   " + summ);
                result.add("   " + summ);

                //    
                HashMap<Integer, Float> customersMap = new HashMap<Integer, Float>();
                for (CustomerType customer : data2.getCustomer()) {
                    Float summPerCust = 0.0f;
                    customersMap.put(customer.getId(), summPerCust);
                    for (OrderType orderType : customer.getOrders().getOrder()) {
                        for (PositionType positionType : orderType.getPositions().getPosition()) {
                            summPerCust += positionType.getCount() * positionType.getPrice();
                        }
                    }
                    //System.out.println(customer.getId() + " orders " + summPerCust);
                    customersMap.put(customer.getId(), summPerCust);
                }
                TreeMap sortedMap = sortByValue(customersMap);
                System.out.println(" " + sortedMap.keySet().toArray()[0]
                        + "    : " + sortedMap.get(sortedMap.firstKey()));
                result.add(" " + sortedMap.keySet().toArray()[0] + "    : "
                        + sortedMap.get(sortedMap.firstKey()));

                //  
                TreeMap sortedMapOrders = sortByValue(ordersMap);
                System.out.println("   " + sortedMapOrders.keySet().toArray()[0]
                        + " : " + sortedMapOrders.get(sortedMapOrders.firstKey()));
                result.add("   " + sortedMapOrders.keySet().toArray()[0] + " : "
                        + sortedMapOrders.get(sortedMapOrders.firstKey()));

                //  
                System.out.println("   "
                        + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1]
                        + " : " + sortedMapOrders.get(sortedMapOrders.lastKey()));
                result.add("   "
                        + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1]
                        + " : " + sortedMapOrders.get(sortedMapOrders.lastKey()));

                // 
                System.out.println("  " + sortedMapOrders.size());
                result.add("  " + sortedMapOrders.size());

                //  
                ArrayList<Float> floats = new ArrayList<Float>(sortedMapOrders.values());
                Float summAvg = 0.0f;
                Float avg = 0.0f;
                for (Float f : floats) {
                    summAvg += f;
                }
                avg = new BigDecimal(summAvg / floats.size()).setScale(2, RoundingMode.UP).floatValue();
                System.out.println("   " + avg);
                result.add("   " + avg);

            }
        } catch (FileUploadException e) {
            System.out.println("FileUploadException:- " + e.getMessage());
        } catch (JAXBException ex) {
            //Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    ModelAndView modelAndView = new ModelAndView("fileuploadsuccess");
    modelAndView.addObject("files", result);
    modelAndView.addObject("name", fileName);
    modelAndView.addObject("size", size);
    return modelAndView;

}

From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.CsvTable.java

public List<String[]> findMultiEquals(Pair<Integer, String>... keys) {
    if (keys.length > 0) {
        TreeMap<String, List<String[]>> idx = indices.get(keys[0].getFirst());
        if (idx != null) {
            Pair<Integer, String>[] sk = Arrays.copyOfRange(keys, 1, keys.length);
            List<String[]> res = idx.get(keys[0].getValue());
            if (res == null) {
                return Collections.emptyList();
            }//  www .  j  av a2  s . c o  m
            return findMultiEquals(res, sk);
        }
    }
    return findMultiEquals(table, keys);
}

From source file:org.apache.hadoop.hbase.TestGet.java

private void verifyGet(final HRegion r, final String expectedServer) throws IOException {
    // This should return a value because there is only one family member
    byte[] value = r.get(ROW_KEY, CONTENTS);
    assertNotNull(value);//  w w w  . j a  v  a 2s  .  c  om

    // This should not return a value because there are multiple family members
    value = r.get(ROW_KEY, HConstants.COLUMN_FAMILY);
    assertNull(value);

    // Find out what getFull returns
    TreeMap<Text, byte[]> values = r.getFull(ROW_KEY);

    // assertEquals(4, values.keySet().size());
    for (Iterator<Text> i = values.keySet().iterator(); i.hasNext();) {
        Text column = i.next();
        if (column.equals(HConstants.COL_SERVER)) {
            String server = Writables.bytesToString(values.get(column));
            assertEquals(expectedServer, server);
            LOG.info(server);
        }
    }
}