Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

In this page you can find the example usage for java.util HashMap size.

Prototype

int size

To view the source code for java.util HashMap size.

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:fr.cirad.mgdb.exporting.individualoriented.DARwinExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, Collection<File> individualExportFiles,
        boolean fDeleteSampleExportFilesOnExit, ProgressIndicator progress, DBCursor markerCursor,
        Map<Comparable, Comparable> markerSynonyms, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    GenotypingProject aProject = mongoTemplate.findOne(
            new Query(Criteria.where(GenotypingProject.FIELDNAME_PLOIDY_LEVEL).exists(true)),
            GenotypingProject.class);
    if (aProject == null)
        LOG.warn("Unable to find a project containing ploidy level information! Assuming ploidy level is 2.");

    int ploidy = aProject == null ? 2 : aProject.getPloidyLevel();

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*from   w  w w .j  av  a 2  s .  c  o  m*/
        }

    String exportName = sModule + "_" + markerCount + "variants_" + individualExportFiles.size()
            + "individuals";

    StringBuffer donFileContents = new StringBuffer(
            "@DARwin 5.0 - DON -" + LINE_SEPARATOR + individualExportFiles.size() + "\t" + 1 + LINE_SEPARATOR
                    + "N" + "\t" + "individual" + LINE_SEPARATOR);

    int count = 0;
    String missingGenotype = "";
    for (int j = 0; j < ploidy; j++)
        missingGenotype += "\tN";

    zos.putNextEntry(new ZipEntry(exportName + ".var"));
    zos.write(("@DARwin 5.0 - ALLELIC - " + ploidy + LINE_SEPARATOR + individualExportFiles.size() + "\t"
            + markerCount * ploidy + LINE_SEPARATOR + "N").getBytes());

    DBCursor markerCursorCopy = markerCursor.copy(); // dunno how expensive this is, but seems safer than keeping all IDs in memory at any time

    short nProgress = 0, nPreviousProgress = 0;
    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    markerCursorCopy.batchSize(nChunkSize);

    int nMarkerIndex = 0;
    while (markerCursorCopy.hasNext()) {
        DBObject exportVariant = markerCursorCopy.next();
        Comparable markerId = (Comparable) exportVariant.get("_id");

        if (markerSynonyms != null) {
            Comparable syn = markerSynonyms.get(markerId);
            if (syn != null)
                markerId = syn;
        }
        for (int j = 0; j < ploidy; j++)
            zos.write(("\t" + markerId).getBytes());
    }

    TreeMap<Integer, Comparable> problematicMarkerIndexToNameMap = new TreeMap<Integer, Comparable>();
    ArrayList<String> distinctAlleles = new ArrayList<String>(); // the index of each allele will be used as its code
    int i = 0;
    for (File f : individualExportFiles) {
        BufferedReader in = new BufferedReader(new FileReader(f));
        try {
            String individualId, line = in.readLine(); // read sample id

            if (line != null)
                individualId = line;
            else
                throw new Exception("Unable to read first line of temp export file " + f.getName());

            donFileContents.append(++count + "\t" + individualId + LINE_SEPARATOR);

            zos.write((LINE_SEPARATOR + count).getBytes());
            nMarkerIndex = 0;

            while ((line = in.readLine()) != null) {
                List<String> genotypes = MgdbDao.split(line, "|");
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                int highestGenotypeCount = 0;
                String mostFrequentGenotype = null;
                for (String genotype : genotypes) {
                    if (genotype.length() == 0)
                        continue; /* skip missing genotypes */

                    int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                    if (gtCount > highestGenotypeCount) {
                        highestGenotypeCount = gtCount;
                        mostFrequentGenotype = genotype;
                    }
                    genotypeCounts.put(genotype, gtCount);
                }

                if (genotypeCounts.size() > 1) {
                    warningFileWriter.write("- Dissimilar genotypes found for variant __" + nMarkerIndex
                            + "__, individual " + individualId + ". Exporting most frequent: "
                            + mostFrequentGenotype + "\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String codedGenotype = "";
                if (mostFrequentGenotype != null)
                    for (String allele : mostFrequentGenotype.split(" ")) {
                        if (!distinctAlleles.contains(allele))
                            distinctAlleles.add(allele);
                        codedGenotype += "\t" + distinctAlleles.indexOf(allele);
                    }
                else
                    codedGenotype = missingGenotype.replaceAll("N", "-1"); // missing data is coded as -1
                zos.write(codedGenotype.getBytes());

                nMarkerIndex++;
            }
        } catch (Exception e) {
            LOG.error("Error exporting data", e);
            progress.setError("Error exporting data: " + e.getClass().getSimpleName()
                    + (e.getMessage() != null ? " - " + e.getMessage() : ""));
            return;
        } finally {
            in.close();
        }

        if (progress.hasAborted())
            return;

        nProgress = (short) (++i * 100 / individualExportFiles.size());
        if (nProgress > nPreviousProgress) {
            //            LOG.debug("============= doDARwinExport (" + i + "): " + nProgress + "% =============");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }

        if (!f.delete()) {
            f.deleteOnExit();
            LOG.info("Unable to delete tmp export file " + f.getAbsolutePath());
        }
    }

    zos.putNextEntry(new ZipEntry(exportName + ".don"));
    zos.write(donFileContents.toString().getBytes());

    // now read variant names for those that induced warnings
    nMarkerIndex = 0;
    markerCursor.batchSize(nChunkSize);
    while (markerCursor.hasNext()) {
        DBObject exportVariant = markerCursor.next();
        if (problematicMarkerIndexToNameMap.containsKey(nMarkerIndex)) {
            Comparable markerId = (Comparable) exportVariant.get("_id");

            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(markerId);
                if (syn != null)
                    markerId = syn;
            }
            for (int j = 0; j < ploidy; j++)
                zos.write(("\t" + markerId).getBytes());

            problematicMarkerIndexToNameMap.put(nMarkerIndex, markerId);
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            for (Integer aMarkerIndex : problematicMarkerIndexToNameMap.keySet())
                sLine = sLine.replaceAll("__" + aMarkerIndex + "__",
                        problematicMarkerIndexToNameMap.get(aMarkerIndex).toString());
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

public void testEntrySetEntrySetterNonString() {
    HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
    hashMap.put(1, 2);// w w  w  .j a  v  a  2 s  . c om
    Set<Map.Entry<Integer, Integer>> entrySet = hashMap.entrySet();
    Map.Entry<Integer, Integer> entry = entrySet.iterator().next();

    entry.setValue(3);
    assertEquals(3, hashMap.get(1).intValue());

    hashMap.put(1, 4);
    assertEquals(4, entry.getValue().intValue());

    assertEquals(1, hashMap.size());
}

From source file:com.google.gwt.emultest.java.util.HashMapTest.java

public void testEntrySetEntrySetterNull() {
    HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
    hashMap.put(null, 2);//from w  w w.j a  va 2 s .  c o m
    Set<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();
    Map.Entry<String, Integer> entry = entrySet.iterator().next();

    entry.setValue(3);
    assertEquals(3, hashMap.get(null).intValue());

    hashMap.put(null, 4);
    assertEquals(4, entry.getValue().intValue());

    assertEquals(1, hashMap.size());
}

From source file:eu.dety.burp.joseph.attacks.key_confusion.KeyConfusionInfo.java

@Override
public KeyConfusion prepareAttack(IBurpExtenderCallbacks callbacks, IHttpRequestResponse requestResponse,
        IRequestInfo requestInfo, JoseParameter parameter) throws AttackPreparationFailedException {
    this.requestResponse = requestResponse;
    this.parameter = parameter;

    this.publicKeyVariations.clear();
    this.requests.clear();

    String publicKeyValue = publicKey.getText();

    // Throw error if public key value is empty
    if (publicKeyValue.isEmpty()) {
        throw new AttackPreparationFailedException(bundle.getString("PROVIDE_PUBKEY"));
    }// w  w w  .  j a  v a 2 s  .c  o m

    // Parse public key according to selected format
    int publicKeyFormat = publicKeySelection.getSelectedIndex();

    switch (publicKeyFormat) {
    // JWK (JSON)
    case 1:
        // TODO: Refactor to test every key at once? Requires change of HashMap key

        loggerInstance.log(getClass(), "Key format is JWK:  " + publicKeyValue, Logger.LogLevel.DEBUG);

        HashMap<String, PublicKey> publicKeys;
        PublicKey selectedPublicKey;

        try {
            Object publickKeyValueJson = new JSONParser().parse(publicKeyValue);

            publicKeys = Converter.getRsaPublicKeysByJwkWithId(publickKeyValueJson);
        } catch (Exception e) {
            loggerInstance.log(getClass(), "Error in prepareAttack (JWK):  " + e.getMessage(),
                    Logger.LogLevel.ERROR);
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK"));
        }

        switch (publicKeys.size()) {
        // No suitable JWK in JWK Set found
        case 0:
            loggerInstance.log(getClass(), "Error in prepareAttack (JWK): No suitable JWK",
                    Logger.LogLevel.ERROR);
            throw new AttackPreparationFailedException(bundle.getString("NO_SUITABLE_JWK"));

            // Exactly one suitable JWK found
        case 1:
            selectedPublicKey = publicKeys.entrySet().iterator().next().getValue();
            break;

        // More than one suitable JWK found. Provide dialog to select one.
        default:
            selectedPublicKey = Converter.getRsaPublicKeyByJwkSelectionPanel(publicKeys);
        }

        try {
            loggerInstance.log(getClass(),
                    "Encoded PubKey: " + Base64.encodeBase64String(selectedPublicKey.getEncoded())
                            + "\nFormat: " + selectedPublicKey.getFormat(),
                    Logger.LogLevel.DEBUG);

            // PKCS#8 / X.509
            publicKeyVariations.put(PayloadType.PKCS8,
                    transformKeyByPayload(PayloadType.PKCS8, selectedPublicKey));

            // With header/footer
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER, selectedPublicKey));

            // With line feeds
            publicKeyVariations.put(PayloadType.PKCS8_WITH_LF,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_LF, selectedPublicKey));

            // With line feeds and header/footer
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF, selectedPublicKey));

            // With line feeds and header/footer and additional line feed at end
            publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, transformKeyByPayload(
                    PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, selectedPublicKey));

        } catch (Exception e) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK"));
        }

        break;
    // PEM (String)
    default:
        loggerInstance.log(getClass(), "Key format is PEM:  " + publicKeyValue, Logger.LogLevel.DEBUG);

        // Simple check if String has valid format
        if (!publicKeyValue.trim().startsWith("-----BEGIN") && !publicKeyValue.trim().startsWith("MI")) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM"));
        }

        try {
            // No modification
            publicKeyVariations.put(PayloadType.ORIGINAL, publicKeyValue);

            // Without header/footer
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER, publicKeyValue));

            // Without line feeds/carriage returns
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_LF, publicKeyValue));

            // Without header/footer and line feeds/carriage returns
            publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF, publicKeyValue));

            publicKeyVariations.put(PayloadType.ORIGINAL_ADDITIONAL_LF,
                    transformKeyByPayload(PayloadType.ORIGINAL_ADDITIONAL_LF, publicKeyValue));

            // PKCS#1, easy but hacky transformation
            publicKeyVariations.put(PayloadType.PKCS1,
                    transformKeyByPayload(PayloadType.PKCS1, publicKeyValue));

            // PKCS#1 without header/footer
            publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER,
                    transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER, publicKeyValue));

            // PKCS#1 without line feeds/carriage returns
            publicKeyVariations.put(PayloadType.PKCS1_NO_LF,
                    transformKeyByPayload(PayloadType.PKCS1_NO_LF, publicKeyValue));

            // PKCS#1 without header/footer and line feeds/carriage
            // returns
            publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER_LF,
                    transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER_LF, publicKeyValue));

        } catch (Exception e) {
            throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM"));
        }

        break;
    }

    for (Map.Entry<PayloadType, String> publicKey : publicKeyVariations.entrySet()) {
        for (String algorithm : algorithms) {
            try {
                // Change the "alg" header value for each of the algorithms
                // entries
                String[] components = Decoder.getComponents(this.parameter.getJoseValue());
                String decodedHeader = Decoder.getDecoded(components[0]);
                String decodedHeaderReplacedAlgorithm = decodedHeader.replaceFirst("\"alg\":\"(.+?)\"",
                        "\"alg\":\"" + algorithm + "\"");
                String encodedHeaderReplacedAlgorithm = Decoder.getEncoded(decodedHeaderReplacedAlgorithm);

                String macAlg = Crypto.getMacAlgorithmByJoseAlgorithm(algorithm, "HmacSHA256");

                // Generate signature
                String newSignature = Decoder
                        .getEncoded(Crypto.generateMac(macAlg, helpers.stringToBytes(publicKey.getValue()),
                                helpers.stringToBytes(Decoder.concatComponents(
                                        new String[] { encodedHeaderReplacedAlgorithm, components[1] }))));

                // Build new JWS String and update parameter
                String[] newComponents = { encodedHeaderReplacedAlgorithm, components[1], newSignature };
                String newComponentsConcatenated = Decoder.concatComponents(newComponents);

                byte[] tmpRequest = JoseParameter.updateRequest(this.requestResponse.getRequest(),
                        this.parameter, helpers, newComponentsConcatenated);
                requests.add(new KeyConfusionAttackRequest(tmpRequest, publicKey.getKey().ordinal(), algorithm,
                        publicKey.getValue(), publicKey.getValue().length()));
            } catch (Exception e) {
                throw new AttackPreparationFailedException(
                        "Attack preparation failed. Message: " + e.getMessage());
            }
        }
    }

    this.amountRequests = requests.size();
    return new KeyConfusion(callbacks, this);
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.BarCharts.java

