Example usage for java.util TreeMap put

List of usage examples for java.util TreeMap put

Introduction

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

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:it.cnr.icar.eric.client.ui.thin.UserPreferencesBean.java

/** Returns a Collection of all locales as SelectItems. */
public Collection<SelectItem> getAllLocalesSelectItems() {
    if (allLocalesSelectItems == null) {
        TreeMap<String, SelectItem> selectItemsMap = new TreeMap<String, SelectItem>();
        Locale loc[] = Locale.getAvailableLocales();
        for (int i = 0; i < loc.length; i++) {
            String name = loc[i].getDisplayName(loc[i]);
            SelectItem item = new SelectItem(loc[i].toString(), name);
            selectItemsMap.put(name.toLowerCase(), item);
        }//from  ww  w  . j  a v  a2 s.  co m
        Collection<SelectItem> all = new ArrayList<SelectItem>();
        all.addAll(selectItemsMap.values());
        allLocalesSelectItems = all;
    }
    return allLocalesSelectItems;
}

From source file:acoli.controller.Controller.java

/**
 *
 * @param request/*from   w w w.  j a v a 2s  .  c om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws FileNotFoundException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileNotFoundException {

    // Get servlet context.
    ServletContext servletContext = this.getServletConfig().getServletContext();
    String path = servletContext.getRealPath("/");
    //System.out.println(path);
    // Previously used way to obtain servlet context doesn't work.
    //ServletContext context = request.getServletContext();
    //String path = context.getRealPath("/");
    //System.out.println("ServletContext.getRealPath():" + path + "<--");

    String forward = "";
    // Get a map of the request parameters
    @SuppressWarnings("unchecked")
    Map parameters = request.getParameterMap();

    if (parameters.containsKey("grammar")) {
        HttpSession session = request.getSession(false);
        String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //System.out.println("Uploaded file to analyze: " + absoluteUnzippedGrammarDir);

        // User-selected port.
        String javaport = (String) request.getParameter("javaport");

        System.out.println("User selected port: " + javaport);
        String traleport = String.valueOf((Integer.parseInt(javaport) - 1000));

        // Check if these ports are already in use
        // if so, kill the grammar in the corresponding directory and start a new one.
        if (portAvailable(Integer.parseInt(javaport)) && portAvailable(Integer.parseInt(traleport))) {
            System.out.println("Both javaport/traleport: " + javaport + "/" + traleport + " available!");
        } else {
            // Java port not free.
            if (!portAvailable(Integer.parseInt(javaport))) {
                System.out.println("Port: " + javaport + " not available!");
                // Get the grammar directory that is running on this port and kill it.
                if (portToGrammarFolderMappings.containsKey(javaport)) {
                    String grammarDirToKill = portToGrammarFolderMappings.get(javaport);
                    // Stop grammar.
                    runBashScript(path, "./single_grammar_stop.sh", grammarDirToKill, "");

                } else {
                    killProcessID(path, "./free_java_port.sh", javaport);
                }
            }
            // Trale port not free.
            if (!portAvailable(Integer.parseInt(traleport))) {
                killProcessID(path, "./free_sicstus_port.sh", traleport);
            }
        }
        // Generate port-specific files
        // which will be redirected by the script later.
        PrintWriter w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "javaserverport.txt"));
        w.write(javaport);
        w.flush();
        w.close();

        w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "traleserverstart.pl"));
        w.write("trale_server_start(" + traleport + ").\n"); // 1000 port ids less than the java id.
        w.flush();
        w.close();

        // Copy wtx.pl and tokenization.pl into the grammar directory.
        File tokenizationFile = new File(path + "/resources/servertrale_files/tokenization.pl");
        File wtxFile = new File(path + "/resources/servertrale_files/wtx.pl");

        //System.out.println("tokenizationFile: " + tokenizationFile.getAbsolutePath());
        //System.out.println("wtxFile: " + wtxFile.getAbsolutePath());
        File destinationDir = new File(absoluteUnzippedGrammarDir + "/");
        //System.out.println("destinationDir: " + absoluteUnzippedGrammarDir);
        FileUtils.copyFileToDirectory(tokenizationFile, destinationDir);
        FileUtils.copyFileToDirectory(wtxFile, destinationDir);

        // Start grammar.
        // Check webtrale version from user selection.
        String labelVersion = (String) request.getParameter("webtraleVersion");
        System.out.println("User selected label version: " + labelVersion);

        switch (labelVersion) {
        case "webtralePS94":
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_labels.jar");
            break;
        case "webtraleAprilLabels":
            // April labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_aprillabels.jar");
            break;
        case "webtraleMayLabels":
            // May labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_maylabels.jar");
            break;
        case "webtraleJuneLabels":
            // June labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_junelabels.jar");
            break;
        default:
            // Standard labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_nolabels.jar");
            break;
        }

        portToGrammarFolderMappings.put(javaport, absoluteUnzippedGrammarDir);
        session.setAttribute("javaport", javaport);
        System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n");

        forward = GRAMMAR_JSP;
    } else if (parameters.containsKey("run")) {
        forward = RUN_JSP;
    } else if (parameters.containsKey("admin")) {
        System.out.println("Accessing grammar admin.");
        // Check which ports are still non-available.
        TreeMap<String, String> tmpMap = new TreeMap<>();
        for (String aJavaPort : portToGrammarFolderMappings.keySet()) {
            if (!portAvailable(Integer.parseInt(aJavaPort))) {
                tmpMap.put(aJavaPort, portToGrammarFolderMappings.get(aJavaPort));
            }
        }

        portToGrammarFolderMappings.clear();
        portToGrammarFolderMappings = tmpMap;
        System.out
                .println("Used ports and grammar directories in admin: " + portToGrammarFolderMappings + "\n");

        // only testing.
        //portToGrammarFolderMappings.put("7001", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/BEBFECC89/posval");
        //portToGrammarFolderMappings.put("7002", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/B02CA6BAA/4_Semantics_Raising");

        // Save all used ports and directories in this session attribute.
        HttpSession session = request.getSession(false);
        String portToGrammarFolderMappingsString = portToGrammarFolderMappings.toString().substring(1,
                portToGrammarFolderMappings.toString().length() - 1);
        session.setAttribute("runningGrammars", portToGrammarFolderMappingsString.split("\\, "));

        forward = ADMIN_JSP;

    } // Upload (START PAGE)
    else {

        //            HttpSession session = request.getSession(false);
        //            String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //            if (absoluteUnzippedGrammarDir != null) {
        //                // Stop grammar.
        //                runBashScript(path, "./single_grammar_stop.sh", absoluteUnzippedGrammarDir);
        //                // Remove this java port from the list of occupied ports.
        //                TreeMap<String, String> tmpMap = new TreeMap<>();
        //                for(String aJavaPort : portToGrammarFolderMappings.keySet()) {
        //                    String aGrammarDir = portToGrammarFolderMappings.get(aJavaPort);
        //                    if(aGrammarDir.equals(absoluteUnzippedGrammarDir)) {
        //                        // Java port should be removed. So ignore it.
        //                    }
        //                    else {
        //                        tmpMap.put(aJavaPort, absoluteUnzippedGrammarDir);
        //                    }
        //                }
        //                portToGrammarFolderMappings.clear();
        //                portToGrammarFolderMappings = tmpMap;
        //                System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n\n");
        //                
        //            } else {
        //                System.out.println("No grammar to kill.");
        //            }
        forward = UPLOAD_JSP;
    }

    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}

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

@Override
public RepresentationDef getRepresentationDefForMimeType(String mimeType) {
    TreeMap<String, RepresentationDef> map = new TreeMap<String, RepresentationDef>();
    for (RepresentationDef def : representationDefs) {
        if (def.getMIMEType().equals(mimeType)) {
            map.put(def.getName(), def);
        }/*from www .j  av  a 2s  .  c om*/
    }
    if (map.isEmpty()) {
        return null;
    } else {
        return map.firstEntry().getValue();
    }
}

