Example usage for java.util HashMap put

List of usage examples for java.util HashMap put

Introduction

In this page you can find the example usage for java.util HashMap 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:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);/*from   w  w w  .  ja v  a  2  s  .  c  o  m*/
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

From source file:edu.osu.netmotifs.warswap.ui.GenerateMotifImages.java

public static void main(String[] args) {
    HashMap<Integer, Color> cHash = new HashMap<Integer, Color>();
    cHash.put(0, Color.BLUE);
    cHash.put(2, Color.BLACK);//from w w w .  j  a  va 2 s  .c  o  m
    cHash.put(1, Color.RED);
    try {
        new GenerateMotifImages(cHash,
                "/home/mitra/workspace/uni-workspace/warswap_tool/warswap.subgraphsdddd.OUT", 3,
                "data/htmout.htm").createHtm(1, 0, 10);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.petendi.ethereum.secure.proxy.Application.java

public static void main(String[] args) {

    try {//from  w  w w . j a  v  a  2s  .  c  o  m
        cmdLineResult = new CmdLineResult();
        cmdLineResult.parseArguments(args);
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        System.out.println("Usage:");
        cmdLineResult.printExample();
        System.exit(-1);
        return;
    }

    File workingDirectory = new File(System.getProperty("user.home"));
    if (cmdLineResult.getWorkingDirectory().length() > 0) {
        workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile();
    }

    ArgumentList argumentList = new ArgumentList();
    argumentList.setWorkingDirectory(workingDirectory);
    File certificate = new File(workingDirectory, "seccoco-secured/cert.p12");
    if (certificate.exists()) {
        char[] passwd = null;
        if (cmdLineResult.getPassword() != null) {
            System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!");
            passwd = cmdLineResult.getPassword().toCharArray();
        } else {
            Console console = System.console();
            if (console != null) {
                passwd = console.readPassword("[%s]", "Enter application password:");
            } else {
                System.out.print("No suitable console found for entering password");
                System.exit(-1);
            }
        }
        argumentList.setTokenPassword(passwd);
    }
    try {
        SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList);
        seccoco = seccocoFactory.create();
    } catch (InitializationException e) {
        System.out.println(e.getMessage());
        System.exit(-1);
    }
    try {
        System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl());
        URL url = new URL(cmdLineResult.getUrl());
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        String additionalHeaders = cmdLineResult.getAdditionalHeaders();
        if (additionalHeaders != null) {
            StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyValue = tokenizer.nextToken();
                StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":");
                headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken());
            }
        }
        settings = new Settings(cmdLineResult.isExposeWhisper(), headers);
        jsonRpcHttpClient = new JsonRpcHttpClient(url);
        jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener());

        jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers);
        if (cmdLineResult.isExposeWhisper()) {
            jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers);
        }
        System.out.println("Connection succeeded");
    } catch (Throwable e) {
        System.out.println("Connection failed: " + e.getMessage());
        System.exit(-1);
    }
    SpringApplication app = new SpringApplication(Application.class);
    app.setBanner(new Banner() {
        @Override
        public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
            //send the Spring Boot banner to /dev/null
        }
    });
    app.run(new String[] {});
}

From source file:GetAllConnectedWlanDevices.java

