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.eucalyptus.objectstorage.pipeline.handlers.ObjectStorageAuthenticationHandler.java

/**
 * Ensure that only one header for each name exists (i.e. not 2 Authorization headers)
 * Accomplish this by comma-delimited concatenating any duplicates found as per HTTP 1.1 RFC 2616 section 4.2
 * <p/>/*from   w w w. j a v  a 2 s  .  c o  m*/
 * TODO: Also, should convert all headers to lower-case for consistent processing later. This is okay since headers are case-insensitive.
 * <p/>
 * in HTTP
 *
 * @param httpRequest
 */
private static void canonicalizeHeaders(MappingHttpRequest httpRequest) {
    //Iterate through headers and find duplicates, concatenate their values together and remove from
    // request as we find them.
    TreeMap<String, String> headerMap = new TreeMap<String, String>();
    String value = null;

    //Construct a map of the normalized headers, cannot modify in-place since
    // conconcurrent-modify exception may result
    for (String header : httpRequest.getHeaderNames()) {
        //TODO: zhill, put in the map in lower-case form.
        headerMap.put(header, Joiner.on(',').join(httpRequest.getHeaders(header)));
    }

    //Remove *all* headers
    httpRequest.clearHeaders();

    //Add the normalized headers back into the request
    for (String foundHeader : headerMap.keySet()) {
        httpRequest.addHeader(foundHeader, headerMap.get(foundHeader).toString());
    }
}

From source file:crawler.AScraper.java

/**
 * Insert new art work and new model to db if not exist.
 *
 * @param artwork//  w  w  w  . ja v  a  2s. co  m
 * @return artwork if not exist in db
 * @throws ParseException
 * @throws MalformedURLException
 */
@Transformer(inputChannel = "channel4", outputChannel = "channel5")
public Artwork processNew(Artwork artwork) throws ParseException, MalformedURLException {
    if (modelRepository.getModelByName(artwork.getModelNickname()) == null) {
        LOG.info(String.format("Model=%s,not exist in db,inserting", artwork.getModelNickname()));
        modelRepository.insertModel(new Model(artwork.getModelNickname()));
    }
    Artwork artwork_db = artworkRepository.getArtwork(artwork.getArtId());
    if (artwork_db == null) {
        ThreadPageScraper threadPageScraper = new ThreadPageScraper();
        TreeMap<String, Object> results = threadPageScraper.scrape(artwork.getThreadAddress().toString());
        artwork.setThumbnailImgList((ArrayList<URL>) results.get(ThreadPageScraper.KEY_THUMBNAILS));
        artwork.setAuthorComment((String) results.get(ThreadPageScraper.KEY_AUTHOR_DESCRIPTION));
        artwork.setResolutionX((Integer) results.get(ThreadPageScraper.KEY_RESOLUTION_X));
        artwork.setResolutionY((Integer) results.get(ThreadPageScraper.KEY_RESOLUTION_Y));
        LOG.info("Artwork={},new post, Notify user...", artwork);
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MailConfig.class);
        MailService mailService = ctx.getBean(MailService.class);
        try {
            mailService.sendHtmlMailNotification("kasimok@163.com".split(";"),
                    String.valueOf(mailService.genNotifyForNewArtworkPost(artwork)));
        } catch (MessagingException e) {
            return artwork;
        }
        LOG.info("Artwork={},not exist in db,inserting", artwork);
        artworkRepository.insertArtwork(artwork);
        return artwork;
    } else {
        return artwork_db;
    }
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Before calling the endpoint, set up the cookies found in the request.
 * @param context the context// w w w  .ja  v a  2s.co m
 */
