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:nextflow.fs.dx.api.DxEnv.java

/**
 * Loads the user-specified config and returns an object representing that
 * environment. From lowest to highest precedence, we (1) apply the system
 * defaults, which can be overridden by (2) JSON config in the file
 * ~/.dnanexus_config/environment.json, which can be overridden by (3) the
 * DX_* environment variables.//  w ww  . j a v a  2  s  .c  om
 */
private static DxEnv create() {
    log.debug("Creating DxEnv object");

    // (1) System defaults
    String apiserverHost = DEFAULT_APISERVER_HOST;
    String apiserverPort = DEFAULT_APISERVER_PORT;
    String apiserverProtocol = DEFAULT_APISERVER_PROTOCOL;
    String securityContext = null;
    String jobId = null;
    String workspaceId = null;
    String projectContextId = null;

    // (2) JSON config file: ~/.dnanexus_config/environment.json
    File jsonConfigFile = new File(System.getProperty("user.home") + "/.dnanexus_config/environment.json");
    if (jsonConfigFile.exists()) {
        try {
            JsonNode jsonConfig = jsonFactory.createJsonParser(jsonConfigFile).readValueAsTree();
            if (getTextValue(jsonConfig, "DX_APISERVER_HOST") != null) {
                apiserverHost = getTextValue(jsonConfig, "DX_APISERVER_HOST");
            }
            if (getTextValue(jsonConfig, "DX_APISERVER_PORT") != null) {
                apiserverPort = getTextValue(jsonConfig, "DX_APISERVER_PORT");
            }
            if (getTextValue(jsonConfig, "DX_APISERVER_PROTOCOL") != null) {
                apiserverProtocol = getTextValue(jsonConfig, "DX_APISERVER_PROTOCOL");
            }
            if (getTextValue(jsonConfig, "DX_SECURITY_CONTEXT") != null) {
                securityContext = getTextValue(jsonConfig, "DX_SECURITY_CONTEXT");
            }
            if (getTextValue(jsonConfig, "DX_JOB_ID") != null) {
                jobId = getTextValue(jsonConfig, "DX_JOB_ID");
            }
            if (getTextValue(jsonConfig, "DX_WORKSPACE_ID") != null) {
                workspaceId = getTextValue(jsonConfig, "DX_WORKSPACE_ID");
            }
            if (getTextValue(jsonConfig, "DX_PROJECT_CONTEXT_ID") != null) {
                projectContextId = getTextValue(jsonConfig, "DX_PROJECT_CONTEXT_ID");
            }
        } catch (IOException e) {
            log.error("WARNING: JSON config file {} could not be parsed, skipping it",
                    jsonConfigFile.getPath());
        }
    }

    // (3) Environment variables
    Map<String, String> sysEnv = System.getenv();
    if (sysEnv.containsKey("DX_APISERVER_HOST")) {
        apiserverHost = sysEnv.get("DX_APISERVER_HOST");
    }
    if (sysEnv.containsKey("DX_APISERVER_PORT")) {
        apiserverPort = sysEnv.get("DX_APISERVER_PORT");
    }
    if (sysEnv.containsKey("DX_APISERVER_PROTOCOL")) {
        apiserverProtocol = sysEnv.get("DX_APISERVER_PROTOCOL");
    }
    if (sysEnv.containsKey("DX_SECURITY_CONTEXT")) {
        securityContext = sysEnv.get("DX_SECURITY_CONTEXT");
    }
    if (sysEnv.containsKey("DX_JOB_ID")) {
        jobId = sysEnv.get("DX_JOB_ID");
    }
    if (sysEnv.containsKey("DX_WORKSPACE_ID")) {
        workspaceId = sysEnv.get("DX_WORKSPACE_ID");
    }
    if (sysEnv.containsKey("DX_PROJECT_CONTEXT_ID")) {
        projectContextId = sysEnv.get("DX_PROJECT_CONTEXT_ID");
    }

    return new DxEnv(apiserverHost, apiserverPort, apiserverProtocol, securityContext, jobId, workspaceId,
            projectContextId);
}

From source file:AIR.Common.collections.IGrouping.java

public static <K, V> List<IGrouping<K, V>> createGroups(Collection<V> list, Transformer transformer) {
    Map<K, IGrouping<K, V>> map = new HashMap<K, IGrouping<K, V>>();
    for (V element : list) {
        @SuppressWarnings("unchecked")
        K groupValue = (K) transformer.transform(element);
        IGrouping<K, V> group = null;
        if (map.containsKey(groupValue)) {
            group = map.get(groupValue);
        } else {//from ww w  .j a  v a 2s  .c om
            group = new IGrouping<K, V>(groupValue);
            map.put(groupValue, group);
        }
        group.add(element);
    }
    return new ArrayList<IGrouping<K, V>>(map.values());
}

