Example usage for java.util HashMap remove

List of usage examples for java.util HashMap remove

Introduction

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

Prototype

public V remove(Object key) 

Source Link

Document

Removes the mapping for the specified key from this map if present.

Usage

From source file:uk.co.revsys.oddball.Oddball.java

public Collection<String> findQueryCasesForEach(String ruleSetName, String query, Map<String, String> options)
        throws IOException, RuleSetNotLoadedException, DaoException, TransformerNotLoadedException,
        AggregationException, UnknownBinException, InvalidCaseException, InvalidTimePeriodException,
        ProcessorNotLoadedException, ComparisonException, FilterException,
        IdentificationSchemeNotLoadedException {
    ArrayList<String> cases = new ArrayList<String>();
    String forEach = options.get("forEach");
    HashMap<String, String> distinctOptions = new HashMap<String, String>();
    distinctOptions.putAll(options);/*from  w  w w.  j ava 2 s  . co m*/
    distinctOptions.put("distinct", forEach);
    distinctOptions.remove("transformer");
    distinctOptions.remove("aggregator");
    distinctOptions.remove("selector");
    distinctOptions.remove("identifier");
    distinctOptions.remove("comparator");
    distinctOptions.remove("tagger");
    distinctOptions.remove("filter");
    distinctOptions.remove("forEach");
    distinctOptions.remove("processor");
    distinctOptions.remove("processorChain");
    ArrayList<String> allDistinct = new ArrayList<String>();
    allDistinct.addAll(findQueryCases(ruleSetName, query, distinctOptions));
    for (String distinctValue : allDistinct) {
        options.put("forEachValue", distinctValue.replace("\"", ""));
        cases.addAll(findQueryCases(ruleSetName, query, options));
    }
    return cases;
}

From source file:org.kuali.ole.select.service.impl.BibInfoServiceImpl.java

private void removeElements(HashMap<String, String> dataMap) throws Exception {
    dataMap.remove(OleSelectConstant.BIB_MARC_XMLSTRING);
    dataMap.remove(OleSelectConstant.ITEM_MARC_XMLSTRING);
}

From source file:com.linkedin.databus.core.TestDbusEventBufferPersistence.java

