Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

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

Usage

From source file:com.vertica.hadoop.VerticaOutputFormat.java

/**
  * Optionally called at the end of a job to optimize any newly created and
  * loaded tables. Useful for new tables with more than 100k records.
  * /*from w ww  .j a  v  a 2 s. c  o m*/
  * @param conf
  * @throws Exception
  */
public static void optimize(Configuration conf) throws Exception {
    VerticaConfiguration vtconfig = new VerticaConfiguration(conf);
    Connection conn = vtconfig.getConnection(true);

    // TODO: consider more tables and skip tables with non-temp projections 
    Relation vTable = new Relation(vtconfig.getOutputTableName());
    Statement stmt = conn.createStatement();
    ResultSet rs = null;
    HashSet<String> tablesWithTemp = new HashSet<String>();

    //for now just add the single output table
    tablesWithTemp.add(vTable.getQualifiedName().toString());

    // map from table name to set of projection names
    HashMap<String, Collection<String>> tableProj = new HashMap<String, Collection<String>>();
    rs = stmt.executeQuery("select projection_schema, anchor_table_name, projection_name from projections;");
    while (rs.next()) {
        String ptable = rs.getString(1) + "." + rs.getString(2);
        if (!tableProj.containsKey(ptable)) {
            tableProj.put(ptable, new HashSet<String>());
        }

        tableProj.get(ptable).add(rs.getString(3));
    }

    for (String table : tablesWithTemp) {
        if (!tableProj.containsKey(table)) {
            throw new RuntimeException("Cannot optimize table with no data: " + table);
        }
    }

    String designName = (new Integer(conn.hashCode())).toString();
    stmt.execute("select dbd_create_workspace('" + designName + "')");
    stmt.execute("select dbd_create_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_design_tables('" + designName + "', '" + vTable.getQualifiedName().toString()
            + "')");
    stmt.execute("select dbd_populate_design('" + designName + "', '" + designName + "')");

    //Execute
    stmt.execute("select dbd_create_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_deployment_design('" + designName + "', '" + designName + "', '" + designName
            + "')");
    stmt.execute("select dbd_add_deployment_drop('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_execute_deployment('" + designName + "', '" + designName + "')");

    //Cleanup
    stmt.execute("select dbd_drop_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_remove_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_workspace('" + designName + "')");
}

From source file:com.icesoft.faces.facelets.D2DFaceletViewHandler.java

/**
 * Do the least amount of work to find if there are any duplicate ids,
 * with the assumption being that we won't typically find any
 * We also mention any null ids, just to be safe
 *
 * @param comp         UIComponent to recurse down through, searching for
 *                     duplicate ids.//from ww w.  j a v  a  2  s  . c  om
 * @param ids          HashMap<String id, String id> allows for detecting
 *                     if an id has already been encountered or not
 * @param duplicateIds ArrayList<String id> duplicate ids encountered
 *                     as we recurse down
 */
private static void quicklyDetectDuplicateComponentIds(UIComponent comp, HashMap ids, ArrayList duplicateIds) {
    String id = comp.getId();
    if (id == null) {
        log.debug("UIComponent has null id: " + comp);
    } else {
        if (ids.containsKey(id)) {
            if (!duplicateIds.contains(id))
                duplicateIds.add(id);
        } else {
            ids.put(id, id);
        }
    }
    Iterator children = comp.getFacetsAndChildren();
    while (children.hasNext()) {
        UIComponent child = (UIComponent) children.next();
        quicklyDetectDuplicateComponentIds(child, ids, duplicateIds);
    }
}

From source file:com.ibm.bi.dml.hops.globalopt.GDFEnumOptimizer.java

private static void rResetRuntimePlanConfig(Plan p, HashMap<Long, Plan> memo) {
    //basic memoization including containment check 
    if (memo.containsKey(p.getNode().getID())) {
        return;/*from w  w w  .j  av a  2 s .co m*/
    }

    //release forced plan configuration
    Hop hop = p.getNode().getHop();
    if (hop != null) {
        hop.setForcedExecType(null);
        hop.setRowsInBlock(DMLTranslator.DMLBlockSize);
        hop.setColsInBlock(DMLTranslator.DMLBlockSize);
        if (!HopRewriteUtils.alwaysRequiresReblock(hop)) {
            hop.setRequiresReblock(false);
        }
    }

    //process childs
    if (p.getChilds() != null)
        for (Plan c : p.getChilds())
            rResetRuntimePlanConfig(c, memo);

    //memoization (mark as processed)
    memo.put(p.getNode().getID(), p);
}

