Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java

/**
 * Executes directory request/*from w w w.ja  va  2s .c om*/
 * @param context
 * @throws java.lang.Throwable
 */
private void executeRequest(OperationContext context) throws java.lang.Throwable {

    long t1 = System.currentTimeMillis();
    DirectoryParams params = context.getRequestOptions().getDirectoryOptions();

    try {

        String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration()
                .getParameters().getValue("openls.directory");

        // HashMap<String,Point> poiLocations = params.getPoiLocations(); 

        // TODO
        /*Point location = null;
        Set<String> keys = poiLocations.keySet();
         Iterator<String> iter = keys.iterator();
         while(iter.hasNext()){
            String key = iter.next();
            location = (Point) poiLocations.get(key);
         }*/

        // MAKE THE POI REQUEST
        HashMap<String, String> poiProperties = params.getPoiProperties();
        Set<String> keys = poiProperties.keySet();
        Iterator<String> iter = keys.iterator();
        StringBuffer filter = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            QueryFilter queryFilter = new QueryFilter(key, poiProperties.get(key));
            filter.append(makePOIRequest(queryFilter));
        }

        // SUBMIT THE REQUEST
        String sUrl = srvCfg + "/query?" + filter.toString();
        LOGGER.info("REQUEST=\n" + sUrl);

        URL url = new URL(sUrl);
        URLConnection conn = url.openConnection();

        // Get the response
        String line = "";
        String sResponse = "";

        InputStream is = conn.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader rd = new BufferedReader(isr);
        while ((line = rd.readLine()) != null) {
            sResponse += line;
        }
        rd.close();
        url = null;

        parsePOIResponse(sResponse, params);

    } catch (Exception p_e) {
        LOGGER.severe("Throwing exception" + p_e.getMessage());
        throw p_e;
    } finally {
        long t2 = System.currentTimeMillis();
        LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service");
    }
}

From source file:edu.utexas.cs.tactex.BrokerUtilsTest.java

/**
 * as assert function I added that compares hash maps
 * @param msg /* ww  w.java  2  s  .  c o m*/
 * 
 * @param twoLevelMap
 * @param expectedMap
 * @throws ArrayComparisonFailure
 */
private <K1, K2, V> void myAssertMapsEqual(String msg, HashMap<K1, HashMap<K2, V>> expectedMap,
        HashMap<K1, HashMap<K2, V>> revertedTwoLevelMap) throws ArrayComparisonFailure {

    // compare key1
    assertTrue(msg, expectedMap.keySet().equals(revertedTwoLevelMap.keySet()));

    // for each key1, compare all <key2, value>s
    for (K1 key1 : expectedMap.keySet()) {

        assertTrue(msg + " comparing key2",
                expectedMap.get(key1).keySet().equals(revertedTwoLevelMap.get(key1).keySet()));

        for (K2 key2 : expectedMap.get(key1).keySet()) {
            assertEquals(msg + " comparing values", expectedMap.get(key1).get(key2),
                    revertedTwoLevelMap.get(key1).get(key2));
        }
    }
}

From source file:com.example.diego.inicio2.Conexion.MYSQL_Request.java

/**
 * Set the request update//from  ww  w  . j  a  v a2 s  .c  o  m
 */
public void setRequestUpdate(String table, HashMap<String, String> values, String where) {
    String tempRequest = "UPDATE " + table + " SET ";

    Iterator mIterator = values.keySet().iterator();
    while (mIterator.hasNext()) {
        String key = (String) mIterator.next();
        String value = (String) values.get(key);
        if (mIterator.hasNext())
            tempRequest += key + " = '" + value + "', ";
        else
            tempRequest += key + " = '" + value + "'";
    }

    tempRequest += " WHERE " + where;

    this.request = tempRequest;
}

From source file:net.sf.mpaxs.spi.server.HostRegister.java

/**
 * Shutdown the host register./* w w w.j  av a  2s .  c  om*/
 *
 * @param timeout  maximum time to wait before hard shutdown
 * @param timeUnit time unit for timeout
 * @throws InterruptedException
 */
