Example usage for java.util HashMap get

List of usage examples for java.util HashMap get

Introduction

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

Prototype

public 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:AndroidUninstallStock.java

private static LinkedHashMap<String, String> _getListFromPattern(LinkedHashMap<String, String> apkorliblist,
        HashMap<String, String> pattern, AusInfo info, String status, boolean library) {
    LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
    if (library && !pattern.get("in").equalsIgnoreCase("library")) {
        return res;
    }/*w  w  w.  j  a  v  a2 s.com*/
    int flags = getBoolean(pattern.get("case-insensitive")) ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
            : 0;
    try {
        Pattern pat = Pattern.compile(getBoolean(pattern.get("regexp")) ? pattern.get("pattern")
                : Pattern.quote(pattern.get("pattern")), flags);
        for (Map.Entry<String, String> apk : apkorliblist.entrySet()) {
            String need = "";
            switch (pattern.get("in")) {
            case "library": // TODO well as to specify the pattern package...
            case "path":
                need = apk.getKey();
                break;
            case "path+package":
                need = apk.getKey() + apk.getValue();
                break;
            case "apk":
                need = apk.getKey().substring(apk.getKey().lastIndexOf('/') + 1);
                break;
            case "package":
            default:
                need = apk.getValue();
                break;
            }
            if (pat.matcher(need).find()) {
                res.put(apk.getKey(), apk.getValue());
                System.out.println(status + need + " - " + pat.pattern());
            }
        }
    } catch (PatternSyntaxException e) {
        System.out.println("Warring in: " + info + " pattern: " + e);
    }
    return res;
}

From source file:org.esigate.DriverFactory.java

/**
 * Loads all instances according to the properties parameter.
 * //w  w  w.j a v a 2s  .  c  o m
 * @param props
 *            properties to use for configuration
 */
public static void configure(Properties props) {
    Properties defaultProperties = new Properties();

    HashMap<String, Properties> driversProps = new HashMap<String, Properties>();
    for (Enumeration<?> enumeration = props.propertyNames(); enumeration.hasMoreElements();) {
        String propertyName = (String) enumeration.nextElement();
        String value = props.getProperty(propertyName);
        int idx = propertyName.lastIndexOf('.');
        if (idx < 0) {
            defaultProperties.put(propertyName, value);
        } else {
            String prefix = propertyName.substring(0, idx);
            String name = propertyName.substring(idx + 1);
            Properties driverProperties = driversProps.get(prefix);
            if (driverProperties == null) {
                driverProperties = new Properties();
                driversProps.put(prefix, driverProperties);
            }
            driverProperties.put(name, value);
        }
    }

    // Merge with default properties
    Map<String, Driver> newInstances = new HashMap<String, Driver>();
    for (Entry<String, Properties> entry : driversProps.entrySet()) {
        String name = entry.getKey();
        Properties properties = new Properties();
        properties.putAll(defaultProperties);
        properties.putAll(entry.getValue());
        newInstances.put(name, createDriver(name, properties));
    }
    if (newInstances.get(DEFAULT_INSTANCE_NAME) == null
            && Parameters.REMOTE_URL_BASE.getValue(defaultProperties) != null) {

        newInstances.put(DEFAULT_INSTANCE_NAME, createDriver(DEFAULT_INSTANCE_NAME, defaultProperties));
    }

    instances = new IndexedInstances(newInstances);
}

From source file:amie.keys.CombinationsExplorationNew.java