@Test
public void testMetaFileCloseMult() throws Exception {
    int maxEventBufferSize = 1144;
    int maxIndividualBufferSize = 500;
    int bufNum = maxEventBufferSize / maxIndividualBufferSize;
    if (maxEventBufferSize % maxIndividualBufferSize > 0)
        bufNum++;/*from w  w w.  ja  v a2 s . c o  m*/

    DbusEventBuffer.StaticConfig config = getConfig(maxEventBufferSize, maxIndividualBufferSize, 100, 500,
            AllocationPolicy.MMAPPED_MEMORY, _mmapDirStr, true);

    // create buffer mult
    DbusEventBufferMult bufMult = createBufferMult(config);

    // Save all the files and validate the meta files.
    bufMult.close();
    for (DbusEventBuffer dbusBuf : bufMult.bufIterable()) {
        File metaFile = new File(_mmapDir, dbusBuf.metaFileName());
        // check that we don't have the files
        Assert.assertTrue(metaFile.exists());
        validateFiles(metaFile, bufNum);
    }
    File[] entries = _mmapDir.listFiles();

    // When we create a new multi-buffer, we should get renamed files as well as new files.
    bufMult = createBufferMult(config);
    entries = _mmapDir.listFiles(); // Has session dirs and renamed meta files.
    // Create an info file for one buffer.
    DbusEventBuffer buf = bufMult.bufIterable().iterator().next();
    buf.saveBufferMetaInfo(true);
    File infoFile = new File(_mmapDir, buf.metaFileName() + ".info");
    Assert.assertTrue(infoFile.exists());

    // Create a session directory that has one file in it.
    File badSes1 = new File(_mmapDir, DbusEventBuffer.getSessionPrefix() + "m");
    badSes1.mkdir();
    badSes1.deleteOnExit();
    File junkFile = new File(badSes1.getAbsolutePath() + "/junkFile");
    junkFile.createNewFile();
    junkFile.deleteOnExit();
    // Create a directory that is empty
    File badSes2 = new File(_mmapDir, DbusEventBuffer.getSessionPrefix() + "n");
    badSes2.mkdir();
    badSes2.deleteOnExit();

    // Create a good file under mmap directory that we don't want to see removed.
    final String goodFile = "GoodFile";
    File gf = new File(_mmapDir, goodFile);
    gf.createNewFile();

    // Now close the multibuf, and see that the new files are still there.
    // We should have deleted the unused sessions and info files.
    bufMult.close();

    HashSet<String> validEntries = new HashSet<String>(bufNum);
    for (DbusEventBuffer dbusBuf : bufMult.bufIterable()) {
        File metaFile = new File(_mmapDir, dbusBuf.metaFileName());
        // check that we don't have the files
        Assert.assertTrue(metaFile.exists());
        validateFiles(metaFile, bufNum);
        validEntries.add(metaFile.getName());
        DbusEventBufferMetaInfo mi = new DbusEventBufferMetaInfo(metaFile);
        mi.loadMetaInfo();
        validEntries.add(mi.getSessionId());
    }

    validEntries.add(goodFile);

    // Now we should be left with meta files, and session dirs and nothing else.
    entries = _mmapDir.listFiles();
    for (File f : entries) {
        Assert.assertTrue(validEntries.contains(f.getName()));
        validEntries.remove(f.getName());
    }
    Assert.assertTrue(validEntries.isEmpty());

    // And everything else should have moved to the .BAK directory
    entries = _mmapBakDir.listFiles();
    HashMap<String, File> fileHashMap = new HashMap<String, File>(entries.length);
    for (File f : entries) {
        fileHashMap.put(f.getName(), f);
    }

    Assert.assertTrue(fileHashMap.containsKey(badSes1.getName()));
    Assert.assertTrue(fileHashMap.get(badSes1.getName()).isDirectory());
    Assert.assertEquals(fileHashMap.get(badSes1.getName()).listFiles().length, 1);
    Assert.assertEquals(fileHashMap.get(badSes1.getName()).listFiles()[0].getName(), junkFile.getName());
    fileHashMap.remove(badSes1.getName());

    Assert.assertTrue(fileHashMap.containsKey(badSes2.getName()));
    Assert.assertTrue(fileHashMap.get(badSes2.getName()).isDirectory());
    Assert.assertEquals(fileHashMap.get(badSes2.getName()).listFiles().length, 0);
    fileHashMap.remove(badSes2.getName());

    // We should have the renamed meta files in the hash now.
    for (File f : entries) {
        if (f.getName().startsWith(DbusEventBuffer.getMmapMetaInfoFileNamePrefix())) {
            Assert.assertTrue(fileHashMap.containsKey(f.getName()));
            Assert.assertTrue(f.isFile());
            fileHashMap.remove(f.getName());
        }
    }

    Assert.assertTrue(fileHashMap.isEmpty());

    // One more test to make sure we create the BAK directory dynamically if it does not exist.
    FileUtils.deleteDirectory(_mmapBakDir);
    bufMult = createBufferMult(config);
    entries = _mmapDir.listFiles();
    // Create an info file for one buffer.
    buf = bufMult.bufIterable().iterator().next();
    buf.saveBufferMetaInfo(true);
    infoFile = new File(_mmapDir, buf.metaFileName() + ".info");
    Assert.assertTrue(infoFile.exists());
    bufMult.close();
    entries = _mmapBakDir.listFiles();
    fileHashMap = new HashMap<String, File>(entries.length);
    for (File f : entries) {
        fileHashMap.put(f.getName(), f);
    }
    Assert.assertTrue(fileHashMap.containsKey(infoFile.getName()));
    Assert.assertTrue(fileHashMap.get(infoFile.getName()).isFile());
}

From source file:com.ibm.bi.dml.hops.cost.CostEstimator.java

/**
 * //from   w  w w .j  a va 2 s. c  om
 * @param inst
 * @param stats
 */