public static void main(String[] args) {
    //Create a new FritzConnection with username and password
    FritzConnection fc = new FritzConnection(ip, user, password);
    try {//from  ww w .jav  a2 s. c om
        //The connection has to be initiated. This will load the tr64desc.xml respectively igddesc.xml 
        //and all the defined Services and Actions. 
        fc.init();
    } catch (ClientProtocolException e2) {
        //Any HTTP related error.
        e2.printStackTrace();
    } catch (IOException e2) {
        //Any Network related error.
        e2.printStackTrace();
    } catch (JAXBException e2) {
        //Any xml violation.
        e2.printStackTrace();
    }

    for (int i = 1; i <= 3; i++) {
        //Get the Service. In this case WLANConfiguration:X 
        Service service = fc.getService("WLANConfiguration:" + i);
        //Get the Action. in this case GetTotalAssociations
        Action action = service.getAction("GetTotalAssociations");
        Response response1 = null;
        try {
            //Execute the action without any In-Parameter.
            response1 = action.execute();
        } catch (UnsupportedOperationException | IOException e1) {

            e1.printStackTrace();
        }
        int deviceCount = -1;
        try {
            //Get the value from the field NewTotalAssociations as an integer. Values can have the Types: String, Integer, Boolean, DateTime and UUID
            deviceCount = response1.getValueAsInteger("NewTotalAssociations");
        } catch (ClassCastException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        System.out.println("WLAN " + i + ":" + deviceCount);
        for (int j = 0; j < deviceCount; j++) {
            //Create a map for the arguments of an action. You have to do this, if the action has IN-Parameters.
            HashMap<String, Object> arguments = new HashMap<String, Object>();
            //Set the argument NewAssociatedDeviceIndex to an integer value.
            arguments.put("NewAssociatedDeviceIndex", j);
            try {
                Response response2 = fc.getService("WLANConfiguration:" + i)
                        .getAction("GetGenericAssociatedDeviceInfo").execute(arguments);
                System.out.println("    " + response2.getData());
            } catch (UnsupportedOperationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}

From source file:com.all.services.ServiceConsole.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from w w  w  .  j  a v  a  2s .  c o  m
        LOG.info("Connecting to JMX service...");
        if (args.length < 2) {
            LOG.error("Incorrect usage of Ultrapeer console.\n\n Args should be 'command password [host]'");
            throw new IllegalArgumentException("Not enough agrugments to run.");
        }
        HashMap env = new HashMap();
        env.put("jmx.remote.credentials", new String[] { "controlRole", args[1] });
        String hostname = args.length > 2 ? args[2] : "";
        JMXConnector jmxc = JMXConnectorFactory
                .connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostname + ":9999/jmxrmi"), env);
        ServiceMonitorMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(),
                new ObjectName("com.all.services:type=ServiceMonitor"), ServiceMonitorMBean.class, true);
        handleCommand(mbeanProxy, args[0]);
        jmxc.close();
        LOG.info("Done.");
    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:minikbextractor.MiniKBextractor.java

/**
 * @param args the command line arguments
 *//* w  w  w . j  av a  2 s  . c o  m*/
public static void main(String[] args) {
    String adomFile = "in/agronomicTaxon.owl";

    ArrayList<Source> sources = new ArrayList();

    SparqlProxy spInAgrovoc = SparqlProxy
            .getSparqlProxy("http://amarger.murloc.fr:8080/Agrovoc2KB_TESTClass_out/");
    HashMap<String, String> limitSpOutAgrovoc = new HashMap<>();
    //limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_5608", "http://amarger.murloc.fr:8080/Agrovoc_mini_Paspalum/");
    limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_148",
            "http://amarger.murloc.fr:8080/Agrovoc_mini_Aegilops/");
    //imitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_5435", "http://amarger.murloc.fr:8080/Agrovoc_mini_Oryza/");
    limitSpOutAgrovoc.put("http://aims.fao.org/aos/agrovoc/c_7950",
            "http://amarger.murloc.fr:8080/Agrovoc_mini_Triticum/");

    String nameAgrovoc = "Agrovoc";

    sources.add(new Source(spInAgrovoc, nameAgrovoc, limitSpOutAgrovoc, adomFile));

    SparqlProxy spInTaxRef = SparqlProxy.getSparqlProxy("http://amarger.murloc.fr:8080/TaxRef2RKB_out_TEST/");
    HashMap<String, String> limitSpOutTaxRef = new HashMap<>();
    //limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/195870", "http://amarger.murloc.fr:8080/TaxRef_mini_Paspalum/");
    limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/188834",
            "http://amarger.murloc.fr:8080/TaxRef_mini_Aegilops/");
    //limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/195564", "http://amarger.murloc.fr:8080/TaxRef_mini_Oryza/");
    limitSpOutTaxRef.put("http://inpn.mnhn.fr/espece/cd_nom/198676",
            "http://amarger.murloc.fr:8080/TaxRef_mini_Triticum/");
    //String limitUriTaxRef = "http://inpn.mnhn.fr/espece/cd_nom/187444"; //Poaceae
    String nameTaxRef = "TaxRef   ";

    sources.add(new Source(spInTaxRef, nameTaxRef, limitSpOutTaxRef, adomFile));

    SparqlProxy spInNCBI = SparqlProxy.getSparqlProxy("http://amarger.murloc.fr:8080/Ncbi2RKB_out/");
    HashMap<String, String> limitSpOutNCBI = new HashMap<>();
    //limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=147271", "http://amarger.murloc.fr:8080/NCBI_mini_Paspalum/");
    limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4480",
            "http://amarger.murloc.fr:8080/NCBI_mini_Aegilops/");
    //limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4527", "http://amarger.murloc.fr:8080/NCBI_mini_Oryza/");
    limitSpOutNCBI.put("http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=4564",
            "http://amarger.murloc.fr:8080/NCBI_mini_Triticum/");
    String nameNCBI = "NCBI";

    sources.add(new Source(spInNCBI, nameNCBI, limitSpOutNCBI, adomFile));

    for (Source s : sources) {
        //System.out.println(s.getStatUnderLimit());
        s.exportAllSubRKB();
        System.out.println("------------------------------------");
    }
    System.exit(0);

}