/**
 * Use for slider: limits the categories visualization from cat selected to cat selected+numberscatsVisualization.
 * //from   www  .  j  a v a 2  s.  c  om
 * @param dataset the dataset
 * @param categories the categories
 * @param catSelected the cat selected
 * @param numberCatsVisualization the number cats visualization
 * 
 * @return the dataset
 */

public Dataset filterDataset(Dataset dataset, HashMap categories, int catSelected,
        int numberCatsVisualization) {
    logger.debug("IN");
    DefaultCategoryDataset catDataset = (DefaultCategoryDataset) dataset;

    int numCats = categories.size();
    Vector visCat = new Vector();
    // from the choice point to min(chose point+interval, end point)
    //int startPoint=((catSelected-1)*numberCatsVisualization)+1;
    int startPoint = catSelected;

    int endPoint;
    if ((startPoint + numberCatsVisualization - 1) <= (categories.size()))
        endPoint = startPoint + numberCatsVisualization - 1;
    else
        endPoint = categories.size();

    for (int i = (startPoint); i <= endPoint; i++) {
        String name = (String) categories.get(new Integer(i));
        visCat.add(name);
    }

    List columns = new Vector(catDataset.getColumnKeys());
    for (Iterator iterator = columns.iterator(); iterator.hasNext();) {
        String col = (String) iterator.next();
        if (!(visCat.contains(col))) {
            catDataset.removeColumn(col);
        }
    }
    logger.debug("OUT");

    return catDataset;

}

