Example usage for java.util Map get

List of usage examples for java.util Map get

Introduction

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

Prototype

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:org.mitre.mpf.wfm.rest_client.RegisterComponent.java

public static void main(String[] args) {

    String filePath = "/home/mpf/mpf/trunk/java-hello-world/src/main/resources/HelloWorldComponent.json";
    //"/home/mpf/mpf/trunk/extraction/hello/cpp/src/helloComponent.json";
    String url = "http://localhost:8080/workflow-manager/rest/component/registerViaFile";
    final String credentials = "Basic bXBmOm1wZjEyMw==";

    Map<String, String> params = new HashMap<String, String>();

    System.out.println("Starting rest-client!");

    //not necessary for localhost
    //System.setProperty("http.proxyHost","gatekeeper.mitre.org");
    //System.setProperty("http.proxyPort","80");

    RequestInterceptor authorize = new RequestInterceptor() {
        @Override/*from ww w .  j  a  v a  2s . c  om*/
        public void intercept(HttpRequestBase request) {
            request.addHeader("Authorization", credentials);
        }
    };
    RestClient client = RestClient.builder().requestInterceptor(authorize).build();

    if (args.length > 0) {
        filePath = args[0];
        System.out.println("args[0] = " + args[0]);
    }

    params.put("filePath", filePath);
    Map<String, String> stringVal = null;
    try {
        stringVal = client.get(url, params, Map.class);
    } catch (RestClientException e) {
        log.error("RestClientException occurred");
        e.printStackTrace();
    } catch (IOException e) {
        log.error("IOException occurred");
        e.printStackTrace();
    }
    System.out.println(stringVal.get("message"));
}

From source file:com.yahoo.athenz.example.instance.InstanceClientRegister.java

public static void main(String[] args) throws MalformedURLException, IOException {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain").toLowerCase();
    String serviceName = cmd.getOptionValue("service").toLowerCase();
    String provider = cmd.getOptionValue("provider").toLowerCase();
    String instance = cmd.getOptionValue("instance");
    String dnsSuffix = cmd.getOptionValue("dnssuffix");
    String providerKeyPath = cmd.getOptionValue("providerkey");
    String providerKeyId = cmd.getOptionValue("providerkeyid");
    String instanceKeyPath = cmd.getOptionValue("instancekey");
    String ztsUrl = cmd.getOptionValue("ztsurl");

    // get our configured private key

    PrivateKey providerKey = Crypto.loadPrivateKey(new File(providerKeyPath));

    // first we are going to generate our attestation data
    // which we are going to use jwt. ZTS Server will send
    // this object to the specified provider for validation

    String compactJws = Jwts.builder().setSubject(domainName + "." + serviceName).setIssuer(provider)
            .setAudience("zts").setId(instance)
            .setExpiration(/*from   w ww .  j a v  a 2 s .c om*/
                    new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES)))
            .setHeaderParam("keyId", providerKeyId).signWith(SignatureAlgorithm.RS256, providerKey).compact();

    System.out.println("JWS: \n" + compactJws + "\n");

    // now we need to generate our CSR so we can get
    // a TLS certificate for our instance

    PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
    String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);

    if (csr == null) {
        System.err.println("Unable to generate CSR for instance");
        System.exit(1);
    }
    System.out.println("CSR: \n" + csr + "\n");

    // now let's generate our instance register object that will be sent
    // to the ZTS Server

    InstanceRegisterInformation info = new InstanceRegisterInformation().setAttestationData(compactJws)
            .setDomain(domainName).setService(serviceName).setProvider(provider).setToken(true).setCsr(csr);

    // now contact zts server to request identity for instance

    InstanceIdentity identity = null;
    Map<String, List<String>> responseHeaders = new HashMap<>();
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
        identity = ztsClient.postInstanceRegisterInformation(info, responseHeaders);
    } catch (ZTSClientException ex) {
        System.out.println("Unable to register instance: " + ex.getMessage());
        System.exit(2);
    }

    System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
    Map<String, String> attrs = identity.getAttributes();
    if (attrs != null) {
        System.out.println("Provider Attributes:");
        for (String key : attrs.keySet()) {
            System.out.println("\t" + key + ": " + attrs.get(key));
        }
    }
}

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  va2  s .  co 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:Main.java