private void cleanupMRJobVariableStatistics(Instruction inst, HashMap<String, VarStats> stats) {
    MRJobInstruction jinst = (MRJobInstruction) inst;

    //get number of indices 
    byte[] indexes = jinst.getIv_resultIndices();
    byte maxIx = -1;
    for (int i = 0; i < indexes.length; i++)
        if (maxIx < indexes[i])
            maxIx = indexes[i];

    //remove all stats up to max index
    for (int i = 0; i <= maxIx; i++) {
        VarStats tmp = stats.remove(String.valueOf(i));
        if (tmp != null)
            tmp._inmem = false; //all MR job outptus on HDFS
    }
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized Uri insert(@NonNull Uri uri, ContentValues initialValues) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }//w  w  w. jav a2 s  .  c o m

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLoggerIf log = WebLogger.getLogger(appName);

    HashMap<String, Object> values = new HashMap<String, Object>();
    if (initialValues != null) {
        for (String key : initialValues.keySet()) {
            values.put(key, initialValues.get(key));
        }
    }

    // force a scan from disk
    values.remove(FormsColumns.DATE);
    values.remove(FormsColumns.JSON_MD5_HASH);
    FormSpec formSpec = patchUpValues(appName, values);

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.TABLE_ID, FormsColumns.FORM_ID };
    String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?";
    String[] selectionArgs = { formSpec.tableId, formSpec.formId };
    Cursor c = null;

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null, null);
            if (c == null) {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- unable to query for existing records. tableId="
                                + formSpec.tableId + " formId=" + formSpec.formId);
            }
            c.moveToFirst();
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri + " -- row already exists for  tableId="
                        + formSpec.tableId + " formId=" + formSpec.formId);
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insertOrThrow(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            // and notify listeners of the new row...
            Uri formUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    (String) values.get(FormsColumns.FORM_ID));
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    Long.toString(rowId));
            getContext().getContentResolver().notifyChange(idUri, null);

            return formUri;
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
}

From source file:org.onecmdb.ui.gwt.desktop.server.service.change.ReconciliationEngine.java

public List<ChangeItem> reconciliate() {
    HashMap<String, ChangeItem> items = new HashMap<String, ChangeItem>();
    List<IRFC> rfcs = compare();
    for (IRFC rfc : rfcs) {
        RFCTarget target = getBeanFromRFC(rfc);
        if (target == null) {
            continue;
        }//from  w  w  w  .ja  v a 2 s. c  o  m
        CiBean bean = target.bean;
        if (bean == null) {
            continue;
        }
        if (rfc instanceof RFCNewCi) {
            if (items.containsKey(bean.getAlias())) {
                items.remove(bean);
            }

            ChangeItem item = toChanges(bean, ChangeItem.STATUS_NEW, "");
            items.put(bean.getAlias(), item);
            //updateBeanSummary(bean, item);
            continue;
        }

        if (rfc instanceof RFCDestroy && target.attr == null && target.value == null) {
            if (items.containsKey(bean.getAlias())) {
                items.remove(bean.getAlias());
            }
            ChangeItem item = toChanges(bean, ChangeItem.STATUS_DELETE, "");
            items.put(bean.getAlias(), item);
            //updateBeanSummary(bean, item);
            continue;
        }
        ChangeItem item = items.get(bean.getAlias());
        if (item == null) {
            item = toChanges(bean, ChangeItem.STATUS_MODIFIED, "");
        }
        if (item.getStatus().equals(ChangeItem.STATUS_DELETE)
                || item.getStatus().equals(ChangeItem.STATUS_NEW)) {
            continue;
        }
        String summary = item.get("summary", "");
        if (rfc instanceof RFCDestroy) {
            if (target.attr != null) {
                summary = summary + "<br/> Delete attribute " + target.attr.getAlias();
            } else if (target.value != null) {
                summary = summary + "<br/> Delete value " + target.value.getAlias();
            }
        } else {
            summary = summary + "<br/>" + rfc.getSummary();
        }
        item.set("summary", summary);
        items.put(bean.getAlias(), item);
    }
    for (String alias : items.keySet()) {
        CiBean bean = getBean(alias);
        if (bean != null) {
            updateBeanSummary(bean, items.get(alias));
        }
    }
    getResult().addAll(items.values());
    return (result);

}

From source file:org.sakaiproject.tool.assessment.ui.bean.util.EmailBean.java

public void prepareAttachment() {
    ToolSession session = SessionManager.getCurrentToolSession();
    ArrayList newAttachmentList = new ArrayList();
    if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
        List refs = (List) session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
        Reference ref;/*from ww  w  .  ja v a 2 s. co  m*/
        if (refs.size() == 0) {
            hasAttachment = false;
        } else {
            HashMap map = getResourceIdHash(attachmentList);
            for (int i = 0; i < refs.size(); i++) {
                ref = (Reference) refs.get(i);
                String resourceId = ref.getId();
                if (map.get(resourceId) == null) {
                    AssessmentService assessmentService = new AssessmentService();
                    AttachmentData attach = assessmentService.createEmailAttachment(resourceId,
                            ref.getProperties().getProperty(ref.getProperties().getNamePropDisplayName()),
                            ServerConfigurationService.getServerUrl());

                    newAttachmentList.add(attach);

                } else {
                    newAttachmentList.add((AttachmentData) map.get(resourceId));
                    map.remove(resourceId);
                }

                hasAttachment = true;
            }
        }
        session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
        session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
    } else {
        hasAttachment = false;
    }
    attachmentList = newAttachmentList;
}