From source file:com.moscona.dataSpace.ExportHelper.java

public void csvExportAll(INameSpace ns, String dirName, boolean includeMetaData)
        throws DataSpaceException, FileNotFoundException {
    File dir = new File(dirName);
    if (!dir.exists()) {
        dir.mkdirs();/*from w w w  .  j  ava  2  s.c om*/
    }

    HashMap<String, IScalar> scalars = new HashMap<String, IScalar>();

    for (String name : ns.getAssignedVariableNames()) {
        try {
            IDataElement var = ns.get(name);
            if (IScalar.class.isAssignableFrom(var.getClass())) {
                scalars.put(name, (IScalar) var);
            }
            if (DataFrame.class.isAssignableFrom(var.getClass())) {
                DataFrame df = (DataFrame) var;
                csvExport(df, dirName + "/" + name + ".dataFrame.csv", includeMetaData);
            }
            if (AbstractVector.class.isAssignableFrom(var.getClass())) {
                AbstractVector vector = (AbstractVector) var;
                csvExport(vector, dirName + "/" + name + ".vector.csv", includeMetaData);
            }
        } catch (DataSpaceException e) {
            throw new DataSpaceException("Error while exporting " + ns.get(name).getClass().getSimpleName()
                    + " \"" + name + "\": " + e, e);
        }
    }

    if (scalars.size() == 0) {
        return;
    }

    String filename = dirName + "/scalars.csv";
    PrintStream out = new PrintStream(new File(filename));
    try {
        for (String name : scalars.keySet()) {
            csvOut(out, name, toCsvString(scalars.get(name)));
        }
    } finally {
        out.close();
    }
}