From source file:org.powertac.du.DefaultBrokerServiceTests.java

@Test
public void testConfig() {
    service.setDefaults();//from   ww  w .j a v a2s  . c o  m
    List<String> completedInits = new ArrayList<String>();
    completedInits.add("TariffMarket");

    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("du.defaultBrokerService.consumptionRate", "-0.50");
    map.put("du.defaultBrokerService.productionRate", "0.02");
    map.put("du.defaultBrokerService.initialBidKWh", "1000.0");
    Configuration mapConfig = new MapConfiguration(map);
    config.setConfiguration(mapConfig);
    service.initialize(competition, completedInits);
    assertEquals("correct consumption rate", -0.5, service.getConsumptionRate(), 1e-6);
    assertEquals("correct production rate", 0.02, service.getProductionRate(), 1e-6);
    assertEquals("correct initial kwh", 1000.0, service.getInitialBidKWh(), 1e-6);
}

From source file:emlab.role.investment.InvestInPowerGenerationTechnologiesRole.java

private TreeMap<Integer, Double> calculateSimplePowerPlantInvestmentCashFlow(int depriacationTime,
        int buildingTime, double totalInvestment, double operatingProfit) {
    TreeMap<Integer, Double> investmentCashFlow = new TreeMap<Integer, Double>();
    double equalTotalDownPaymentInstallement = totalInvestment / buildingTime;
    for (int i = 0; i < buildingTime; i++) {
        investmentCashFlow.put(new Integer(i), -equalTotalDownPaymentInstallement);
    }// ww  w . ja  v  a  2s.c o m
    for (int i = buildingTime; i < depriacationTime + buildingTime; i++) {
        investmentCashFlow.put(new Integer(i), operatingProfit);
    }

    return investmentCashFlow;
}

