Example usage for java.util Map containsKey

List of usage examples for java.util Map containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.saltyrtc.client.helpers.MessageReader.java

/**
 * Read MessagePack bytes, return a Message subclass instance.
 * @param bytes Messagepack bytes./*  w w w  .  jav a2 s.c o  m*/
 * @param taskTypes List of message types supported by task.
 * @return Message subclass instance.
 * @throws SerializationError Thrown if deserialization fails.
 * @throws ValidationError Thrown if message can be deserialized but is invalid.
 */
public static Message read(byte[] bytes, List<String> taskTypes) throws SerializationError, ValidationError {
    // Unpack data into map
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    Map<String, Object> map;
    try {
        map = objectMapper.readValue(bytes, new TypeReference<Map<String, Object>>() {
        });
    } catch (IOException e) {
        throw new SerializationError("Deserialization failed", e);
    }

    // Get type value
    if (!map.containsKey("type")) {
        throw new SerializationError("Message does not contain a type field");
    }
    Object typeObj = map.get("type");
    if (!(typeObj instanceof String)) {
        throw new SerializationError("Message type must be a string");
    }
    String type = (String) typeObj;

    // Dispatch message instantiation
    switch (type) {
    case "server-hello":
        return new ServerHello(map);
    case "client-hello":
        return new ClientHello(map);
    case "server-auth":
        if (map.containsKey("initiator_connected")) {
            return new ResponderServerAuth(map);
        } else if (map.containsKey("responders")) {
            return new InitiatorServerAuth(map);
        }
        throw new ValidationError("Invalid server-auth message");
    case "client-auth":
        return new ClientAuth(map);
    case "new-initiator":
        return new NewInitiator(map);
    case "new-responder":
        return new NewResponder(map);
    case "drop-responder":
        return new DropResponder(map);
    case "send-error":
        return new SendError(map);
    case "token":
        return new Token(map);
    case "key":
        return new Key(map);
    case "auth":
        if (map.containsKey("task")) {
            return new InitiatorAuth(map);
        } else if (map.containsKey("tasks")) {
            return new ResponderAuth(map);
        }
        throw new ValidationError("Invalid auth message");
    case "close":
        return new Close(map);
    case "application":
        return new Application(map);
    default:
        if (taskTypes.contains(type)) {
            return new TaskMessage(type, map);
        }
        throw new ValidationError("Unknown message type: " + type);
    }
}

From source file:net.dmulloy2.autocraft.util.BlockStates.java

/**
 * Applies serialized data from {@link #serialize(BlockState)} back to a
 * BlockState.//from   w ww. jav  a2  s  .c  om
 * 
 * @param state State to apply data to
 * @param values Data to apply
 */
public static void deserialize(BlockState state, Map<String, Object> values) {
    for (Method method : ReflectionUtil.getMethods(state.getClass())) {
        try {
            String name = method.getName();
            if (name.startsWith("set") && method.getParameterTypes().length == 1) {
                name = name.substring(3, name.length());
                if (values.containsKey(name)) {
                    method.invoke(state, values.get(name));
                }
            }
        } catch (Throwable ex) {
        }
    }
}

From source file:org.jsharkey.sky.WebserviceHelper.java

/**
 * Retrieve a specific {@link Forecast} object from the given {@link Map}
 * structure. If the {@link Forecast} doesn't exist, it's created and
 * returned./*from  w  w w . j  a  va  2 s .  c o m*/
 */
private static Forecast getForecast(Map<String, List<Forecast>> forecasts, String layout, int index) {
    if (!forecasts.containsKey(layout)) {
        forecasts.put(layout, new ArrayList<Forecast>());
    }
    List<Forecast> layoutSpecific = forecasts.get(layout);

    while (index >= layoutSpecific.size()) {
        layoutSpecific.add(new Forecast());
    }
    return layoutSpecific.get(index);
}

From source file:Main.java