public void shutdown(long timeout, TimeUnit timeUnit) throws InterruptedException {
    HashMap<UUID, Host> hosts = getHosts();
    try {
        for (Iterator<UUID> i = hosts.keySet().iterator(); i.hasNext();) {
            Host host = hosts.get(i.next());
            IComputeHost remRef;
            try {

                remRef = (IComputeHost) Naming
                        .lookup("//" + host.getIP() + ":" + settings.getLocalPort() + "/" + host.getName());
                remRef.masterServerShuttingDown(
                        UUID.fromString(settings.getString(ConfigurationKeys.KEY_AUTH_TOKEN)));

            } catch (NotBoundException ex) {
                EventLogger.getInstance().getLogger().log(Level.SEVERE, "Not Bound Exception!", ex);
            } catch (MalformedURLException ex) {
                EventLogger.getInstance().getLogger().log(Level.SEVERE, "MalformedURLException!", ex);
            } catch (RemoteException ex) {
                EventLogger.getInstance().getLogger().log(Level.SEVERE, "RemoteException!", ex);
            }
        }
    } catch (Exception e) {
        EventLogger.getInstance().getLogger().log(Level.SEVERE, "Exception while shutting down hosts!", e);
        throw new RuntimeException(e);
    } finally {
        //we need to shut down the executor and event service
        //we can not throw the interrupted exceptions however, since
        //that would
        try {
            EventLogger.getInstance().getLogger().log(Level.INFO,
                    "Shutting down host register executor service");
            executorService.shutdown();
            if (!executorService.awaitTermination(timeout, timeUnit)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException ie) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        } finally {
            try {
                EventLogger.getInstance().getLogger().log(Level.INFO,
                        "Shutting down host register event service");
                eventService.shutdown();
                if (!eventService.awaitTermination(timeout, timeUnit)) {
                    eventService.shutdownNow();
                }
            } catch (InterruptedException ie) {
                eventService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}

From source file:com.francisli.processing.http.HttpClient.java

/**
 * @exclude/*from w  w w .j  a v a 2 s  .  com*/
 */
public void pre() throws Throwable {
    HashMap<HttpRequest, HttpResponse> requestMapClone;
    synchronized (this) {
        requestMapClone = (HashMap<HttpRequest, HttpResponse>) requestMap.clone();
    }
    for (HttpRequest request : requestMapClone.keySet()) {
        HttpResponse response = requestMapClone.get(request);
        try {
            callbackMethod.invoke(parent, new Object[] { request, response });
        } catch (IllegalAccessException ex) {

        } catch (IllegalArgumentException ex) {

        } catch (InvocationTargetException ex) {
            throw ex.getCause();
        }
        synchronized (this) {
            requestMap.remove(request);
        }
    }
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context//from  w w w. ja  va 2  s .co  m
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:com.mobileman.moments.core.security.UserSecurityService.java

private void sanitizeUserCacheInfo(UserCacheInfo userCacheInfo) {
    if (false) {//from ww w.  ja v a 2  s.  com
        HashMap<String, Date> tokens = userCacheInfo.getTokens();
        if (tokens.size() > 10) {
            tokens.clear(); // Protection against too many devices
        }
        // remove older items
        Date now = DateUtils.addSeconds(new Date(), -60 * 10);
        HashSet<String> ks = new HashSet<String>(tokens.keySet());
        for (String key : ks) {
            Date d = tokens.get(key);
            if (now.after(d)) {
                tokens.remove(key);
            }
        }
    }
}

From source file:edu.umn.cs.spatialHadoop.util.TemporalIndexManager.java

private Path[] convertFromMapToArray(HashMap<String, Boolean> pathsMap, Path homePath) {
    ArrayList<Path> pathsArrayList = new ArrayList<Path>();
    int count = 0;
    for (String pathsMapKey : pathsMap.keySet()) {
        boolean pathsMapValue = pathsMap.get(pathsMapKey);
        if (pathsMapValue) {
            pathsArrayList.add(new Path(homePath.toString() + "/" + pathsMapKey));
            count++;// w  ww  .jav  a 2s. c o m
        }
    }

    Path[] pathsArr = new Path[count];
    for (int i = 0; i < count; i++) {
        pathsArr[i] = pathsArrayList.get(i);
    }
    return pathsArr;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.QueryTests.java

@SuppressWarnings("unchecked")
@Test/*  w w w .ja va 2s  . c  o  m*/
public void validTypeQueryReturnsOnlyTypeJson() throws IOException, SAXException, ParserConfigurationException,
        XPathExpressionException, JSONException {
    String query = getQueryBase();
    query = query + "oslc_cm.query=" + queryProperty
            + URLEncoder.encode("=\"" + queryPropertyValue + "\"", "UTF-8") + "&"
            + URLEncoder.encode("oslc_cm.properties", "UTF-8") + "=" + queryProperty;

    Iterator<HashMap<String, String>> iter = processJSONQuery(query).iterator();
    while (iter.hasNext()) {
        HashMap<String, String> lhm = iter.next();
        assertTrue(lhm.keySet().contains(queryProperty));
        assertTrue(lhm.get(queryProperty).equals(queryPropertyValue));
    }
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.QueryTests.java

@SuppressWarnings("unchecked")
@Test//from   w  w w  . j  a  v  a2s  . c  o  m
public void validLessThanQueryContainsExpectedDefectsJson() throws IOException, JSONException {
    String query = getQueryBase();
    query = query + "oslc_cm.query=" + queryComparisonProperty
            + URLEncoder.encode("<=\"" + queryComparisonValue + "\"", "UTF-8") + "&"
            + URLEncoder.encode("oslc_cm.properties", "UTF-8") + "=" + queryComparisonProperty;

    //Get response in json
    Iterator<HashMap<String, String>> iter = processJSONQuery(query).iterator();
    while (iter.hasNext()) {
        HashMap<String, String> lhm = iter.next();
        assertTrue(lhm.keySet().contains(queryComparisonProperty));
        // assertTrue(lhm.get(queryComparisonProperty).compareTo(queryComparisonValue) <= 0);
    }
}