From source file:com.vertica.hivestoragehandler.VerticaOutputFormat.java

/**
  * Optionally called at the end of a job to optimize any newly created and
  * loaded tables. Useful for new tables with more than 100k records.
  * /*  w  w w  .j ava 2  s. c  o m*/
  * @param conf
  * @throws Exception
  */
public static void optimize(Configuration conf) throws Exception {
    VerticaConfiguration vtconfig = new VerticaConfiguration(conf);
    Connection conn = vtconfig.getConnection(true);

    // TODO: consider more tables and skip tables with non-temp projections 
    VerticaRelation vTable = new VerticaRelation(vtconfig.getOutputTableName());
    Statement stmt = conn.createStatement();
    ResultSet rs = null;
    HashSet<String> tablesWithTemp = new HashSet<String>();

    //for now just add the single output table
    tablesWithTemp.add(vTable.getQualifiedName().toString());

    // map from table name to set of projection names
    HashMap<String, Collection<String>> tableProj = new HashMap<String, Collection<String>>();
    rs = stmt.executeQuery("select projection_schema, anchor_table_name, projection_name from projections;");
    while (rs.next()) {
        String ptable = rs.getString(1) + "." + rs.getString(2);
        if (!tableProj.containsKey(ptable)) {
            tableProj.put(ptable, new HashSet<String>());
        }

        tableProj.get(ptable).add(rs.getString(3));
    }

    for (String table : tablesWithTemp) {
        if (!tableProj.containsKey(table)) {
            throw new RuntimeException("Cannot optimize table with no data: " + table);
        }
    }

    String designName = (new Integer(conn.hashCode())).toString();
    stmt.execute("select dbd_create_workspace('" + designName + "')");
    stmt.execute("select dbd_create_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_design_tables('" + designName + "', '" + vTable.getQualifiedName().toString()
            + "')");
    stmt.execute("select dbd_populate_design('" + designName + "', '" + designName + "')");

    //Execute
    stmt.execute("select dbd_create_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_add_deployment_design('" + designName + "', '" + designName + "', '" + designName
            + "')");
    stmt.execute("select dbd_add_deployment_drop('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_execute_deployment('" + designName + "', '" + designName + "')");

    //Cleanup
    stmt.execute("select dbd_drop_deployment('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_remove_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_design('" + designName + "', '" + designName + "')");
    stmt.execute("select dbd_drop_workspace('" + designName + "')");
}

From source file:models.NotificationMail.java

/**
 * Sends notification mails for the given event.
 *
 * @param event/*from   w ww. ja v a  2 s .c  om*/
 * @see <a href="https://github.com/nforge/yobi/blob/master/docs/technical/watch.md>watch.md</a>
 */