From source file:TestRedundantObjectPool.java

 public static void main(String args[]) throws Exception {

   SoftReferenceObjectPool pool =// w w w  .j a  va 2 s . c om
     new SoftReferenceObjectPool(new EmployeeFactory(), 5);

   try{

      System.err.println("Number of employees in pool: " + pool.getNumIdle());

      Employee employee = (Employee)pool.borrowObject();

      System.err.println("Borrowed Employee: " + employee);

      employee.doWork();

      pool.returnObject(employee);

      // employee = null;

      HashMap map = new HashMap();

      System.err.println("Running memory intensive operation");
      for(int i = 0; i < 1000000; i++) {
         map.put(new Integer(i), new String("Fred Flintstone" + i));
      }

   }catch(OutOfMemoryError e) {
      System.err.println("Borrowed employee after OutOfMemory: " +
        pool.borrowObject());
      System.err.println("Error: "  + e);
   }
}

From source file:com.bt.aloha.batchtest.Chart.java

public static void main(String args[]) throws Exception {
    try {//  w  w  w.java2  s  . c  o  m
        BasicConfigurator.configure();
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "batchTestApplicationContext.xml");
        PerformanceMeasurmentDao dao = (PerformanceMeasurmentDao) applicationContext
                .getBean("performanceMeasurementDaoBean");
        List<Metrics> list1 = dao.findMetricsByRunId(1);
        List<Metrics> list2 = dao.findMetricsByRunId(2);
        List<Metrics> list3 = dao.findMetricsByRunId(3);
        List<Metrics> list4 = dao.findMetricsByRunId(4);
        List<Metrics> list5 = dao.findMetricsByRunId(5);
        List<Metrics> list6 = dao.findMetricsByRunId(6);
        List<Metrics> list7 = dao.findMetricsByRunId(7);
        List<Metrics> list8 = dao.findMetricsByRunId(8);
        List<Metrics> list9 = dao.findMetricsByRunId(9);
        List<Metrics> list10 = dao.findMetricsByRunId(10);
        HashMap<Long, List<Metrics>> map = new HashMap<Long, List<Metrics>>();
        map.put(1L, list1);
        Chart c = new Chart(map);
        c.saveChart(new File("unitPerSecond.jpg"), "Run with standard deviation", "threads",
                "units per second");
        map.put(2L, list2);
        map.put(3L, list3);
        map.put(4L, list4);
        map.put(5L, list5);
        map.put(6L, list6);
        map.put(7L, list7);
        map.put(8L, list8);
        map.put(9L, list9);
        map.put(10L, list10);
        c = new Chart(map);
        c.saveCombinedChart(new File("unitPerSecond-historical.jpg"), "Runs Per Second", "threads",
                "runs per second", "Standard Deviation", "threads", "std. deviation");
    } catch (RuntimeException e) {
        log.error(e);
    } finally {
        System.exit(0);
    }
}

From source file:org.ala.harvester.IdentifyLifeHarvester.java

/**
 * @param args//from  ww  w  . j  a v a 2s  . c  o  m
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.print("Usage: ");
        System.out.print("<infosourceId>");
        System.out.println();
        System.out.println("infosourceId e.g. 1036");
        System.exit(1);
    }

    String[] locations = { "classpath*:spring.xml" };
    ApplicationContext context = new ClassPathXmlApplicationContext(locations);
    IdentifyLifeHarvester identifyLifeHarvester = context.getBean(IdentifyLifeHarvester.class);
    HashMap<String, String> connectParams = new HashMap<String, String>();
    connectParams.put(SEARCH_END_POINT_ATTR_NAME, "http://www.identifylife.org:8001/Keys/Search");
    connectParams.put(KEY_END_POINT_ATTR_NAME, "http://www.identifylife.org:8001/Keys");
    connectParams.put(KEY_FIELD_ATTR_NAME, SEARCH_FIELD_TAXO_SCOPE);
    identifyLifeHarvester.setConnectionParams(connectParams);
    identifyLifeHarvester.setDocumentMapper(new IdentifyLifeDocumentMapper());
    identifyLifeHarvester.start(Integer.parseInt(args[0]), 500);
    System.exit(0);
}

From source file:Main.java

public static void main(String[] args) throws IllegalAccessException {
    Class clazz = Color.class;
    Field[] colorFields = clazz.getDeclaredFields();

    HashMap<String, Color> singleColors = new HashMap<String, Color>();
    for (Field cf : colorFields) {
        int modifiers = cf.getModifiers();
        if (!Modifier.isPublic(modifiers))
            continue;

        Color c = (Color) cf.get(null);
        if (!singleColors.values().contains(c))
            singleColors.put(cf.getName(), c);
    }//from w ww .j  a va  2  s .co  m

    for (String k : singleColors.keySet()) {
        System.out.println(k + ": " + singleColors.get(k));
    }
}