public static void copyCookiesToEndpoint(ProxyContext context) {
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    context.clearRequestCookies();
    if (clientRequest != null) {
        javax.servlet.http.Cookie[] cookies = clientRequest.getCookies();
        HttpState initState = context.getHttpClient().getState();

        if (cookies != null) {
            // Gather up the cookies keyed on the length of the path.
            // This is done so that if we have two cookies with the same name,
            // we pass the cookie with the longest path first to the endpoint
            TreeMap cookieMap = new TreeMap();
            for (javax.servlet.http.Cookie cookie : cookies) {
                CookieInfo origCookie = new CookieInfo(cookie.getName(), cookie.getDomain(), cookie.getName(),
                        cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), null, cookie.getSecure());
                CookieInfo newCookie = RequestUtil.createCookie(origCookie, context,
                        context.getTarget().getUrl().getHost(), context.getTarget().getUrl().getPath());

                if (newCookie != null) {
                    Integer pathInt = Integer.valueOf(0 - newCookie.path.length());
                    ArrayList list = (ArrayList) cookieMap.get(pathInt);
                    if (list == null) {
                        list = new ArrayList();
                        cookieMap.put(pathInt, list);
                    }
                    list.add(newCookie);
                }
            }

            // loop through (in order) the cookies we've gathered
            for (Object mapValue : cookieMap.values()) {
                ArrayList list = (ArrayList) mapValue;
                for (Object aList : list) {
                    CookieInfo cookieInfo = (CookieInfo) aList;
                    if (Log.isInfo()) {
                        String str = "-- Cookie in request: " + cookieInfo;
                        Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug(str);
                    }

                    Cookie cookie = new Cookie(cookieInfo.domain, cookieInfo.name, cookieInfo.value,
                            cookieInfo.path, cookieInfo.maxAge, cookieInfo.secure);

                    // If this is a session cookie and we're dealing with local domain, make sure the session
                    // cookie has the latest session id. This check is needed when the session was invalidated
                    // and then recreated in this request; we shouldn't be sending the old session id to the endpoint.
                    if (context.isLocalDomain() && STRING_JSESSIONID.equalsIgnoreCase(cookieInfo.clientName)) {
                        FlexSession flexSession = FlexContext.getFlexSession();
                        if (flexSession != null && flexSession.isValid()) {
                            String sessionId = flexSession.getId();
                            String cookieValue = cookie.getValue();
                            if (!cookieValue.contains(sessionId)) {
                                int colonIndex = cookieValue.indexOf(':');
                                if (colonIndex != -1) {
                                    // Websphere changes jsession id to the following format:
                                    // 4 digit cacheId + jsessionId + ":" + cloneId.
                                    ServletContext servletContext = FlexContext.getServletContext();
                                    String serverInfo = servletContext != null ? servletContext.getServerInfo()
                                            : null;
                                    boolean isWebSphere = serverInfo != null
                                            && serverInfo.contains("WebSphere");
                                    if (isWebSphere) {
                                        String cacheId = cookieValue.substring(0, 4);
                                        String cloneId = cookieValue.substring(colonIndex);
                                        String wsSessionId = cacheId + sessionId + cloneId;
                                        cookie.setValue(wsSessionId);
                                    } else {
                                        cookie.setValue(sessionId);
                                    }
                                } else {
                                    cookie.setValue(sessionId);
                                }
                            }
                        }
                    }
                    // finally add the cookie to the current request
                    initState.addCookie(cookie);
                    context.addRequestCookie(cookie);
                }
            }
        }
    }
}

From source file:gsn.vsensor.AbstractScheduledVirtualSensor.java

/**
 * Called once while initializing an instance of the virtual sensor
 * Gets schedule parameters from VSD, calculates timer parameters and instantiates timer instance.
 * //from   ww  w.j  a v  a  2s  .  co  m
 * @return True if the initialization is done successfully.
 */