From source file:net.bluehornreader.service.FeedCrawlerService.java

/**
 * If there's any change, it deletes all previous feeds. Whould be nicer to keep what already exists but not sure it's worth it
 *
 * @throws Exception/*from   w  w w.j a  v  a 2  s  .  c o  m*/
 */
private void updateFeedList() throws Exception {

    int feedIdsSeq = crawlerDb.getFeedIdsSeq(crawler.crawlerId);
    if (crawler.feedIdsSeq == feedIdsSeq) {
        return;
    }

    LOG.info("Feed list changed");
    HashMap<String, FeedInfo> newFeedMap = new HashMap<>();

    Crawler newCrawler = crawlerDb.getCrawler(crawler.crawlerId);

    synchronized (this) {

        // Some feeds might be being crawled at this time; we don't want to end up with 2 entries for them in availableFeeds, so we don't add them
        HashSet<String> crawlingFeedIds = new HashSet<>(feedMap.keySet());
        {
            HashSet<String> availableFeedIds = new HashSet<>();
            for (FeedInfo feedInfo : availableFeeds) {
                availableFeedIds.add(feedInfo.feed.feedId);
            }
            crawlingFeedIds.removeAll(availableFeedIds);
        }

        availableFeeds = new PriorityQueue<>(newFeedMap.size() + 1, feedInfoComparator);
        for (String feedId : newCrawler.feedIds) {
            Feed feed = feedDb.get(feedId);
            if (feed == null) {
                LOG.warn(String.format(
                        "FeedCrawlerService %s was asked to crawl feed %s but couldn't find such a feed", IP,
                        feedId));
            } else {
                FeedInfo feedInfo = feedMap.get(feedId);
                if (feedInfo == null) {
                    feedInfo = new FeedInfo(feed, getSeq());
                    LOG.info("New feed to crawl: " + feedInfo);
                }
                newFeedMap.put(feedId, feedInfo);
                if (crawlingFeedIds.contains(feedId)) {
                    LOG.info(String.format(
                            "Feed %s is being currently crawled, so it's not going to be added to the list with available feeds",
                            feedInfo));
                } else {
                    availableFeeds.add(feedInfo);
                }
            }
        }

        feedMap = newFeedMap;
        crawler.feedIdsSeq = feedIdsSeq;
        LOG.info("Feeds to crawl: " + feedMap);
    }
}