/**
 * Removes the value from the set of values mapped by key. If this value was the last value in the set of values
 * mapped by key, the complete key/values entry is removed.
 * /* ww  w .j  av a2s  .  com*/
 * @param key
 *            The key for which to remove a value.
 * @param value
 *            The value for which to remove the key.
 * @param map
 *            The object that maps the key to a set of values, on which the operation should occur.
 */
public static <K, V> void deleteAndRemove(final K key, final V value, final Map<K, Set<V>> map) {
    if (key == null) {
        throw new IllegalArgumentException("Argument 'key' cannot be null.");
    }
    if (value == null) {
        throw new IllegalArgumentException("Argument 'value' cannot be null.");
    }
    if (map == null) {
        throw new IllegalArgumentException("Argument 'map' cannot be null.");
    }

    if (map.isEmpty() || !map.containsKey(key)) {
        return;
    }

    final Set<V> values = map.get(key);
    values.remove(value);

    if (values.isEmpty()) {
        map.remove(key);
    }
}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

public static Map<String, String> getTunnelServiceInfo(CloudFoundryClient client, String serviceName) {
    String urlToUse = getTunnelUri(client) + "/services/" + serviceName;
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", getTunnelAuth(client));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<String> response = restTemplate.exchange(urlToUse, HttpMethod.GET, requestEntity, String.class);
    String json = response.getBody().trim();
    Map<String, String> svcInfo = new HashMap<String, String>();
    try {/*from w  w w . ja v a 2s.co  m*/
        svcInfo = convertJsonToMap(json);
    } catch (IOException e) {
        return new HashMap<String, String>();
    }
    if (svcInfo.containsKey("url")) {
        String svcUrl = svcInfo.get("url");
        try {
            URI uri = new URI(svcUrl);
            String[] userInfo;
            if (uri.getUserInfo().contains(":")) {
                userInfo = uri.getUserInfo().split(":");
            } else {
                userInfo = new String[2];
                userInfo[0] = uri.getUserInfo();
                userInfo[1] = "";
            }
            svcInfo.put("user", userInfo[0]);
            svcInfo.put("username", userInfo[0]);
            svcInfo.put("password", userInfo[1]);
            svcInfo.put("host", uri.getHost());
            svcInfo.put("hostname", uri.getHost());
            svcInfo.put("port", "" + uri.getPort());
            svcInfo.put("path", (uri.getPath().startsWith("/") ? uri.getPath().substring(1) : uri.getPath()));
            svcInfo.put("vhost", svcInfo.get("path"));
        } catch (URISyntaxException e) {
        }
    }
    return svcInfo;
}

From source file:com.thinkbiganalytics.feedmgr.util.ImportUtil.java

public static void addToImportOptionsSensitiveProperties(ImportOptions importOptions,
        List<NifiProperty> sensitiveProperties, ImportComponent component) {
    ImportComponentOption option = importOptions.findImportComponentOption(component);
    if (option.getProperties().isEmpty()) {
        option.setProperties(sensitiveProperties.stream().map(p -> new ImportProperty(p.getProcessorName(),
                p.getProcessorId(), p.getKey(), "", p.getProcessorType())).collect(Collectors.toList()));
    } else {//from  w  w w  .  ja va2  s  .co m
        //only add in those that are unique
        Map<String, ImportProperty> propertyMap = option.getProperties().stream()
                .collect(Collectors.toMap(p -> p.getProcessorNameTypeKey(), p -> p));
        sensitiveProperties.stream()
                .filter(nifiProperty -> !propertyMap.containsKey(nifiProperty.getProcessorNameTypeKey()))
                .forEach(p -> {
                    option.getProperties().add(new ImportProperty(p.getProcessorName(), p.getProcessorId(),
                            p.getKey(), "", p.getProcessorType()));
                });
    }
}

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Establishes a connection to the database
 * // www  .  j  av  a 2  s  .  co  m
 * @return the established connection
 * 
 * @throws Exception
 *          a custom exception thrown if no postgresql service URL was found
 */