private static HashMap<Rule, HashSet<String>> discoverConditionalKeysFirstLevel(
        HashMap<Rule, GraphNew> ruleToGraphNew, HashMap<Integer, GraphNew> instantiatedProperty2GraphNew) {
    Rule rule = new Rule();
    for (int conditionProperty : instantiatedProperty2GraphNew.keySet()) {
        GraphNew graph = instantiatedProperty2GraphNew.get(conditionProperty);
        String prop = id2Property.get(conditionProperty);

        Iterable<Rule> conditions = Utilities.getConditions(rule, prop, (int) support, kb);
        for (Rule conditionRule : conditions) {
            GraphNew newGraph = new GraphNew();
            discoverConditionalKeysForCondition(newGraph, graph, graph.topGraphNodes(), conditionRule);
            if (newGraph != null) {
                ruleToGraphNew.put(conditionRule, newGraph);
            }/*from w  w w  .  ja  v  a  2s.  co m*/
        }
    }

    HashMap<Rule, HashSet<String>> newRuleToExtendWith = new HashMap<>();
    for (Rule conRule : ruleToGraphNew.keySet()) {
        GraphNew newGraph = ruleToGraphNew.get(conRule);
        HashSet<String> properties = new HashSet<>();
        for (Node node : newGraph.topGraphNodes()) {
            if (node.toExplore) {
                Iterator<Integer> it = node.set.iterator();
                int prop = it.next();
                String propertyStr = id2Property.get(prop);
                properties.add(propertyStr);
            }

        }
        if (properties.size() != 0) {
            newRuleToExtendWith.put(conRule, properties);
        }
    }
    return newRuleToExtendWith;
}

From source file:gr.wavesoft.webng.io.web.WebStreams.java

public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException {
    try {/*w  w  w .  ja  va  2s  .c o  m*/

        // WebRequest connection
        ClientConnectionRequest connRequest = connectionManager.requestConnection(
                new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null);

        ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
        try {

            // Prepare request
            BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath());

            // Setup headers
            if (headers != null) {
                for (String k : headers.keySet()) {
                    request.addHeader(k, headers.get(k));
                }
            }

            // Send request
            conn.sendRequestHeader(request);

            // Fetch response
            HttpResponse response = conn.receiveResponseHeader();
            conn.receiveResponseEntity(response);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
                // Replace entity
                response.setEntity(managedEntity);
            }

            // Do something useful with the response
            // The connection will be released automatically 
            // as soon as the response content has been consumed
            return response;

        } catch (IOException ex) {
            // Abort connection upon an I/O error.
            conn.abortConnection();
            throw ex;
        }

    } catch (HttpException ex) {
        throw new IOException("HTTP Exception occured", ex);
    } catch (InterruptedException ex) {
        throw new IOException("InterruptedException", ex);
    } catch (ConnectionPoolTimeoutException ex) {
        throw new IOException("ConnectionPoolTimeoutException", ex);
    }

}

From source file:com.jabyftw.lobstercraft.util.InventoryHolder.java

/**
 * This method will mix all items in one Map(ItemStack, amount of items)
 *
 * @param itemStacks ItemStack array/* w  w  w .j  a  va2  s .co  m*/
 * @return a map with all ItemStacks together
 */
public static HashMap<ItemStack, Integer> mergeItems(@NotNull final ItemStack[] itemStacks) {
    HashMap<ItemStack, Integer> items = new HashMap<>();

    for (ItemStack currentItem : itemStacks) {
        ItemStack similarItem = null;
        // Iterate through inserted items
        for (ItemStack insertedItem : items.keySet())
            // If currentItem is similar to a inserted item, merge them
            // Note: this doesn't consider amount, so we're safe!
            if (insertedItem.isSimilar(currentItem)) {
                similarItem = insertedItem;
                break;
            }

        if (similarItem != null)
            items.put(similarItem, items.get(similarItem) + currentItem.getAmount());
        else
            items.put(currentItem, currentItem.getAmount());
    }

    return items;
}

From source file:com.act.reachables.Network.java