From source file:de.vandermeer.skb.datatool.commons.DataUtilities.java

/**
 * Takes the given entry map and tries to generate a special data object from it.
 * @param key the key pointing to the map entry
 * @param keyStart string used to start a key
 * @param map key/value mappings to load the key from
 * @param loadedTypes loaded types as lookup for links
 * @param cs core settings required for loading data
 * @return a new data object of specific type (as read from the map) on success, null on no success
 * @throws IllegalArgumentException if any of the required arguments or map entries are not set or empty
 * @throws URISyntaxException if creating a URI for an SKB link failed
 *//*from www  . jav  a2  s . com*/
public static Object loadData(EntryKey key, String keyStart, Map<?, ?> map, LoadedTypeMap loadedTypes,
        CoreSettings cs) throws URISyntaxException {
    if (!map.containsKey(key.getKey())) {
        return null;
    }

    Object data = map.get(key.getKey());
    if (key.getSkbUri() != null && data instanceof String) {
        return loadLink(data, loadedTypes);
    }

    if (key.getType().equals(String.class) && data instanceof String) {
        if (key.useTranslator() == true && cs.getTranslator() != null) {
            return cs.getTranslator().translate((String) data);
        }
        return data;
    }
    if (key.getType().equals(Integer.class) && data instanceof Integer) {
        return data;
    }

    if (ClassUtils.isAssignable(key.getType(), EntryObject.class)) {
        EntryObject eo;
        try {
            eo = (EntryObject) key.getType().newInstance();
            if (data instanceof Map) {
                eo.loadObject(keyStart, data, loadedTypes, cs);
            }
            return eo;
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}

From source file:com.avego.oauth.migration.OauthMigrationDaoFactory.java

/**
 * This creates an instance of a token dao
 * @param params The dao params/* www. ja v a  2s  .  c  o m*/
 * @return The token dao instance
 * @throws DaoCreationException If it failed to instantiate the dao
 */
public static OauthMigrationDao newInstance(Map<String, Object> params) throws DaoCreationException {

    OauthMigrationDao dao = null;
    String className = System.getProperty(MIGRATION_DAO_PROPERTY, DEFAULT_MIGRATION_DAO);
    if (params != null && params.containsKey(MIGRATION_DAO_PROPERTY)) {
        String paramClassName = (String) params.get(MIGRATION_DAO_PROPERTY);
        if (paramClassName != null && paramClassName.length() > 0) {
            className = paramClassName;
        }
    }
    Constructor<OauthMigrationDao> constructor = null;
    try {
        @SuppressWarnings("unchecked")
        Class<OauthMigrationDao> clazz = (Class<OauthMigrationDao>) Class.forName(className);

        // look for a constructor that takes the jdbc template
        constructor = ConstructorUtils.getAccessibleConstructor(clazz, Map.class);
        if (constructor == null) {
            // use default no arg constructor
            constructor = ConstructorUtils.getAccessibleConstructor(clazz);
            if (constructor != null) {
                dao = constructor.newInstance();
            }
        } else {
            dao = constructor.newInstance(params);
        }
    } catch (Exception ex) {
        throw new DaoCreationException(
                "Failed to create the dao with the class: " + className + ", msg; " + ex.getMessage(), ex);
    }
    if (constructor == null) {
        throw new DaoCreationException("The class: " + className
                + " Did not have a no args constructor nor a constructor taking a Map<String, Object>");
    }
    return dao;
}

From source file:com.adito.activedirectory.ActiveDirectoryPropertyManager.java

private static PropertyList getRealValue(Map<String, String> alternativeValues, String key,
        PropertyList values) {// w  w w  . j  a va2s  .c om
    return alternativeValues.containsKey(key) ? new PropertyList(alternativeValues.get(key)) : values;
}

From source file:Main.java

public static Map<String, List<String>> classify(List<Map<String, Object>> result, String key, String key2) {
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    List<String> values = null;
    for (Map<String, Object> record : result) {
        String mapKey = String.valueOf(record.get(key));
        String mapkey2 = String.valueOf(record.get(key2));
        if (!map.containsKey(mapKey)) {
            values = new LinkedList<String>();
            values.add(mapkey2);//from w w  w . j a v a2s . c o  m
        } else {
            map.get(mapKey).add(mapkey2);
        }
        map.put(mapKey, values);
    }
    return map;
}

From source file:org.alfresco.mobile.android.api.exceptions.impl.OAuthErrorContent.java

/**
 * Parses the json exception response and try to retrieve essential values.
 * /*from w ww.  ja  v a  2s . c  o m*/
 * @param errorContentValue the raw data from the HTTP request.
 * @return the OAuth error content
 */
public static OAuthErrorContent parseJson(String errorContentValue) {
    Map<String, Object> json = null;
    try {
        json = JsonUtils.parseObject(errorContentValue);
    } catch (Exception e) {
        return null;
    }

    OAuthErrorContent errorContent = null;
    if (json.containsKey(CloudConstant.ERROR_VALUE) || json.containsKey(CloudConstant.ERRORDESCRIPTION_VALUE)) {
        errorContent = new OAuthErrorContent();
        errorContent.message = JSONConverter.getString(json, CloudConstant.ERROR_VALUE);
        errorContent.description = JSONConverter.getString(json, CloudConstant.ERRORDESCRIPTION_VALUE);
    }
    return errorContent;
}

From source file:com.turn.ttorrent.client.tracker.HTTPTrackerClient.java

@CheckForNull
public static HTTPTrackerMessage toMessage(@Nonnull HttpResponse response,
        @CheckForSigned long maxContentLength) throws IOException {
    HttpEntity entity = response.getEntity();
    if (entity == null) // Usually 204-no-content, etc.
        return null;
    try {/*from w w  w .  ja v  a 2  s.  c o  m*/
        if (maxContentLength >= 0) {
            long contentLength = entity.getContentLength();
            if (contentLength >= 0)
                if (contentLength > maxContentLength)
                    throw new IllegalArgumentException(
                            "ContentLength was too big: " + contentLength + ": " + response);
        }

        InputStream in = entity.getContent();
        if (in == null)
            return null;
        try {
            StreamBDecoder decoder = new StreamBDecoder(in);
            BEValue value = decoder.bdecodeMap();
            Map<String, BEValue> params = value.getMap();
            // TODO: "warning message"
            if (params.containsKey("failure reason"))
                return HTTPTrackerErrorMessage.fromBEValue(params);
            else
                return HTTPAnnounceResponseMessage.fromBEValue(params);
        } finally {
            IOUtils.closeQuietly(in);
        }
    } catch (InvalidBEncodingException e) {
        throw new IOException("Failed to parse response " + response, e);
    } catch (TrackerMessage.MessageValidationException e) {
        throw new IOException("Failed to parse response " + response, e);
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

From source file:Main.java

public static <V> void get(final Map<?, ? extends V> map, final Collection<? super V> values,
        final Object... keys) {
    for (final Object key2 : keys) {
        final Object key = key2;
        if (!map.containsKey(key)) {
            continue;
        }//from   ww  w  .  j a  va 2  s.  co  m

        final V value = map.get(key);
        values.add(value);
    }
}

From source file:com.github.tteofili.p2h.Par2HierUtils.java

/**
 * base case: on a leaf hv = pv//ww  w .j  a v  a 2s .  c  o m
 * on a non-leaf node with n children: hv = pv + k centroids of the n hv
 */
private static INDArray getPar2HierVector(WeightLookupTable<VocabWord> lookupTable, PatriciaTrie<String> trie,
        String node, int k, Map<String, INDArray> hvs, Method method) {
    if (hvs.containsKey(node)) {
        return hvs.get(node);
    }
    INDArray hv = lookupTable.vector(node);
    String[] split = node.split(REGEX);
    Collection<String> descendants = new HashSet<>();
    if (split.length == 2) {
        String separator = ".";
        String prefix = node.substring(0, node.indexOf(split[1])) + separator;

        SortedMap<String, String> sortedMap = trie.prefixMap(prefix);

        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            if (prefix.lastIndexOf(separator) == entry.getKey().lastIndexOf(separator)) {
                descendants.add(entry.getValue());
            }
        }
    } else {
        descendants = Collections.emptyList();
    }
    if (descendants.size() == 0) {
        // just the pv
        hvs.put(node, hv);
        return hv;
    } else {
        INDArray chvs = Nd4j.zeros(descendants.size(), hv.columns());
        int i = 0;
        for (String desc : descendants) {
            // child hierarchical vector
            INDArray chv = getPar2HierVector(lookupTable, trie, desc, k, hvs, method);
            chvs.putRow(i, chv);
            i++;
        }

        double[][] centroids;
        if (chvs.rows() > k) {
            centroids = Par2HierUtils.getTruncatedVT(chvs, k);
        } else if (chvs.rows() == 1) {
            centroids = Par2HierUtils.getDoubles(chvs.getRow(0));
        } else {
            centroids = Par2HierUtils.getTruncatedVT(chvs, 1);
        }
        switch (method) {
        case CLUSTER:
            INDArray matrix = Nd4j.zeros(centroids.length + 1, hv.columns());
            matrix.putRow(0, hv);
            for (int c = 0; c < centroids.length; c++) {
                matrix.putRow(c + 1, Nd4j.create(centroids[c]));
            }
            hv = Nd4j.create(Par2HierUtils.getTruncatedVT(matrix, 1));
            break;
        case SUM:
            for (double[] centroid : centroids) {
                hv.addi(Nd4j.create(centroid));
            }
            break;
        }

        hvs.put(node, hv);
        return hv;
    }
}