private static void sendNotification(NotificationEvent event) {
    Set<User> receivers = event.receivers;

    // Remove inactive users.
    Iterator<User> iterator = receivers.iterator();
    while (iterator.hasNext()) {
        User user = iterator.next();
        if (user.state != UserState.ACTIVE) {
            iterator.remove();
        }
    }

    receivers.remove(User.anonymous);

    if (receivers.isEmpty()) {
        return;
    }

    HashMap<String, List<User>> usersByLang = new HashMap<>();

    for (User receiver : receivers) {
        String lang = receiver.lang;

        if (lang == null) {
            lang = Locale.getDefault().getLanguage();
        }

        if (usersByLang.containsKey(lang)) {
            usersByLang.get(lang).add(receiver);
        } else {
            usersByLang.put(lang, new ArrayList<>(Arrays.asList(receiver)));
        }
    }

    for (String langCode : usersByLang.keySet()) {
        final EventEmail email = new EventEmail(event);

        try {
            if (hideAddress) {
                email.setFrom(Config.getEmailFromSmtp(), event.getSender().name);
                email.addTo(Config.getEmailFromSmtp(), utils.Config.getSiteName());
            } else {
                email.setFrom(event.getSender().email, event.getSender().name);
            }

            for (User receiver : usersByLang.get(langCode)) {
                if (hideAddress) {
                    email.addBcc(receiver.email, receiver.name);
                } else {
                    email.addTo(receiver.email, receiver.name);
                }
            }

            if (email.getToAddresses().isEmpty()) {
                continue;
            }

            Lang lang = Lang.apply(langCode);

            String message = event.getMessage(lang);
            String urlToView = event.getUrlToView();
            String reference = Url.removeFragment(event.getUrlToView());

            email.setSubject(event.title);

            Resource resource = event.getResource();
            if (resource.getType() == ResourceType.ISSUE_COMMENT) {
                IssueComment issueComment = IssueComment.find.byId(Long.valueOf(resource.getId()));
                resource = issueComment.issue.asResource();
            }
            email.setHtmlMsg(getHtmlMessage(lang, message, urlToView, resource));
            email.setTextMsg(getPlainMessage(lang, message, Url.create(urlToView)));
            email.setCharset("utf-8");
            email.addReferences();
            email.setSentDate(event.created);
            Mailer.send(email);
            String escapedTitle = email.getSubject().replace("\"", "\\\"");
            String logEntry = String.format("\"%s\" %s", escapedTitle, email.getBccAddresses());
            play.Logger.of("mail").info(logEntry);
        } catch (Exception e) {
            Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Rescales using plate intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16/*  w  w  w .  java2  s  .  co m*/
 * @return
 */
public static BufferedImage convertTo8bit(int rdfId, BufferedImage bi16, PlateScalingMin plateScalingMin,
        PlateScalingMax plateScalingMax) throws Exception {
    RawDataFile rdf = DALConfig.getImageProvider().LoadRawDataFile(rdfId);
    /*
    if (plateScalingMin==defaultPlateScalingMin && plateScalingMax==defaultPlateScalingMax) {
        // /orbitvol1/2014-11/4309324.1002.jpg
        String url = RawUtils.STR_SERVER+"/rawFile?rawFile="+rdf.getDataPath()+"/"+rdfId+"."+RawUtils.LEVEL_8BITPREVIEW+".jpg";
        System.out.println("url: " + url);
        return ImageIO.read(new URL(url));
    }
    */

    RawData rd = DALConfig.getImageProvider().LoadRawData(rdf.getRawDataId());
    List<RawMeta> rmList = DALConfig.getImageProvider().LoadRawMetasByRawDataFile(rdfId);
    List<RawMeta> rmDataList = DALConfig.getImageProvider().LoadRawMetasByRawData(rd.getRawDataId());
    rmList.addAll(rmDataList);
    HashMap<String, RawMeta> rmHash = RawUtilsCommon.getHashFromMetaList(rmList);

    if (!rmHash.containsKey(RawUtilsCommon.STR_META_CHANNEL))
        throw new Exception("Error: Meta data 'Channel' not available for RawDataFile " + rdfId);
    //int channel = Integer.parseInt(rmHash.get(RawUtils.STR_META_CHANNEL).getValue()) - 1;
    int channel = Integer.parseInt(rmHash.get(RawUtilsCommon.STR_META_CHANNEL).getValue());
    String metaKey = "Percentiles_wvlength_" + channel + "_channel_0";
    if (!rmHash.containsKey(metaKey))
        throw new Exception("Error: Meta data '" + metaKey + "' not available for RawDataFile " + rdfId);
    String val = rmHash.get(metaKey).getValue();
    int[] minmax = parseMinMax(val, plateScalingMin, plateScalingMax);

    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, new int[] { minmax[0] }, new int[] { minmax[1] });
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else {
        throw new IllegalArgumentException("Only images with 1 band (gray-color) supported. This image has "
                + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parseHashMap(HashMap hashMap) throws Exception {

    /*/*w  w  w  .j av  a  2  s  .  c om*/
     * ((HashMap)((java.util.HashMap)v.getValue()).get("crowd")).get("time");
            
    (java.lang.String) 2012-07-26T06:29:51.947Z
    (java.lang.String) #lab_visits    (java.util.ArrayList<E>) [07:00, 08:00]
            
            
    (java.util.HashMap<K,V>) {motion_spread=-1.000000, time=2012-07-26T06:29:51.947Z, motion_horizontal=-1, density=0.000000, motion_vertical=-1}
    (java.util.HashMap<K,V>) {isActive=false, temporalHint=[07:00, 08:00], name=#lab_visits, date=26-07-2012}
    (java.util.HashMap<K,V>) {motion_spread=-1.000000, time=2012-07-26T06:29:51.947Z, motion_horizontal=-1, density=0.000000, motion_vertical=-1}
    Evaluation failed. Reason(s):
    ClassCastException: Cannot cast java.util.HashMap (id=185) to java.util.Hashtable
     * */

    HashMap crowdHashMap = (HashMap) hashMap.get("crowd");
    double density = (Double) crowdHashMap.get("density");

    String time = (String) crowdHashMap.get("time");

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    double[] colors = null;

    if (crowdHashMap.containsKey("color")) {
        ArrayList colorList = (ArrayList) crowdHashMap.get("color");
        colors = new double[colorList.size()];
        for (int i = 0; i < colorList.size(); i++) {
            colors[i] = (Double) colorList.get(i);
        }
    }

    CrowdReport crowdReport = new CrowdReport(null, new Double(density), 0.0, colors);
    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(null, null, c, crowdReport);

    return snapShot;
}

From source file:net.exclaimindustries.geohashdroid.wiki.WikiUtils.java

/** Uploads an image to the wiki
   @param  httpclient  an active HTTP session, wiki login has to have happened before.
   @param  filename    the name of the new image file
   @param  description the description of the image. An initial description will be used as page content for the image's wiki page
   @param  formfields  a formfields hash as modified by getWikiPage containing an edittoken we can use (see the MediaWiki API for reasons why)
   @param  data        a ByteArray containing the raw image data (assuming jpeg encoding, currently).
*//* w w w.  j a  va  2s  .c om*/
public static void putWikiImage(HttpClient httpclient, String filename, String description,
        HashMap<String, String> formfields, byte[] data) throws Exception {
    if (!formfields.containsKey("token")) {
        throw new WikiException(R.string.wiki_error_unknown);
    }

    HttpPost httppost = new HttpPost(WIKI_API_URL);

    // First, we need an edit token.  Let's get one.
    ArrayList<NameValuePair> tnvps = new ArrayList<NameValuePair>();
    tnvps.add(new BasicNameValuePair("action", "query"));
    tnvps.add(new BasicNameValuePair("prop", "info"));
    tnvps.add(new BasicNameValuePair("intoken", "edit"));
    tnvps.add(new BasicNameValuePair("titles", "UPLOAD_AN_IMAGE"));
    tnvps.add(new BasicNameValuePair("format", "xml"));

    httppost.setEntity(new UrlEncodedFormEntity(tnvps, "utf-8"));
    Document response = getHttpDocument(httpclient, httppost);

    Element root = response.getDocumentElement();

    // Hopefully, a token exists.  If not, a problem exists.
    String token;
    Element page;
    try {
        page = DOMUtil.getFirstElement(root, "page");
        token = DOMUtil.getSimpleAttributeText(page, "edittoken");
    } catch (Exception e) {
        throw new WikiException(R.string.wiki_error_xml);
    }

    // TOKEN GET!  Now we've got us enough to get our upload on!
    Part[] nvps = new Part[] { new StringPart("action", "upload", "utf-8"),
            new StringPart("filename", filename, "utf-8"), new StringPart("comment", description, "utf-8"),
            new StringPart("watch", "true", "utf-8"), new StringPart("ignorewarnings", "true", "utf-8"),
            new StringPart("token", token, "utf-8"), new StringPart("format", "xml", "utf-8"),
            new FilePart("file", new ByteArrayPartSource(filename, data), "image/jpeg", "utf-8"), };
    httppost.setEntity(new MultipartEntity(nvps, httppost.getParams()));

    response = getHttpDocument(httpclient, httppost);

    root = response.getDocumentElement();

    // First, check for errors.
    if (doesResponseHaveError(root)) {
        throw new WikiException(getErrorTextId(findErrorCode(root)));
    }
}

From source file:Main.java

public static HashMap<String, List<Object[]>> getUnitDataMapList(List<Object[]> list, int[] indexnum) {
    HashMap<String, List<Object[]>> dataMap = new HashMap<String, List<Object[]>>();
    for (int i = 0; i < list.size(); i++) {
        StringBuffer returnStringBuffer = new StringBuffer();
        for (int ai = 0; ai < indexnum.length; ai++) {
            int index = indexnum[ai];
            Object obj = list.get(i)[index];
            String gunit = obj.toString();
            if (ai == 0) {
                returnStringBuffer.append(gunit);
            } else {
                returnStringBuffer.append("(" + gunit + ")");
            }/* w ww  .j  av  a 2s . c o m*/

        }
        String unit = returnStringBuffer.toString();
        if (dataMap.containsKey(unit)) {
            dataMap.get(unit).add((Object[]) list.get(i));
        } else {
            ArrayList<Object[]> rowdata = new ArrayList<Object[]>();
            rowdata.add((Object[]) list.get(i));
            dataMap.put(unit, rowdata);
        }
    }

    return dataMap;
}

From source file:org.eclipse.swt.examples.launcher.LauncherPlugin.java

/**
 * Constructs a list of available programs from registered extensions.
 * // ww  w  . jav a2 s.  c  o  m
 * @return an ItemTreeNode representing the root of a tree of items (the root is not to be displayed)
 */
public static ItemTreeNode getLaunchItemTree() {
    ItemTreeNode categoryTree = new ItemTreeNode(
            new ItemDescriptor("<<Root>>", "<<Root>>", null, null, null, null, null, null));

    // get the platform's public plugin registry
    IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry();
    // retrieve all configuration elements registered at our launchItems extension-point
    IConfigurationElement[] configurationElements = extensionRegistry
            .getConfigurationElementsFor(LAUNCH_ITEMS_POINT_ID);

    if (configurationElements == null || configurationElements.length == 0) {
        logError(getResourceString("error.CouldNotFindRegisteredExtensions"), null);
        return categoryTree;
    }

    /* Collect all launch categories -- coalesce those with same ID */
    HashMap<String, ItemTreeNode> idMap = new HashMap<>();
    for (IConfigurationElement ce : configurationElements) {
        final String ceName = ce.getName();
        final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);

        if (idMap.containsKey(attribId))
            continue;
        if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
            final String attribName = getItemName(ce);
            ItemDescriptor theDescriptor = new ItemDescriptor(attribId, attribName, getItemDescription(ce),
                    null, null, null, null, ce);
            idMap.put(attribId, new ItemTreeNode(theDescriptor));
        }
    }

    /* Generate launch category hierarchy */
    Set<String> tempIdSet = new HashSet<>(); // used to prevent duplicates from being entered into the tree
    for (IConfigurationElement ce : configurationElements) {
        final String ceName = ce.getName();
        final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);

        if (tempIdSet.contains(attribId))
            continue;
        if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
            final ItemTreeNode theNode = idMap.get(attribId);
            addItemByCategory(ce, categoryTree, theNode, idMap);
            tempIdSet.add(attribId);
        }
    }

    /* Generate program tree */
    for (IConfigurationElement ce : configurationElements) {
        final String ceName = ce.getName();
        final String attribId = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ID, null);

        if (idMap.containsKey(attribId))
            continue;
        if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_CATEGORY)) {
            // ignore
        } else if (ceName.equalsIgnoreCase(LAUNCH_ITEMS_XML_ITEM)) {
            final String enabled = getItemAttribute(ce, LAUNCH_ITEMS_XML_ATTRIB_ENABLED,
                    LAUNCH_ITEMS_XML_VALUE_TRUE);
            if (enabled.equalsIgnoreCase(LAUNCH_ITEMS_XML_VALUE_FALSE))
                continue;
            ItemDescriptor theDescriptor = createItemDescriptor(ce, attribId);

            if (theDescriptor != null) {
                final ItemTreeNode theNode = new ItemTreeNode(theDescriptor);
                addItemByCategory(ce, categoryTree, theNode, idMap);
                idMap.put(attribId, theNode);
            }
        }
    }
    return categoryTree;
}