From source file:com.sfs.whichdoctor.dao.ReimbursementDAOImpl.java

/**
 * Load groups./*from  w  w w .j  a  va 2 s.c o m*/
 *
 * @param guid the guid
 *
 * @return the collection< group bean>
 */
private Collection<GroupBean> loadGroups(final int guid) {

    ArrayList<GroupBean> groups = new ArrayList<GroupBean>();

    // Create new SearchBean of type Reimbursement and default values
    SearchResultsBean results = new SearchResultsBean();
    SearchBean groupSearch = this.getSearchDAO().initiate("group", null);
    groupSearch.setLimit(0);

    GroupBean searchCriteria = (GroupBean) groupSearch.getSearchCriteria();
    searchCriteria.setObjectType("Reimbursements");
    ItemBean item = new ItemBean();
    item.setObject2GUID(guid);
    TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>();
    items.put("Reimbursement", item);
    searchCriteria.setItems(items);

    groupSearch.setSearchCriteria(searchCriteria);

    try {
        BuilderBean loadGroup = new BuilderBean();
        loadGroup.setParameter("ITEMS", true);
        loadGroup.setParameter("REFERENCEID", String.valueOf(guid));
        results = this.getSearchDAO().search(groupSearch, loadGroup);
    } catch (WhichDoctorSearchDaoException wdse) {
        dataLogger.error("Error loading groups for reimbursement: " + wdse.getMessage());
    }

    for (Object group : results.getSearchResults()) {
        groups.add((GroupBean) group);
    }
    return groups;
}

From source file:decision_tree_learning.Matrix.java

public void postmodifyMetadata() {
    Iterator<TreeMap<Integer, String>> s_m_enum_to_str = this.m_enum_to_str.iterator();
    for (int i = 0; i < this.m_str_to_enum.size() - 1; i++) { // we don't wanna touch last attribute's metadata
        TreeMap<String, Integer> s_m_str_to_enum = this.m_str_to_enum.get(i);
        int max = Collections.max(s_m_str_to_enum.values());
        s_m_str_to_enum.put("MISSING", max + 1);
        s_m_enum_to_str.next().put(max + 1, "MISSING");
    }/*from   w  w w  . j a  va2 s  . co m*/
}

From source file:io.github.proxyprint.kitchen.controllers.printshops.PrintShopController.java

@ApiOperation(value = "Returns a list of printshops.", notes = "This method returns a list of the nearest printshops.")
@RequestMapping(value = "/printshops/nearest", method = RequestMethod.GET)
public String getNearestPrintShops(WebRequest request) {
    String lat = request.getParameter("latitude");
    String lon = request.getParameter("longitude");

    JsonObject response = new JsonObject();

    if (lat != null && lon != null) {
        Double latitude = Double.parseDouble(lat);
        Double longitude = Double.parseDouble(lon);
        System.out.format("Latitude: %s Longitude: %s\n", latitude, longitude);

        TreeMap<Double, PrintShop> pshops = new TreeMap<>();

        for (PrintShop p : printshops.findAll()) {
            double distance = DistanceCalculator.distance(latitude, longitude, p.getLatitude(),
                    p.getLongitude());// www .jav  a  2  s. c om
            pshops.put(distance, p);
        }
        response.addProperty("success", true);
        response.add("printshops", GSON.toJsonTree((pshops)));
    } else {
        response.addProperty("success", false);
    }
    return GSON.toJson(response);
}

From source file:com.jfolson.hive.serde.RTypedBytesInput.java

/**
 * Reads the map following a <code>Type.MAP</code> code.
 * // w w w.ja v  a 2  s  .  c  om
 * @return the obtained map
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public TreeMap readMap() throws IOException {
    int length = readMapHeader();
    TreeMap result = new TreeMap();
    for (int i = 0; i < length; i++) {
        Object key = read();
        Object value = read();
        result.put(key, value);
    }
    return result;
}

From source file:com.sun.faces.generate.HtmlTaglibGenerator.java

/**
 * @return a SortedMap, where the keys are component-family String
 * entries, and the values are {@link ComponentBean} instances
 * Only include components that do not have a base component type.
 *///from www  .ja  v a  2  s .c  o m
private static SortedMap getComponentFamilyComponentMap() throws IllegalStateException {
    TreeMap result = new TreeMap();
    ComponentBean[] components = fcb.getComponents();
    for (int i = 0, len = components.length; i < len; i++) {
        if (null == (component = components[i])) {
            throw new IllegalStateException("No Components Found");
        }
        if (component.getBaseComponentType() != null) {
            continue;
        }
        String componentFamily = component.getComponentFamily();
        String componentType = component.getComponentType();
        result.put(componentFamily, component);
    }
    return result;
}