From source file:xyz.openmodloader.gradle.task.MergeJarsTask.java

private void processJar(File clientInFile, File serverInFile, File outFile) throws IOException {
    ZipFile cInJar = null;//from   w  w w . ja v a2s. c o m
    ZipFile sInJar = null;
    ZipOutputStream outJar = null;

    try {
        try {
            cInJar = new ZipFile(clientInFile);
            sInJar = new ZipFile(serverInFile);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        // different messages.

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        // read in the jars, and initalize some variables
        HashSet<String> resources = new HashSet<String>();
        HashMap<String, ZipEntry> cClasses = getClassEntries(cInJar, outJar, resources);
        HashMap<String, ZipEntry> sClasses = getClassEntries(sInJar, outJar, resources);
        HashSet<String> cAdded = new HashSet<String>();

        // start processing
        for (Entry<String, ZipEntry> entry : cClasses.entrySet()) {
            String name = entry.getKey();
            ZipEntry cEntry = entry.getValue();
            ZipEntry sEntry = sClasses.get(name);

            if (sEntry == null) {
                copyClass(cInJar, cEntry, outJar, true);
                cAdded.add(name);
                continue;
            }

            sClasses.remove(name);
            byte[] cData = readEntry(cInJar, entry.getValue());
            byte[] sData = readEntry(sInJar, sEntry);
            byte[] data = processClass(cData, sData);

            ZipEntry newEntry = new ZipEntry(cEntry.getName());
            outJar.putNextEntry(newEntry);
            outJar.write(data);
            cAdded.add(name);
        }

        for (Entry<String, ZipEntry> entry : sClasses.entrySet()) {
            if (DEBUG) {
                System.out.println("Copy class s->c : " + entry.getKey());
            }
            copyClass(sInJar, entry.getValue(), outJar, false);
        }

        for (String name : new String[] { sideOnlyClass.getName(), sideClass.getName() }) {
            String eName = name.replace(".", "/");
            String classPath = eName + ".class";
            ZipEntry newEntry = new ZipEntry(classPath);
            if (!cAdded.contains(eName)) {
                outJar.putNextEntry(newEntry);
                outJar.write(getClassBytes(name));
            }
        }

    } finally {
        if (cInJar != null) {
            try {
                cInJar.close();
            } catch (IOException e) {
            }
        }

        if (sInJar != null) {
            try {
                sInJar.close();
            } catch (IOException e) {
            }
        }
        if (outJar != null) {
            try {
                outJar.close();
            } catch (IOException e) {
            }
        }

    }
}

From source file:com.isencia.passerelle.process.actor.flow.ContextEntryModifier.java

/**
 * /*from  w ww.  j a  v  a 2  s  .  com*/
 * @param diagnosisContext
 * @param modeStr
 * @param scopeStr
 * @param entryName
 * @param entryValue
 * @throws IllegalStateException
 *           e.g. when the Context has a conflicting entry for e.g. scope
 * @throws IllegalArgumentException
 *           e.g. when an invalid mode is passed
 */
@SuppressWarnings("unchecked")
private void doItOnScope(Context diagnosisContext, String modeStr, String scopeStr, String entryName,
        String entryValue) throws IllegalStateException, IllegalArgumentException {
    Object scopeObj = diagnosisContext.getEntryValue(scopeStr);
    HashMap<String, String> scopeMap = null;
    if (scopeObj != null) {
        try {
            scopeMap = (HashMap<String, String>) scopeObj;
        } catch (ClassCastException e) {
            throw new IllegalStateException("Context entry scope not a Map for " + scopeStr);
        }
    }
    Mode mode = Mode.valueOf(modeStr);
    switch (mode) {
    case Set:
        if (scopeMap == null) {
            scopeMap = new HashMap<String, String>();
            diagnosisContext.putEntry(scopeStr, scopeMap);
        }
        scopeMap.put(entryName, entryValue);
        break;
    case Remove:
        if (scopeMap != null) {
            if (StringUtils.isEmpty(entryName)) {
                // it's a remove for the complete scope
                diagnosisContext.removeEntry(scopeStr);
            } else {
                // it's a remove for one specific entry
                scopeMap.remove(entryName);
            }
        }
        break;
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *//*from   w  w  w  .j a  v  a 2  s.  c  o m*/
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}