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:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Do post./*from   www  .  j  av  a2  s .co  m*/
 *
 * @param uri
 *            the uri
 * @param body
 *            the body
 * @param headers
 *            the headers
 * @return the int
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws HttpResponseException
 *             the http response exception
 */
public static int doPost(String uri, String body, HashMap<String, String> headers)
        throws ClientProtocolException, IOException, HttpResponseException {
    // TODO delete before commit
    // System.out.println("doPost>> uri:"+uri +"\nbody:"+body+"\n");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    int resp = -1;
    try {
        HttpPost httpPost = new HttpPost(uri);
        for (String key : headers.keySet()) {
            httpPost.addHeader(key, headers.get(key));
            // System.out.println("header:"+key+"/"+headers.get(key));

        }
        // System.out.println("doPost<<");
        httpPost.setEntity(new StringEntity(body));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        resp = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            response.close();
        } else {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpclient.close();
    }
    return resp;
}

From source file:com.evolveum.midpoint.common.policy.ValuePolicyGenerator.java

/**
 * Count cardinality/*  www  .  j  a v a2  s .c  o m*/
 */
private static HashMap<Integer, ArrayList<String>> cardinalityCounter(
        HashMap<StringLimitType, ArrayList<String>> lims, ArrayList<String> password, Boolean skipMatchedLims,
        boolean uniquenessReached, OperationResult op) {
    HashMap<String, Integer> counter = new HashMap<String, Integer>();

    for (StringLimitType l : lims.keySet()) {
        int counterKey = 1;
        ArrayList<String> chars = lims.get(l);
        int i = 0;
        if (null != password) {
            i = charIntersectionCounter(lims.get(l), password);
        }
        // If max is exceed then error unable to continue
        if (l.getMaxOccurs() != null && i > l.getMaxOccurs()) {
            OperationResult o = new OperationResult("Limitation check :" + l.getDescription());
            o.recordFatalError("Exceeded maximal value for this limitation. " + i + ">" + l.getMaxOccurs());
            op.addSubresult(o);
            return null;
            // if max is all ready reached or skip enabled for minimal skip
            // counting
        } else if (l.getMaxOccurs() != null && i == l.getMaxOccurs()) {
            continue;
            // other cases minimum is not reached
        } else if ((l.getMinOccurs() == null || i >= l.getMinOccurs()) && !skipMatchedLims) {
            continue;
        }
        for (String s : chars) {
            if (null == password || !password.contains(s) || uniquenessReached) {
                //               if (null == counter.get(s)) {
                counter.put(s, counterKey);
                //               } else {
                //                  counter.put(s, counter.get(s) + 1);
                //               }
            }
        }
        counterKey++;

    }

    // If need to remove disabled chars (already reached limitations)
    if (null != password) {
        for (StringLimitType l : lims.keySet()) {
            int i = charIntersectionCounter(lims.get(l), password);
            if (l.getMaxOccurs() != null && i > l.getMaxOccurs()) {
                OperationResult o = new OperationResult("Limitation check :" + l.getDescription());
                o.recordFatalError("Exceeded maximal value for this limitation. " + i + ">" + l.getMaxOccurs());
                op.addSubresult(o);
                return null;
            } else if (l.getMaxOccurs() != null && i == l.getMaxOccurs()) {
                // limitation matched remove all used chars
                LOGGER.trace("Skip " + l.getDescription());
                for (String charToRemove : lims.get(l)) {
                    counter.remove(charToRemove);
                }
            }
        }
    }

    // Transpone to better format
    HashMap<Integer, ArrayList<String>> ret = new HashMap<Integer, ArrayList<String>>();
    for (String s : counter.keySet()) {
        // if not there initialize
        if (null == ret.get(counter.get(s))) {
            ret.put(counter.get(s), new ArrayList<String>());
        }
        ret.get(counter.get(s)).add(s);
    }
    return ret;
}

From source file:marytts.server.http.MivoqSynthesisRequestHandler.java

private static String toOldStyleEffectsString(HashMap<String, ParamParser> registry,
        HashMap<String, Object> effects_values) {
    StringBuilder sb = new StringBuilder();
    for (String name : effects_values.keySet()) {
        Object param = effects_values.get(name);
        if (param != null) {
            ParamParser parser = registry.get(name);
            if (parser != null) {
                param = parser.limit(param);
                String s = parser.toOldStyleString(param);
                if (s != null) {
                    if (sb.length() > 0) {
                        sb.append('+');
                    }/*from www  .  j a  va  2 s.  c o  m*/
                    sb.append(s);
                }
            }
        }
    }
    return sb.toString();
}

From source file:org.easyrec.utils.MyUtils.java

/**
 * This function sorts the Strings in the given list by their first
 * occurrence in the given text. The Strings in the list are tokenized
 * e.g. "red bull" is split in "red" and "bull" those tokens are
 * matched by their first occurrence in the text.
 *//*ww  w.  j a v  a  2  s  . com*/