public boolean initialize() {
    TreeMap<String, String> params = getVirtualSensorConfiguration().getMainClassInitialParams();
    String rate_value = params.get(RATE_PARAM);

    if (rate_value == null) {
        logger.warn("Parameter \"" + RATE_PARAM + "\" not provider in Virtual Sensor file");
        return false;
    }

    clock_rate = Integer.parseInt(rate_value);

    String start_value = params.get(START_PARAM);

    if (start_value != null) { //start value set in VSD
        try {
            startTime = Helpers.convertTimeFromIsoToLong(start_value);
        } catch (Exception e) {
            logger.error(
                    "Failed to parse the start-time parameter of the remote wrapper, a sample time could be:"
                            + (CURRENT_TIME));
            throw new RuntimeException(e);
        }
    }
    // If the scheduled start is not in the future
    // then start at the next whole time interval
    if (System.currentTimeMillis() >= startTime) {
        startTime = System.currentTimeMillis(); // current time
        // Calculate from midnight   
        long midnight = DateUtils.truncate(new Date(), Calendar.DATE).getTime();
        long current_time = System.currentTimeMillis();
        // Start
        startTime = midnight + (((current_time - midnight) / clock_rate) + 1) * clock_rate;
    } //otherwise use the time retrieved from the VSD

    logger.warn(getVirtualSensorConfiguration().getName() + " scheduled to start at "
            + new Date(startTime).toString());

    // startTime is used in the virtual sensor class to start a timer
    timer0 = new Timer();
    // timer task is started in the sub class
    return true;
}

From source file:com.opengamma.analytics.financial.interestrate.CashFlowEquivalentCalculator.java

/**
 * Add a cash flow amount at a given time in the flow map. If the time is present, the amount is added; if the time is not present a new entry is created.
 * @param flow The map describing the cash flows.
 * @param time The time of the flow to add.
 * @param amount The amount of the flow to add.
 *///from ww w  .j  a v a  2s.  co  m
private void addcf(TreeMap<Double, Double> flow, double time, double amount) {
    if (flow.containsKey(time)) {
        flow.put(time, flow.get(time) + amount);
    } else {
        flow.put(time, amount);
    }
}

From source file:net.triptech.buildulator.model.DataGrid.java

/**
 * Gets the rows as a list.//from www  .  j  a va 2s  .  co  m
 *
 * @return the list of row data
 */