public static Connection getConnection() throws Exception {
    Map<String, String> env = System.getenv();

    if (env.containsKey("VCAP_SERVICES")) {
        // we are running on cloud foundry, let's grab the service details from vcap_services
        JSONParser parser = new JSONParser();
        JSONObject vcap = (JSONObject) parser.parse(env.get("VCAP_SERVICES"));
        JSONObject service = null;

        // We don't know exactly what the service is called, but it will contain "postgresql"
        for (Object key : vcap.keySet()) {
            String keyStr = (String) key;
            if (keyStr.toLowerCase().contains("postgresql")) {
                service = (JSONObject) ((JSONArray) vcap.get(keyStr)).get(0);
                break;
            }
        }

        if (service != null) {
            JSONObject creds = (JSONObject) service.get("credentials");
            String name = (String) creds.get("name");
            String host = (String) creds.get("host");
            Long port = (Long) creds.get("port");
            String user = (String) creds.get("user");
            String password = (String) creds.get("password");

            String url = "jdbc:postgresql://" + host + ":" + port + "/" + name;

            return DriverManager.getConnection(url, user, password);
        }
    }
    throw new Exception(
            "No PostgreSQL service URL found. Make sure you have bound the correct services to your app.");
}

From source file:com.ikon.util.DatabaseMetadataUtils.java

/**
 * Obtain a DatabaseMetadataValue from a Map
 *//*w ww  .  j a v a 2  s .  c om*/
public static DatabaseMetadataValue getDatabaseMetadataValueByMap(Map<String, String> map)
        throws DatabaseException, IllegalAccessException, InvocationTargetException {
    DatabaseMetadataValue dmv = new DatabaseMetadataValue();

    if (!map.isEmpty() && map.containsKey(DatabaseMetadataMap.MV_NAME_TABLE)) {
        dmv.setTable(map.get(DatabaseMetadataMap.MV_NAME_TABLE));

        if (map.containsKey(DatabaseMetadataMap.MV_NAME_ID)) {
            dmv.setId(new Double(map.get(DatabaseMetadataMap.MV_NAME_ID)).longValue());
        }

        List<DatabaseMetadataType> types = DatabaseMetadataDAO.findAllTypes(dmv.getTable());
        for (DatabaseMetadataType emt : types) {
            if (!emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_ID)
                    && !emt.getVirtualColumn().equals(DatabaseMetadataMap.MV_NAME_TABLE)) {
                if (map.keySet().contains(emt.getVirtualColumn())) {
                    BeanUtils.setProperty(dmv, emt.getRealColumn(), map.get(emt.getVirtualColumn()));
                }
            }
        }
    }

    return dmv;
}

From source file:org.grails.datastore.mapping.core.DatastoreUtils.java

/**
 * Close the given Session or register it for deferred close.
 * @param session the Datastore Session to close
 * @param datastore Datastore that the Session was created with
 * (may be <code>null</code>)
 * @see #initDeferredClose/*  ww  w . j  av a  2  s.c  o  m*/
 * @see #processDeferredClose
 */
public static void closeSessionOrRegisterDeferredClose(Session session, Datastore datastore) {
    Map<Datastore, Set<Session>> holderMap = deferredCloseHolder.get();
    if (holderMap != null && datastore != null && holderMap.containsKey(datastore)) {
        logger.debug("Registering Datastore Session for deferred close");
        holderMap.get(datastore).add(session);
    } else {
        closeSession(session);
    }
}

From source file:Main.java

public static <TKey, TValue> boolean MapEquals(Map<TKey, TValue> mapA, Map<TKey, TValue> mapB) {
    if (mapA == null) {
        return mapB == null;
    }/*from   w  w  w . ja v a 2s. co m*/
    if (mapB == null) {
        return false;
    }
    if (mapA.size() != mapB.size()) {
        return false;
    }
    for (Map.Entry<TKey, TValue> kvp : mapA.entrySet()) {
        TValue valueB = null;
        boolean hasKey;
        valueB = mapB.get(kvp.getKey());
        hasKey = (valueB == null) ? mapB.containsKey(kvp.getKey()) : true;
        if (hasKey) {
            TValue valueA = kvp.getValue();
            if (!(((valueA) == null) ? ((valueB) == null) : (valueA).equals(valueB))) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}