public static final void main(String[] ignored) {
    Map<Integer, List<String>> mapOfIntStrs = new HashMap<Integer, List<String>>();

    add(mapOfIntStrs, 1, "one");
    add(mapOfIntStrs, 1, "two");
    add(mapOfIntStrs, 1, "three");
    add(mapOfIntStrs, 2, "four");
    add(mapOfIntStrs, 2, "five");
    add(mapOfIntStrs, 3, "six");
    add(mapOfIntStrs, 3, "seven");

    Set<Integer> keySet = mapOfIntStrs.keySet();

    for (int i : keySet) {
        List<String> strList = mapOfIntStrs.get(i);
        System.out.println(i);/*from w w w.  j av  a  2 s.  co m*/
        for (String s : strList) {
            System.out.println("  " + s);
        }
    }
}

From source file:com.google.oacurl.Fetch.java

public static void main(String[] args) throws Exception {
    FetchOptions options = new FetchOptions();
    CommandLine line = options.parse(args);
    args = line.getArgs();//  w  w  w.  j  av a 2  s. co  m

    if (options.isHelp()) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(0);
    }

    if (args.length != 1) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(-1);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isVerbose()) {
        LoggingConfig.enableWireLog();
    }

    String url = args[0];

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao();
    AccessorDao accessorDao = new AccessorDao();

    Properties loginProperties = null;
    try {
        loginProperties = new PropertiesProvider(options.getLoginFileName()).get();
    } catch (FileNotFoundException e) {
        System.err.println(".oacurl.properties file not found in homedir");
        System.err.println("Make sure you've run oacurl-login first!");
        System.exit(-1);
    }

    OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider();
    OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider);
    OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer);

    OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL));

    OAuthVersion version = (loginProperties.containsKey("oauthVersion"))
            ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion"))
            : OAuthVersion.V1;

    OAuthEngine engine;
    switch (version) {
    case V1:
        engine = new V1OAuthEngine();
        break;
    case V2:
        engine = new V2OAuthEngine();
        break;
    case WRAP:
        engine = new WrapOAuthEngine();
        break;
    default:
        throw new IllegalArgumentException("Unknown version: " + version);
    }

    try {
        OAuthMessage request;

        List<Entry<String, String>> related = options.getRelated();

        Method method = options.getMethod();
        if (method == Method.POST || method == Method.PUT) {
            InputStream bodyStream;
            if (related != null) {
                bodyStream = new MultipartRelatedInputStream(related);
            } else if (options.getFile() != null) {
                bodyStream = new FileInputStream(options.getFile());
            } else {
                bodyStream = System.in;
            }
            request = newRequestMessage(accessor, method, url, bodyStream, engine);
            request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType()));
        } else {
            request = newRequestMessage(accessor, method, url, null, engine);
        }

        List<Parameter> headers = options.getHeaders();
        addHeadersToRequest(request, headers);

        HttpResponseMessage httpResponse;
        if (version == OAuthVersion.V1) {
            OAuthResponseMessage response;
            response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
            httpResponse = response.getHttpResponse();
        } else {
            HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL),
                    request.getBodyAsStream());
            httpRequest.headers.addAll(request.getHeaders());
            httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters());
            httpResponse = HttpMessageDecoder.decode(httpResponse);
        }

        System.err.flush();

        if (options.isInclude()) {
            Map<String, Object> dump = new HashMap<String, Object>();
            httpResponse.dump(dump);
            System.out.print(dump.get(HttpMessage.RESPONSE));
        }

        // Dump the bytes in the response's encoding.
        InputStream bodyStream = httpResponse.getBody();
        byte[] buf = new byte[1024];
        int count;
        while ((count = bodyStream.read(buf)) > -1) {
            System.out.write(buf, 0, count);
        }
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    }
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.W2VDatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *//*from  ww w  .j  ava 2  s .  co m*/
public static void main(String[] args) {
    CommandLine cmd = ESADatalessAnnotator.getCMDOpts(args);

    ResourceManager rm;

    try {
        String configFile = cmd.getOptionValue("config", "config/project.properties");
        ResourceManager nonDefaultRm = new ResourceManager(configFile);

        rm = new W2VDatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new W2VDatalessConfigurator().getDefaultConfig();
    }

    String testFile = cmd.getOptionValue("testFile", "data/graphicsTestDocument.txt");

    StringBuilder sb = new StringBuilder();

    String line;

    try (BufferedReader br = new BufferedReader(new FileReader(new File(testFile)))) {
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(" ");
        }

        String text = sb.toString().trim();

        TokenizerTextAnnotationBuilder taBuilder = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
        TextAnnotation ta = taBuilder.createTextAnnotation(text);

        W2VDatalessAnnotator datalessAnnotator = new W2VDatalessAnnotator(rm);
        datalessAnnotator.addView(ta);

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_W2V).getConstituents();

        System.out.println("Predicted LabelIDs:");

        for (Constituent annot : annots) {
            System.out.println(annot.getLabel());
        }

        Map<String, String> labelNameMap = DatalessAnnotatorUtils
                .getLabelNameMap(rm.getString(DatalessConfigurator.LabelName_Path.key));

        System.out.println("Predicted Labels:");

        for (Constituent annot : annots) {
            System.out.println(labelNameMap.get(annot.getLabel()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("Test File not found at " + testFile + " ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    }
}

From source file:MainClass.java

public static void main(String[] argv) {
    Map map = new MyMap();

    map.put("Adobe", "Mountain View, CA");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("IBM", "White Plains, NY");

    String queryString = "Google";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) map.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();//from  w  ww.j av a 2  s  . c  o  m

    Iterator k = map.keySet().iterator();
    while (k.hasNext()) {
        String key = (String) k.next();
        System.out.println("Key " + key + "; Value " + (String) map.get(key));
    }

    Set es = map.entrySet();
    System.out.println("entrySet() returns " + es.size() + " Map.Entry's");
}

From source file:HashMapExample.java

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<Integer, String>();

    map.put(new Integer(1), "One");
    map.put(new Integer(2), "Two");
    map.put(new Integer(3), "Three");
    map.put(new Integer(4), "Four");
    map.put(new Integer(5), "Five");

    System.out.println("Map Values Before: ");
    Set keys = map.keySet();/*from  w w  w .j  a va 2 s  .  c  om*/
    for (Iterator i = keys.iterator(); i.hasNext();) {
        Integer key = (Integer) i.next();
        String value = (String) map.get(key);
        System.out.println(key + " = " + value);
    }

    System.out.println("\nRemove element with key 6");
    map.remove(new Integer(6));

    System.out.println("\nMap Values After: ");
    keys = map.keySet();
    for (Iterator i = keys.iterator(); i.hasNext();) {
        Integer key = (Integer) i.next();
        String value = (String) map.get(key);
        System.out.println(key + " = " + value);
    }
}

From source file:eu.europeana.solr.SimpleCollectionSolrInstance.java

public static void main(String[] args) throws SolrServerException, IOException {
    SimpleCollectionSolrInstance tester = new SimpleCollectionSolrInstance();
    tester.setSolrdir(new File(new File(new File(new File("src"), "test"), "resources"), "solr/" + CORE1));

    SolrQuery q = new SolrQuery("leonardo");
    q.set("debugQuery", "on");
    q.set("defType", "bm25f");

    q.setRows(10); // don't actually request any data

    QueryResponse qr = tester.query(q);/* w  w w  .j a v  a 2 s .c  o m*/
    Map<String, String> explainmap = qr.getExplainMap();
    System.out.println("results " + qr.getResults().getNumFound());
    for (SolrDocument doc : qr.getResults()) {
        System.out.println("Title: " + doc.getFieldValue("title"));
        System.out.println("Expl: " + explainmap.get(doc.getFieldValue("europeana_id")));
    }

    tester.close();
}

From source file:com.zimbra.cs.mailbox.Metadata.java

public static void main(String[] args) throws MailServiceException {
    String encoded = "d1:ai1e4:aclmd1:gld1:ei0e1:g36:474b7021-cef6-469d-b5fb-54c96117efd11:ri1e1:ti1eee2:gei0e2:iei0ee5:mdveri4e4:mseqi628e2:szi7596456e4:unxti744e1:vi10e2:vti5ee";
    Metadata meta = new Metadata(encoded);
    Map<String, ?> map = meta.asMap();
    for (String key : map.keySet()) {
        System.out.println("key: " + key + " value: " + map.get(key));
    }//from w w  w . ja va  2 s .c  om

}