public static JSONObject nodeObj(MongoDB db, Node n) throws JSONException {
    Chemical thisChemical = db.getChemicalFromChemicalUUID(n.id);
    JSONObject no = thisChemical == null ? new JSONObject()
            : new JSONObject(ComputeReachablesTree.getExtendedChemicalInformationJSON(thisChemical));
    no.put("id", n.id);
    HashMap<String, Serializable> attr = n.getAttr();
    for (String k : attr.keySet()) {
        // only output the fields relevants to the reachables tree structure
        if (k.equals("NameOfLen20") || k.equals("ReadableName") || k.equals("Synonyms") || k.equals("InChI")
                || k.equals("InChiKEY") || k.equals("parent") || k.equals("under_root")
                || k.equals("num_children") || k.equals("subtreeVendorsSz") || k.equals("subtreeSz")
                || k.equals("SMILES"))
            no.put(k, attr.get(k).toString());

        if (k.equals("has"))
            no.put(k, attr.get(k));//from w  w w. j  a v  a 2s . c om
    }
    // Object v;
    // String label = "" + ((v = n.getAttribute("canonical")) != null ? v : n.id );
    // no.put("name", label ); // required
    // String layer = "" + ((v = n.getAttribute("globalLayer")) != null ? v : 1);
    // no.put("group", layer ); // required: node color by group
    return no;
}

From source file:com.globalsight.util.file.XliffFileUtil.java

/**
 * For xlz/xlf job, get its original real source file instead of the
 * extracted file./*from   w  ww  . j  a v a 2s .c  om*/
 * 
 * @param srcFile
 * @return File
 */
public static File getOriginalRealSoureFile(File srcFile) {
    if (!srcFile.exists() || !srcFile.isFile())
        return null;

    if (!isXliffFile(srcFile.getName()))
        return srcFile;

    File result = srcFile;
    // Check if it is a sub xlf file from a xlf file that has multiple
    // <file> elements.
    HashMap<String, Object> map = getPossibleOriginalXlfSourceFile(result);
    Boolean isSubFile = (Boolean) map.get("isSubFile");
    if (isSubFile) {
        result = (File) map.get("sourceFile");
    }

    // Check if it is from a xlz file
    HashMap<String, Object> map2 = getPossibleOriginalXlzSourceFile(result);
    Boolean isFromXlzFile = (Boolean) map2.get("isFromXlzFile");
    if (isFromXlzFile) {
        result = (File) map2.get("sourceFile");
    }

    return result;
}

From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java