From source file:com.planetmayo.debrief.satc_rcp.views.SpatialView.java

private void plotRoutesWithScores(HashMap<LegWithRoutes, ArrayList<ScoredRoute>> legRoutes) {
    if (legRoutes.size() == 0)
        return;// w  ww. j  av a2s.  c o  m

    // we need to store the point labels. get ready to store them
    _scoredRouteLabels.clear();
    final DateFormat labelTimeFormat = new SimpleDateFormat("mm:ss");

    // work through the legs
    Iterator<LegWithRoutes> lIter = legRoutes.keySet().iterator();
    while (lIter.hasNext()) {
        final LegWithRoutes thisL = lIter.next();
        final ArrayList<ScoredRoute> scoredRoutes = legRoutes.get(thisL);

        double max = 0, min = Double.MAX_VALUE;
        for (Iterator<ScoredRoute> iterator = scoredRoutes.iterator(); iterator.hasNext();) {
            ScoredRoute route = iterator.next();
            // Ensure thisScore is between 0-100
            double thisScore = route.theScore;

            thisScore = Math.log(thisScore);

            if (max < thisScore) {
                max = thisScore;
            }
            if (min > thisScore) {
                min = thisScore;
            }
        }

        System.out.println(" for leg: " + thisL.getClass().getName() + " min:" + min + " max:" + max);

        for (Iterator<ScoredRoute> iterator = scoredRoutes.iterator(); iterator.hasNext();) {
            ScoredRoute route = iterator.next();

            Point startP = route.theRoute.getStartPoint();
            Point endP = route.theRoute.getEndPoint();

            // Ensure thisScore is between 0-100
            double thisScore = route.theScore;
            thisScore = Math.log(thisScore);

            double thisColorScore = (thisScore - min) / (max - min);

            // System.out.println("this s:" + (int) thisScore + " was:"
            // + route.theScore);

            XYSeries series = new XYSeries("" + (_numCycles++), false);
            series.add(new XYDataItem(startP.getY(), startP.getX()));
            series.add(new XYDataItem(endP.getY(), endP.getX()));

            // get the shape
            _myData.addSeries(series);

            // get the series num
            int num = _myData.getSeriesCount() - 1;
            _renderer.setSeriesPaint(num, getHeatMapColorFor(thisColorScore));

            // make the line width inversely proportional to the score, with a max
            // width of 2 pixels
            final float width = (float) (2f - 2 * thisColorScore);

            // make the top score solid, and worse scores increasingly sparse
            final float dash[];
            if (thisScore == min) {
                dash = null;
            } else {
                float thisWid = (float) (1f + Math.exp(thisScore - min) / 3);
                float[] tmpDash = { 4, thisWid };
                dash = tmpDash;
            }

            // and put this line thickness, dashing into a stroke object
            BasicStroke stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f,
                    dash, 0.0f);

            _renderer.setSeriesStroke(num, stroke, false);
            _renderer.setSeriesLinesVisible(num, true);
            _renderer.setSeriesShapesVisible(num, false);
            _renderer.setSeriesVisibleInLegend(num, false);

            // ok, we'll also show the route points
            XYSeries series2 = new XYSeries("" + (_numCycles++), false);

            ArrayList<String> theseLabels = new ArrayList<String>();

            // loop through the points
            Iterator<State> stIter = route.rawRoute.getStates().iterator();
            while (stIter.hasNext()) {
                State state = (State) stIter.next();
                Point loc = state.getLocation();
                XYDataItem newPt = new XYDataItem(loc.getY(), loc.getX());
                series2.add(newPt);
                // and store the label for this point
                theseLabels.add(labelTimeFormat.format(state.getTime()));
            }

            // get the shape
            _myData.addSeries(series2);
            //
            // // get the series num
            num = _myData.getSeriesCount() - 1;

            // ok, we now need to put hte series into the right slot
            _scoredRouteLabels.put(num, theseLabels);

            if (_settings.isShowRoutePointLabels()) {
                _renderer.setSeriesItemLabelGenerator(num, new XYItemLabelGenerator() {

                    @Override
                    public String generateLabel(XYDataset arg0, int arg1, int arg2) {
                        String res = null;
                        ArrayList<String> thisList = _scoredRouteLabels.get(arg1);
                        if (thisList != null) {
                            res = thisList.get(arg2);
                        }
                        return res;
                    }
                });
                _renderer.setSeriesItemLabelPaint(num, getHeatMapColorFor(thisColorScore));
            }

            // _renderer.setSeriesPaint(num, getHeatMapColorFor(thisColorScore));
            _renderer.setSeriesItemLabelsVisible(num, _settings.isShowRoutePointLabels());
            _renderer.setSeriesLinesVisible(num, false);
            _renderer.setSeriesPaint(num, getHeatMapColorFor(thisColorScore));
            _renderer.setSeriesShapesVisible(num, _settings.isShowRoutePoints());
            _renderer.setSeriesVisibleInLegend(num, false);
        }
    }
}