public static List<String> orderByFuzzyFirstOccurenceInText(String listToOrder[], String textToParse) {
    List<String> sortedList = new ArrayList<String>();
    HashMap<Integer, String> h = new HashMap<Integer, String>();

    if (listToOrder != null && !textToParse.equals("")) {
        for (String stringTokens : listToOrder) {

            String[] tokens = stringTokens.split(" ");
            for (String token : tokens) {

                if (textToParse.indexOf(token) > 0 && token.length() > 3) {

                    h.put(textToParse.indexOf(token), token);
                }
            }
        }

        List<Integer> keys = new ArrayList<Integer>(h.keySet());
        Collections.sort(keys);

        for (Integer k : keys) {
            sortedList.add(h.get(k));
        }
    }
    return sortedList;
}

From source file:edu.msu.cme.rdp.readseq.utils.RmDupSeqs.java

public static void filterDuplicates(String inFile, String outFile, int length, boolean debug)
        throws IOException {
    HashMap<String, String> idSet = new HashMap<String, String>();
    IndexedSeqReader reader = new IndexedSeqReader(new File(inFile));
    BufferedWriter outWriter = new BufferedWriter(new FileWriter(new File(outFile)));
    Set<String> allseqIDset = reader.getSeqIdSet();
    Sequence seq;/* www  .  j av a 2s  . c om*/
    if (debug) {
        System.out.println("ID\tdescription" + "\tcontained_by_ID\tdescription");
    }
    for (String id : allseqIDset) {
        seq = reader.readSeq(id);
        boolean dup = false;
        HashSet<String> tempdupSet = new HashSet<String>();
        for (String exID : idSet.keySet()) {
            String exSeq = idSet.get(exID);
            if (exSeq.length() >= seq.getSeqString().length()) {
                if (exSeq.contains(seq.getSeqString())) {
                    dup = true;
                    if (debug) {
                        Sequence temp = reader.readSeq(exID);
                        System.out.println(id + "\t" + seq.getDesc() + "\t" + exID + "\t" + temp.getDesc());
                    }
                    break;
                }
            } else if (seq.getSeqString().contains(exSeq)) {
                tempdupSet.add(exID);
            }
        }

        if (!dup) {
            idSet.put(id, seq.getSeqString());
        }
        for (String dupid : tempdupSet) {
            idSet.remove(dupid);
            if (debug) {
                Sequence temp = reader.readSeq(dupid);
                System.out.println(dupid + "\t" + temp.getDesc() + "\t" + id + "\t" + seq.getDesc());
            }
        }
    }
    // get the unique seq
    for (String id : idSet.keySet()) {
        seq = reader.readSeq(id);
        if (seq.getSeqString().length() >= length) {
            outWriter.write(">" + id + "\t" + seq.getDesc() + "\n" + seq.getSeqString() + "\n");
        }
    }
    reader.close();
    outWriter.close();
}

From source file:com.ibm.bi.dml.runtime.util.DataConverter.java

/**
 * /* w w  w. j  a  va 2 s  .  c  om*/
 * @param map
 * @return
 */
public static MatrixBlock convertToMatrixBlock(HashMap<MatrixIndexes, Double> map) {
    // compute dimensions from the map
    long nrows = 0, ncols = 0;
    for (MatrixIndexes index : map.keySet()) {
        nrows = Math.max(nrows, index.getRowIndex());
        ncols = Math.max(ncols, index.getColumnIndex());
    }

    // convert to matrix block
    return convertToMatrixBlock(map, (int) nrows, (int) ncols);
}

From source file:free.yhc.netmbuddy.utils.Utils.java

public static <K, V> K findKey(HashMap<K, V> map, V value) {
    Iterator<K> iter = map.keySet().iterator();
    while (iter.hasNext()) {
        K key = iter.next();//from w w  w.java2  s .  co  m
        if (map.get(key).equals(value))
            return key;
    }
    return null;
}

From source file:net.triptech.metahive.model.Definition.java

/**
 * Count the definitions.//  w ww. ja va2  s .c o m
 *
 * @param filter the filter
 * @return the long
 */
public static long countDefinitions(final DefinitionFilter filter) {

    StringBuilder sql = new StringBuilder("SELECT COUNT(d) FROM Definition d JOIN d.category c");
    sql.append(buildWhere(filter));

    TypedQuery<Long> q = entityManager().createQuery(sql.toString(), Long.class);

    HashMap<String, String> variables = buildVariables(filter);
    for (String variable : variables.keySet()) {
        q.setParameter(variable, variables.get(variable));
    }

    return q.getSingleResult();
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * // w  ww .  j a  va2 s  .c o  m
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:net.triptech.metahive.model.Definition.java

/**
 * Find definition entries./*www .j  ava  2 s .  co m*/
 *
 * @param filter the definition filter
 * @param firstResult the first result
 * @param maxResults the max results
 * @return the list
 */
public static List<Definition> findDefinitionEntries(final DefinitionFilter filter, final int firstResult,
        final int maxResults) {

    StringBuilder sql = new StringBuilder("SELECT d FROM Definition d JOIN d.category c");
    sql.append(buildWhere(filter));
    sql.append(" ORDER BY d.name ASC");

    TypedQuery<Definition> q = entityManager().createQuery(sql.toString(), Definition.class)
            .setFirstResult(firstResult).setMaxResults(maxResults);

    HashMap<String, String> variables = buildVariables(filter);
    for (String variable : variables.keySet()) {
        q.setParameter(variable, variables.get(variable));
    }

    return q.getResultList();
}