public List<List<String>> getRows() {
    List<List<String>> data = new ArrayList<List<String>>();

    for (int i : body.keySet()) {
        TreeMap<Integer, String> row = body.get(i);
        List<String> rowData = new ArrayList<String>();

        for (int index : row.keySet()) {
            rowData.add(row.get(index));
        }
        data.add(rowData);
    }
    return data;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.ClusterCentroidsMain.java

public static TreeMap<Integer, Vector> computeClusterCentroids(String inputVectorsPath,
        String clusterOutputPath) throws IOException {
    TreeMap<Integer, Vector> result = new TreeMap<>();
    Map<Integer, Integer> counts = new TreeMap<>();

    // input for cluto
    File inputVectors = new File(inputVectorsPath);

    // resulting clusters
    File clutoClustersOutput = new File(clusterOutputPath);

    LineIterator clustersIterator = IOUtils.lineIterator(new FileInputStream(clutoClustersOutput), "utf-8");

    LineIterator vectorsIterator = IOUtils.lineIterator(new FileInputStream(inputVectors), "utf-8");

    // skip first line (number of clusters and vector size
    vectorsIterator.next();/*from w w  w  .j a  v a2s  . c  o m*/

    while (clustersIterator.hasNext()) {
        String clusterString = clustersIterator.next();
        String vectorString = vectorsIterator.next();

        int clusterNumber = Integer.valueOf(clusterString);

        // now parse the vector
        DenseVector vector = ClusteringUtils.parseVector(vectorString);

        // if there is no resulting vector for the particular cluster, add this one
        if (!result.containsKey(clusterNumber)) {
            result.put(clusterNumber, vector);
        } else {
            // otherwise add this one to the previous one
            result.put(clusterNumber, result.get(clusterNumber).add(vector));
        }

        // and update counts
        if (!counts.containsKey(clusterNumber)) {
            counts.put(clusterNumber, 0);
        }

        counts.put(clusterNumber, counts.get(clusterNumber) + 1);
    }

    // now compute average for each vector
    for (Map.Entry<Integer, Vector> entry : result.entrySet()) {
        // cluster number
        int clusterNumber = entry.getKey();
        // get counts
        int count = counts.get(clusterNumber);

        // divide by count of vectors for each cluster (averaging)
        for (VectorEntry vectorEntry : entry.getValue()) {
            vectorEntry.set(vectorEntry.get() / (double) count);
        }
    }

    return result;
}

From source file:com.example.HDHTAppTest.java

@Test
public void test() throws Exception {
    File file = new File("target/hds2");
    FileUtils.deleteDirectory(file);/*w ww .j  ava2s.  c om*/

    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.set("dt.operator.Store.fileStore.basePath", file.toURI().toString());
    //conf.set("dt.operator.Store.flushSize", "0");
    conf.set("dt.operator.Store.flushIntervalCount", "1");
    conf.set("dt.operator.Store.partitionCount", "2");

    lma.prepareDAG(new HDHTAppTest(), conf);
    LocalMode.Controller lc = lma.getController();
    //lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();

    long tms = System.currentTimeMillis();
    File f0 = new File(file, "0/0-0");
    File f1 = new File(file, "1/1-0");
    File wal0 = new File(file, "0/_WAL-0");
    File wal1 = new File(file, "1/_WAL-0");

    while (System.currentTimeMillis() - tms < 30000) {
        if (f0.exists() && f1.exists())
            break;
        Thread.sleep(100);
    }
    lc.shutdown();

    Assert.assertTrue("exists " + f0, f0.exists() && f0.isFile());
    Assert.assertTrue("exists " + f1, f1.exists() && f1.isFile());
    Assert.assertTrue("exists " + wal0, wal0.exists() && wal0.exists());
    Assert.assertTrue("exists " + wal1, wal1.exists() && wal1.exists());

    HDHTFileAccessFSImpl fs = new TFileImpl.DTFileImpl();

    fs.setBasePath(file.toURI().toString());
    fs.init();

    TreeMap<Slice, byte[]> data = new TreeMap<Slice, byte[]>(new HDHTReader.DefaultKeyComparator());
    fs.getReader(0, "0-0").readFully(data);
    Assert.assertArrayEquals("read key=" + new String(KEY0), DATA0.getBytes(), data.get(new Slice(KEY0)));

    data.clear();
    fs.getReader(1, "1-0").readFully(data);
    Assert.assertArrayEquals("read key=" + new String(KEY1), DATA1.getBytes(), data.get(new Slice(KEY1)));

    fs.close();
}

From source file:org.alfresco.wcm.client.impl.SectionFactoryWebscriptImpl.java

/**
 * Create a Section from a QueryResult//from   www . j  a v  a2  s  .c  o m
 * 
 * @param result
 *            query result
 * @return Section section object
 */
@SuppressWarnings("unchecked")
protected SectionDetails buildSection(TreeMap<String, Serializable> result) {
    SectionDetails sectionDetails = new SectionDetails();

    SectionImpl section = new SectionImpl();

    section.setProperties(result);

    List<String> tagSummary = (List<String>) result.get(PROPERTY_TAG_SUMMARY);
    section.setTags(createTags(tagSummary));
    section.setSectionFactory(this);
    section.setAssetFactory(getAssetFactory());
    section.setDictionaryService(getDictionaryService());
    section.setCollectionFactory(getCollectionFactory());

    sectionDetails.section = section;
    sectionDetails.objectTypeId = (String) result.get("type");

    // Don't set parent of webroot as it is conceptually the top of the tree
    if (!sectionDetails.objectTypeId.equals("ws:webroot")) {
        String parentId = (String) result.get("ws:parentId");
        section.setPrimarySectionId(parentId);
        sectionDetails.parentId = parentId;
    }

    return sectionDetails;
}

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

public String[] findFirst(int idx, String name) {
    TreeMap<String, List<String[]>> index = indices.get(idx);
    if (index != null) {
        List<String[]> n = index.get(name);
        if (n == null) {
            return null;
        }//from ww  w . j ava 2s . co m
        return n.get(0);
    }
    for (String[] rec : table) {
        if (rec.length > idx) {
            String n = rec[idx];
            if (name.equals(n) == true) {
                return rec;
            }
        }
    }
    return null;
}