From source file:com.olleh.ucloudbiz.ucloudstorage.FilesClientExt.java

/**
* <p>/*  w w w  . j  ava2s .  c  o  m*/
* FilesObjectMetaData  manifest   . 
* </p>
*
* @param containerName
*             container 
* @param objName
*              
*
* @return FilesObjectMetaDataExt
*
* @see  <A HREF="../../../../com/rackspacecloud/client/cloudfiles/FilesClient.html#getObjectMetaData(java.lang.String, java.lang.String)"><CODE>FilesClient.getObjectMetaData(String, String)</CODE></A>,
*       <A HREF="../../../../com/rackspacecloud/client/cloudfiles/FilesObjectMetaData.html"><CODE>FilesObjectMetaData</CODE></A>,
*       <A HREF="../../../../com/kt/client/ucloudstorage/FilesObjectMetaDataExt.html"><CODE>FilesObjectMetaDataExt</CODE></A>
*/
public FilesObjectMetaDataExt getObjectMetaDataExt(String containerName, String objName) throws IOException,
        FilesNotFoundException, HttpException, FilesAuthorizationException, FilesInvalidNameException {
    FilesObjectMetaDataExt metaData;
    if (this.isLoggedin()) {
        if (isValidContainerName(containerName) && isValidObjectName(objName)) {
            HttpHead method = new HttpHead(
                    storageURL + "/" + sanitizeForURI(containerName) + "/" + sanitizeForURI(objName));
            try {
                method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                FilesResponseExt response = new FilesResponseExt(client.execute(method));

                if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    method.abort();
                    login();
                    method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                    method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                    response = new FilesResponseExt(client.execute(method));
                }

                if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT
                        || response.getStatusCode() == HttpStatus.SC_OK) {
                    logger.debug("Object metadata retreived  : " + objName);
                    String mimeType = response.getContentType();
                    String lastModified = response.getLastModified();
                    String eTag = response.getETag();
                    String contentLength = response.getContentLength();
                    String contentType = response.getContentType();
                    String objectManifest = response.getObjectManifest();

                    metaData = new FilesObjectMetaDataExt(mimeType, contentLength, eTag, lastModified,
                            contentType, objectManifest);

                    Header[] headers = response.getResponseHeaders();
                    HashMap<String, String> headerMap = new HashMap<String, String>();

                    for (Header h : headers) {
                        if (h.getName().startsWith(FilesConstants.X_OBJECT_META)) {
                            headerMap.put(h.getName().substring(FilesConstants.X_OBJECT_META.length()),
                                    unencodeURI(h.getValue()));
                        }
                    }
                    if (headerMap.size() > 0)
                        metaData.setMetaData(headerMap);

                    return metaData;
                } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    throw new FilesNotFoundException(
                            "Container: " + containerName + " did not have object " + objName,
                            response.getResponseHeaders(), response.getStatusLine());
                } else {
                    throw new FilesException("Unexpected Return Code from Server",
                            response.getResponseHeaders(), response.getStatusLine());
                }
            } finally {
                method.abort();
            }
        } else {
            if (!isValidObjectName(objName)) {
                throw new FilesInvalidNameException(objName);
            } else {
                throw new FilesInvalidNameException(containerName);
            }
        }
    } else {
        throw new FilesAuthorizationException("You must be logged in", null, null);
    }
}