private static void insertVisitAttributesData(GaData gaData, DBCollection collection, Date d,
        DBCollection centerMapping) throws JSONException {
    if (gaData.getTotalResults() > 0) {
        System.out.println("Data Table:" + collection);

        String[] columns = (VISIT_ATTRIBUTES_METRICS + "," + VISIT_ATTRIBUTES_DIMENSIONS).split(",");
        HashMap<String, Integer> columnLookUp = new HashMap<String, Integer>();
        List<ColumnHeaders> columnHeaders = gaData.getColumnHeaders();
        for (String column : columns) {
            for (int i = 0; i < columnHeaders.size(); i++) {
                if (columnHeaders.get(i).getName().equals(column)) {
                    columnLookUp.put(column, i);
                    break;
                }//from  w w w.j  a v a  2 s  . c  o m
            }
        }

        if (!gaData.getContainsSampledData()) {
            for (List<String> rowValues : gaData.getRows()) {
                String demandBaseId = rowValues.get(columnLookUp.get("ga:dimension11"));
                String clientId = rowValues.get(columnLookUp.get("ga:dimension2"));
                String pagePath = rowValues.get(columnLookUp.get("ga:pagePath"));
                String source = rowValues.get(columnLookUp.get("ga:source"));
                String medium = rowValues.get(columnLookUp.get("ga:medium"));
                //                    String visits = rowValues.get(columnLookUp.get("ga:visits"));
                //                    String users = rowValues.get(columnLookUp.get("ga:users"));
                //                    String pageViews = rowValues.get(columnLookUp.get("ga:pageviews"));
                //                    String sessionDuration = rowValues.get(columnLookUp.get("ga:sessionDuration"));

                HashMap<Object, Object> map = new HashMap<Object, Object>();
                map.put("demandbase_sid", demandBaseId);
                map.put("clientId", clientId);
                String[] split = pagePath.split("\\?"); // remove all characters after the URL parameters
                String[] withoutMobileUrl = split[0].split("regus.com");
                String strippedPagePath = withoutMobileUrl[withoutMobileUrl.length - 1];

                String product = "", centerLookUp = "", centerId = "";
                String[] locations = strippedPagePath.split("locations/");
                if (locations.length > 1) {
                    int index = locations[1].indexOf("/");
                    product = locations[1].substring(0, index);
                    centerLookUp = locations[1].substring(index + 1);

                    HashMap<Object, Object> centerLookUpMap = new HashMap<Object, Object>();
                    centerLookUpMap.put("CentreURLName", centerLookUp);
                    BasicDBObject objectToRemove = new BasicDBObject(centerLookUpMap);
                    DBCursor cursor = centerMapping.find(objectToRemove);
                    if (cursor.hasNext()) {
                        centerId = cursor.next().get("CentreID").toString();
                    }

                }
                map.put("pagePath", strippedPagePath);
                map.put("source", source);
                map.put("medium", medium);
                map.put("product", product);
                map.put("centerId", centerId);
                //                    map.put("visits", visits);
                //                    map.put("users", users);
                //                    map.put("pageViews", pageViews);
                //                    map.put("sessionDuration", sessionDuration);
                map.put("date", new SimpleDateFormat("yyyy/MM/dd").format(d));
                BasicDBObject objectToInsert = new BasicDBObject(map);
                collection.insert(objectToInsert);
            }
        } else {
            System.out.println(" Excluding analytics data since it has sample data");
        }
    } else {
        System.out.println("No data");
    }
}

From source file:com.clustercontrol.repository.util.FacilityTreeCache.java

/**
 * ?????????/* ww w.  j av  a  2s.co m*/
 * @param facilityId
 * @return list
 */
public static List<FacilityInfo> getChildFacilityInfoList(String facilityId) {
    // ?????????????????????????
    // (?????????????????????????)
    HashMap<String, FacilityInfo> facilityCache = getFacilityCache();

    List<FacilityInfo> childFacilityInfoList = new ArrayList<FacilityInfo>();
    Set<String> childFacilityIdSet = getChildFacilityIdSet(facilityId);
    for (String childFacilityId : childFacilityIdSet) {
        childFacilityInfoList.add(facilityCache.get(childFacilityId));
    }
    return childFacilityInfoList;
}

From source file:gov.nih.nci.rembrandt.web.helper.PCAAppletHelper.java

