List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:com.wms.studio.cache.lock.SyncLockMapCache.java
/** * ?//from ww w. j a v a 2 s. c om * * @param cacheKey */ public void removes(List<K> cacheKey) { // ?????? try { lock.lock(); HashMap<K, V> attributes = memcachedClient.get(name); if (attributes == null) { return; } for (K key : cacheKey) { attributes.remove(key); } memcachedClient.replace(name, 0, attributes); } catch (Exception e) { log.fatal("MemCache,.", e); } finally { lock.unlock(); } }
From source file:com.wms.studio.cache.memcache.MemCacheMapCache.java
@Override public V remove(final K key) throws CacheException { // ??????memcache????? synchronized (name) { try {// ww w . jav a 2 s . c o m memcachedClient.cas(name, new CASOperation<HashMap<K, V>>() { @Override public int getMaxTries() { return reCount; } @Override public HashMap<K, V> getNewValue(long currentCAS, HashMap<K, V> currentValue) { if (currentValue == null) { currentValue = new HashMap<>(); } currentValue.remove(key); return currentValue; } }); } catch (TimeoutException | InterruptedException | MemcachedException e) { log.fatal("MemCache", e); } } return null; }
From source file:org.epics.archiverappliance.TomcatSetup.java
private HashMap<String, String> createEnvironment(String testName, String applianceName) { HashMap<String, String> environment = new HashMap<String, String>(); environment.putAll(System.getenv()); environment.remove("CLASSPATH"); environment.put("CATALINA_HOME", System.getenv("TOMCAT_HOME")); File workFolder = new File("tomcat_" + testName + File.separator + applianceName); assert (workFolder.exists()); environment.put("CATALINA_BASE", workFolder.getAbsolutePath()); environment.put(ConfigService.ARCHAPPL_CONFIGSERVICE_IMPL, ConfigServiceForTests.class.getName()); environment.put(DefaultConfigService.SITE_FOR_UNIT_TESTS_NAME, DefaultConfigService.SITE_FOR_UNIT_TESTS_VALUE); environment.put(ConfigService.ARCHAPPL_MYIDENTITY, applianceName); if (!System.getProperties().containsKey(ConfigService.ARCHAPPL_APPLIANCES)) { environment.put(ConfigService.ARCHAPPL_APPLIANCES, new File("./src/sitespecific/tests/classpathfiles/appliances.xml").getAbsolutePath()); } else {/*from ww w .j a v a 2 s . c o m*/ environment.put(ConfigService.ARCHAPPL_APPLIANCES, (String) System.getProperties().get(ConfigService.ARCHAPPL_APPLIANCES)); } if (!System.getProperties().containsKey(ConfigService.ARCHAPPL_PERSISTENCE_LAYER) || System.getProperties() .get(ConfigService.ARCHAPPL_PERSISTENCE_LAYER).equals(InMemoryPersistence.class.getName())) { environment.put(ConfigService.ARCHAPPL_PERSISTENCE_LAYER, "org.epics.archiverappliance.config.persistence.InMemoryPersistence"); } else { String persistenceFile = (String) System.getProperties().get(JDBM2Persistence.ARCHAPPL_JDBM2_FILENAME); logger.info("Persistence layer is provided by " + System.getProperties().get(ConfigService.ARCHAPPL_PERSISTENCE_LAYER)); assert (persistenceFile != null); String persistenceFileForMember = persistenceFile.replace(".jdbm2", "_" + applianceName + ".jdbm2"); environment.put(ConfigService.ARCHAPPL_PERSISTENCE_LAYER, (String) System.getProperties().get(ConfigService.ARCHAPPL_PERSISTENCE_LAYER)); environment.put(JDBM2Persistence.ARCHAPPL_JDBM2_FILENAME, persistenceFileForMember); logger.info("Persistence file for member " + persistenceFileForMember); } overrideEnvWithSystemProperty(environment, "ARCHAPPL_SHORT_TERM_FOLDER"); overrideEnvWithSystemProperty(environment, "ARCHAPPL_MEDIUM_TERM_FOLDER"); overrideEnvWithSystemProperty(environment, "ARCHAPPL_LONG_TERM_FOLDER"); if (logger.isDebugEnabled()) { for (String key : environment.keySet()) { logger.debug("Env " + key + "=" + environment.get(key)); } } return environment; }
From source file:com.adaptris.util.datastore.SimpleDataStore.java
/** * @see DataStore#remove(String, String) */// w w w . ja va2 s .c om @Override public void remove(String id, String type) throws DataStoreException { try { checkConfiguration(); getLock(); HashMap sharedData = readData(); sharedData.remove(id + type); writeData(sharedData); } catch (Exception e) { throw new DataStoreException("Shared data could not be removed.", e); } finally { removeLock(); } }
From source file:com.tongbanjie.tarzan.server.client.ClientManager.java
public void unregister(final String group, final ClientChannelInfo clientChannelInfo) { try {//from w w w . j av a 2 s . c o m if (this.groupChannelLock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group); if (null != channelTable && !channelTable.isEmpty()) { ClientChannelInfo old = channelTable.remove(clientChannelInfo.getChannel()); if (old != null) { LOGGER.info("unregister a client[{}] from groupChannelTable {}", group, clientChannelInfo.toString()); } if (channelTable.isEmpty()) { this.groupChannelTable.remove(group); LOGGER.info("unregister a client group[{}] from groupChannelTable", group); } } } finally { this.groupChannelLock.unlock(); } } else { LOGGER.warn("ClientManager unregister client lock timeout"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.error("", e); } }
From source file:org.apache.hama.util.Files.java
/** * Merges k sequence files each of size n using knlog(k) merge algorithm. * @param inputPath :the input directory which contains sorted sequence * files, that have to be merged. * @param fs :the filesystem/*from w w w . ja v a 2 s. c o m*/ * @param outputPath :the path to the merged sorted sequence file. */ public static <KEY extends WritableComparable<? super KEY>, VALUE extends Writable> void merge(FileSystem fs, Path inputPath, Path outputPath, Class<KEY> keyClazz, Class<VALUE> valClazz) { Configuration conf = fs.getConf(); PriorityQueue<KVPair<KEY, VALUE>> pq = new PriorityQueue<KVPair<KEY, VALUE>>(); //Map from KeyValuePair to the split number to which it belongs. HashMap<KVPair<KEY, VALUE>, Integer> keySplitMap = new HashMap<KVPair<KEY, VALUE>, Integer>(); FileStatus[] files; SequenceFile.Writer writer = null; SequenceFile.Reader reader[] = null; try { files = fs.listStatus(inputPath); reader = new SequenceFile.Reader[files.length]; for (int i = 0; i < files.length; i++) { if (files[i].getLen() > 0) { reader[i] = new SequenceFile.Reader(fs, files[i].getPath(), conf); KEY key = ReflectionUtils.newInstance(keyClazz, new Object[0]); VALUE val = ReflectionUtils.newInstance(valClazz, new Object[0]); reader[i].next(key, val); KVPair<KEY, VALUE> kv = new KVPair<KEY, VALUE>(key, val); pq.add(kv); keySplitMap.put(kv, i); } } writer = SequenceFile.createWriter(fs, conf, outputPath, keyClazz, valClazz); while (!pq.isEmpty()) { KVPair<KEY, VALUE> smallestKey = pq.poll(); writer.append(smallestKey.getKey(), smallestKey.getValue()); Integer index = keySplitMap.get(smallestKey); keySplitMap.remove(smallestKey); KEY key = ReflectionUtils.newInstance(keyClazz, new Object[0]); VALUE val = ReflectionUtils.newInstance(valClazz, new Object[0]); if (reader[index].next(key, val)) { KVPair<KEY, VALUE> kv = new KVPair<KEY, VALUE>(key, val); pq.add(kv); keySplitMap.put(kv, index); } } } catch (IOException e) { LOG.error("Couldn't get status, exiting ...", e); System.exit(-1); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { LOG.error("Cannot close writer to sorted seq. file. Exiting ...", e); System.exit(-1); } } } }
From source file:org.duracloud.syncoptimize.config.SyncOptimizeConfigParserTest.java
public void testStandardOptions(SyncOptimizeConfigParser retConfigParser, String expectedPassword) throws Exception { HashMap<String, String> argsMap = getArgsMap(); // Process configs, make sure values match SyncOptimizeConfig syncOptConfig = retConfigParser.processOptions(mapToArray(argsMap)); checkStandardOptions(argsMap, syncOptConfig); // Remove optional params argsMap.remove("-r"); argsMap.remove("-n"); argsMap.remove("-m"); // Process configs, make sure optional params are set to defaults syncOptConfig = retConfigParser.processOptions(mapToArray(argsMap)); assertEquals(SyncOptimizeConfigParser.DEFAULT_PORT, syncOptConfig.getPort()); assertEquals(SyncOptimizeConfigParser.DEFAULT_NUM_FILES, syncOptConfig.getNumFiles()); assertEquals(SyncOptimizeConfigParser.DEFAULT_SIZE_FILES, syncOptConfig.getSizeFiles()); assertEquals(expectedPassword, syncOptConfig.getPassword()); // Make sure error is thrown on missing required params for (String arg : argsMap.keySet()) { String failMsg = "An exception should have been thrown due to " + "missing arg: " + arg; removeArgFailTest(retConfigParser, argsMap, arg, failMsg); }//from w w w.ja v a2s.c o m // Make sure error is thrown when numerical args are not numerical String failMsg = "Port arg should require a numerical value"; addArgFailTest(retConfigParser, argsMap, "-r", "nonNum", failMsg); }
From source file:org.opensilk.music.library.mediastore.util.FilesUtil.java
@NonNull public static List<Track> convertAudioFilesToTracks(Context context, File base, List<File> audioFiles) { if (audioFiles.size() == 0) { return Collections.emptyList(); }//from w w w .j ava2 s. co m final List<Track> trackList = new ArrayList<>(audioFiles.size()); Cursor c = null; try { final HashMap<String, File> pathMap = new HashMap<>(); //Build the selection final int size = audioFiles.size(); final StringBuilder selection = new StringBuilder(); selection.append(MediaStore.Audio.AudioColumns.DATA + " IN ("); for (int i = 0; i < size; i++) { final File f = audioFiles.get(i); final String path = f.getAbsolutePath(); pathMap.put(path, f); //Add file to map while where iterating //TODO it would probably be better to use selectionArgs selection.append("'").append(StringUtils.replace(path, "'", "''")).append("'"); if (i < size - 1) { selection.append(","); } } selection.append(")"); //make query c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Projections.SONG_FILE, selection.toString(), null, null); if (c != null && c.moveToFirst()) { do { final File f = pathMap .remove(c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA))); if (f != null) { try { Track.Builder tb = Track.builder() .setIdentity(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID))) .setName(getStringOrNull(c, MediaStore.Audio.AudioColumns.DISPLAY_NAME)) .setArtistName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ARTIST)) .setAlbumName(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM)) .setAlbumArtistName(getStringOrNull(c, "album_artist")) .setAlbumIdentity(getStringOrNull(c, MediaStore.Audio.AudioColumns.ALBUM_ID)) .setDuration( (int) (getLongOrZero(c, MediaStore.Audio.AudioColumns.DURATION) / 1000)) .setMimeType(getStringOrNull(c, MediaStore.Audio.AudioColumns.MIME_TYPE)) .setDataUri( generateDataUri(c.getString(c.getColumnIndexOrThrow(BaseColumns._ID)))) .setArtworkUri(generateArtworkUri( c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)))); trackList.add(tb.build()); } catch (IllegalArgumentException ignored) { } } } while (c.moveToNext()); } if (!pathMap.isEmpty()) { Timber.w("%d audioFiles didn't make the cursor", pathMap.size()); for (File f : pathMap.values()) { trackList.add(makeTrackFromFile(base, f)); } } } catch (Exception e) { if (DUMPSTACKS) Timber.e(e, "convertAudioFilesToTracks"); } finally { closeQuietly(c); } return trackList; }
From source file:cr.ac.siua.tec.utils.impl.CEInclusionPDFGenerator.java
/** * Fills the PDF file (inclusion.pdf) with the ticket values and returns base64 encoded string. */// ww w .j a v a2s. c o m @Override public String generate(HashMap<String, String> formValues) { String originalPdf = PDFGenerator.RESOURCES_PATH + "inclusion.pdf"; try { PDDocument _pdfDocument = PDDocument.load(originalPdf); PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); formValues.remove("Queue"); formValues.remove("Justificacin"); //Set some fields manually. Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; if (month > 10 || month < 5) acroForm.getField("Semestre").setValue("I"); else acroForm.getField("Semestre").setValue("II"); if (month > 10 && acroForm.getField("Semestre").getValue().equals("I")) year++; acroForm.getField("Ao").setValue(String.valueOf(year)); //Fills enrolled courses table. String enrolledCourses[] = formValues.get("Cursos matriculados").split("\n"); for (int i = 0; i < enrolledCourses.length; i++) { String courseRow[] = enrolledCourses[i].split("-"); acroForm.getField("Cdigo" + Integer.toString(i)).setValue(courseRow[0]); acroForm.getField("Curso" + Integer.toString(i)).setValue(courseRow[1]); acroForm.getField("Grupo" + Integer.toString(i)).setValue(courseRow[2]); } formValues.remove("Cursos matriculados"); //Iterates through remaining custom fields. for (Map.Entry<String, String> entry : formValues.entrySet()) { acroForm.getField(entry.getKey()).setValue(entry.getValue()); } return encodePDF(_pdfDocument); } catch (IOException e) { e.printStackTrace(); System.out.println("Excepcin al llenar el PDF."); return null; } }
From source file:com.edmunds.etm.runtime.impl.ApplicationRepository.java
public synchronized void removeApplication(Application app) { if (app == null) { return;//from www .j av a 2s . c o m } final String applicationName = app.getName(); ApplicationSeries previousSeries = seriesByName.get(applicationName); if (previousSeries == null) { return; } ApplicationSeries series = previousSeries.remove(app); // if no change was made to the series return if (previousSeries == series) { return; } final HashMap<String, ApplicationSeries> temp = Maps.newHashMap(seriesByName); // series will be null if we just removed the last version from the series. if (series == null) { temp.remove(applicationName); } else { // The series has more than one entry in it and we need to add the replacement (smaller) series. temp.put(applicationName, series); } setSeriesByName(temp); }