From source file:edu.ku.brc.specify.plugins.ipadexporter.IPadCloudJSONImpl.java

/**
 * @param valuesMap/*w  ww. j a  v a  2s .com*/
 * @return
 */
private synchronized JSONObject sendPost(final HashMap<String, String> valuesMap) {
    String writeURLStr = getWriteURL();

    isNetworkError = false;

    //        System.out.println(writeURLStr);
    //        System.out.println("\n------------------------ ");
    //        for (String k : valuesMap.keySet())
    //        {
    //            System.out.println(String.format("[%s] [%s]", k, valuesMap.get(k)));
    //        }
    //        System.out.println("------------------------\n"+writeURLStr);
    //UIRegistry.showError("Cloud URL: "+writeURLStr); // Visual Debugging

    PostMethod post = new PostMethod(writeURLStr);
    try {
        Part[] parts = new Part[valuesMap.size()];
        int i = 0;
        for (String key : valuesMap.keySet()) {
            //System.out.println("key["+key+"] val["+valuesMap.get(key)+"]");
            String val = valuesMap.get(key);
            parts[i++] = new StringPart(key, val == null ? "" : val, "UTF-8");
        }

        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        //System.out.println("CharSet: "+client.getParams().getHttpElementCharset());
        client.getParams().setHttpElementCharset("UTF-8");
        //System.out.println("CharSet: "+client.getParams().getHttpElementCharset());

        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            System.err.println("HTTP Status: OK");
            String outStr = post.getResponseBodyAsString();
            System.out.println("outStr[" + outStr + "]");

            return JSONObject.fromObject(outStr);
        }

        System.err.println("HTTP Status: " + status);
        System.err.println(post.getResponseBodyAsString());

    } catch (java.net.UnknownHostException uex) {
        isNetworkError = true;

    } catch (Exception ex) {
        System.out.println("Error:  " + ex.getMessage());
        ex.printStackTrace();
        isNetworkError = true;

    } finally {
        post.releaseConnection();
    }
    return null;
}