public static String generateParams(String sessionId, String taskId) {
    String htm = "";
    DecimalFormat nf = new DecimalFormat("0.0000");

    try {//from  w  w  w .j av  a  2  s. co  m
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(sessionId, taskId);

        ArrayList<PrincipalComponentAnalysisDataPoint> pcaData = new ArrayList();

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();

        List<PCAresultEntry> pcaResults = principalComponentAnalysisFinding.getResultEntries();
        for (PCAresultEntry pcaEntry : pcaResults) {
            sampleIds.add(pcaEntry.getSampleId());
            pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
        }

        Collection<SampleResultset> validatedSampleResultset = ClinicalDataValidator
                .getValidatedSampleResultsetsFromSampleIDs(sampleIds, clinicalFactors);

        if (validatedSampleResultset != null) {
            String id;
            PCAresultEntry entry;

            for (SampleResultset rs : validatedSampleResultset) {
                id = rs.getBiospecimen().getSpecimenName();
                entry = pcaResultMap.get(id);
                PrincipalComponentAnalysisDataPoint pcaPoint = new PrincipalComponentAnalysisDataPoint(id,
                        entry.getPc1(), entry.getPc2(), entry.getPc3());
                String diseaseName = rs.getDisease().getValueObject();
                if (diseaseName != null) {
                    pcaPoint.setDiseaseName(diseaseName);
                } else {
                    pcaPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                }
                GenderDE genderDE = rs.getGenderCode();
                if (genderDE != null) {
                    String gt = genderDE.getValueObject();
                    if (gt != null) {
                        GenderType genderType = GenderType.valueOf(gt);
                        if (genderType != null) {
                            pcaPoint.setGender(genderType);
                        }
                    }
                }
                Long survivalLength = rs.getSurvivalLength();
                if (survivalLength != null) {
                    //survival length is stored in days in the DB so divide by 30 to get the 
                    //approx survival in months
                    double survivalInMonths = survivalLength.doubleValue() / 30.0;
                    pcaPoint.setSurvivalInMonths(survivalInMonths);
                }
                pcaData.add(pcaPoint);
            }
        }

        //make a hashmap
        // [key=group] hold the array of double[][]s
        HashMap<String, ArrayList> hm = new HashMap();

        //now we should have a collection of PCADataPts
        double[][] pts = new double[pcaData.size()][3];
        for (int i = 0; i < pcaData.size(); i++) {
            //just create a large 1 set for now
            //are we breaking groups by gender or disease?
            PrincipalComponentAnalysisDataPoint pd = pcaData.get(i);

            pts[i][0] = pd.getPc1value();
            pts[i][1] = pd.getPc2value();
            pts[i][2] = pd.getPc3value();
            ArrayList<double[]> al;

            try {
                if (hm.containsKey(pd.getDiseaseName())) {
                    //already has it, so add this one
                    al = (ArrayList) hm.get(pd.getDiseaseName());
                } else {
                    al = new ArrayList();
                    hm.put(pd.getDiseaseName(), new ArrayList());
                }
                if (!al.contains(pts[i])) {
                    al.add(pts[i]);
                }
                hm.put(pd.getDiseaseName(), al);
            } catch (Exception e) {
                System.out.print(e.toString());
            }
        }
        int r = hm.size();
        if (r == 1) {
        }
        //hm should now contain a hashmap of all the disease groups

        //generate the param tags
        htm += "<param name=\"key\" value=\"" + taskId + "\" >\n";
        htm += "<param name=\"totalPts\" value=\"" + pts.length + "\" >\n";
        htm += "<param name=\"totalGps\" value=\"" + hm.size() + "\" >\n";
        int ii = 0;
        for (Object k : hm.keySet()) {
            String key = k.toString();
            //for each group

            Color diseaseColor = Color.GRAY;
            if (DiseaseType.valueOf(key) != null) {
                DiseaseType disease = DiseaseType.valueOf(key);
                diseaseColor = disease.getColor();
            }

            ArrayList<double[]> al = hm.get(key);
            htm += "<param name=\"groupLabel_" + ii + "\" value=\"" + key + "\" >\n";
            htm += "<param name=\"groupCount_" + ii + "\" value=\"" + al.size() + "\" >\n";
            htm += "<param name=\"groupColor_" + ii + "\" value=\"" + diseaseColor.getRGB() + "\" >\n";
            int jj = 0;
            for (double[] d : al) {
                String comm = nf.format(d[0]) + "," + nf.format(d[1]) + "," + nf.format(d[2]);
                String h = "<param name=\"pt_" + ii + "_" + jj + "\" value=\"" + comm + "\">\n";
                htm += h;
                jj++;
            }
            ii++;
        }
        /*
         //for bulk rendering
        for(int i=0; i<pts.length; i++)   {
           String comm = String.valueOf(pts[i][0]) + "," +
           String.valueOf(pts[i][1]) + "," +
           String.valueOf(pts[i][2]);
                   
           String h = "<param name=\"pt_"+i+"\" value=\""+ comm +"\">\n";
           //htm += h;
        }
        */

    } //try
    catch (Exception e) {

    }

    return htm;
}