下面列出了java.util.LinkedHashMap#containsKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void currentNews( GenericMessageEvent event, Matcher matcher,
LinkedHashMap<String, ImmutablePair<String, URL>> newsFeedsByCategory,
String defaultCategory, String helpCommand, LimitCommand limitCommand,
String restrictedChannel, Logger logger )
{
String category = matcher.group( 1 ); // The news category
category = ( category != null ) ? category.toLowerCase() : defaultCategory;
if ( newsFeedsByCategory.containsKey( category ) )
{
newsLimit( event, newsFeedsByCategory, category, logger, limitCommand, restrictedChannel );
}
else
{
event.respondWith( "No news feed available for " + category + ". Try " + helpCommand
+ " for available news categories." );
}
}
/**
*
* @param key Key.
* @param node Mapped node.
* @param missedNodesToKeysMapping Full node mapping.
*/
protected boolean checkRetryPermits(
KeyCacheObject key,
ClusterNode node,
Map<ClusterNode, LinkedHashMap<KeyCacheObject, Boolean>> missedNodesToKeysMapping
) {
LinkedHashMap<KeyCacheObject, Boolean> keys = missedNodesToKeysMapping.get(node);
if (keys != null && keys.containsKey(key)) {
if (REMAP_CNT_UPD.incrementAndGet(this) > MAX_REMAP_CNT) {
onDone(new ClusterTopologyCheckedException("Failed to remap key to a new node after " +
MAX_REMAP_CNT + " attempts (key got remapped to the same node) [key=" + key + ", node=" +
U.toShortString(node) + ", mappings=" + missedNodesToKeysMapping + ']'));
return false;
}
}
return true;
}
LinkedHashMap<DegreeOfFreedom,double[]> calcDOFBounds(RCTuple conf){
LinkedHashMap<DegreeOfFreedom,double[]> DOFBounds = new LinkedHashMap<>();
for(int posCount=0; posCount<conf.pos.size(); posCount++){
//we may actually need DOF intervals for different RCs to differ here...
//anyway an RC is just a set of box constr, so we enforce the intersection
RC curRC = cSpace.posFlex.get(conf.pos.get(posCount)).RCs.get(conf.RCs.get(posCount));
for(int dofCount=0; dofCount<curRC.DOFs.size(); dofCount++){
DegreeOfFreedom curDOF = curRC.DOFs.get(dofCount);
double lb = curRC.DOFmin.get(dofCount);
double ub = curRC.DOFmax.get(dofCount);
if(DOFBounds.containsKey(curDOF)){
double[] curBounds = DOFBounds.get(curDOF);
curBounds[0] = Math.max(lb, curBounds[0]);
curBounds[1] = Math.min(ub, curBounds[1]);
}
else
DOFBounds.put(curDOF, new double[]{lb,ub} );
}
}
return DOFBounds;
}
private void findNewestParticipatingLeaves(Course course, Staff staff, LinkedHashMap<Long, Course> resultMap) {
if (!resultMap.containsKey(course.getId())) {
resultMap.put(course.getId(), course);
if (course.isExpires()) {
Collection<Course> renewals = course.getRenewals();
if (renewals != null && renewals.size() > 0) {
Iterator<Course> it = renewals.iterator();
while (it.hasNext()) {
Course renewal = it.next();
if (getCachedParticiaptionCourseIds(staff).contains(renewal.getId())) {
findNewestParticipatingLeaves(renewal, staff, resultMap);
}
}
}
}
}
}
/**
* @param line filter line from <code>VCF</code> file
*/
public ContigField(String line) {
final LinkedHashMap<String, String> temp = VcfHeader.parseMetaLine(line, CONTIG_LINE_PATTERN);
VcfHeader.checkRequiredMetaKeys(temp, "ID");
mId = temp.get("ID");
temp.remove("ID");
if (temp.containsKey("length")) {
try {
mLength = Integer.valueOf(temp.get("length"));
} catch (NumberFormatException e) {
throw new VcfFormatException("Non-integer contig length \"" + temp.get("length") + "\"");
}
temp.remove("length");
} else {
mLength = null;
}
mValues = temp;
}
@VisibleForTesting
static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classloader) {
LinkedHashMap<File, ClassLoader> entries = Maps.newLinkedHashMap();
// Search parent first, since it's the order ClassLoader#loadClass() uses.
ClassLoader parent = classloader.getParent();
if (parent != null) {
entries.putAll(getClassPathEntries(parent));
}
if (classloader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) classloader;
for (URL entry : urlClassLoader.getURLs()) {
if (entry.getProtocol().equals("file")) {
File file = new File(entry.getFile());
if (!entries.containsKey(file)) {
entries.put(file, classloader);
}
}
}
}
return ImmutableMap.copyOf(entries);
}
public LinkedHashMap<String,Object> getPluginConfiguration(String pluginId) throws SparklerException {
pluginId = pluginId.replace("-", ".");
if (this.containsKey(Constants.key.PLUGINS)) {
LinkedHashMap plugins = (LinkedHashMap) this.get(Constants.key.PLUGINS);
if (plugins.containsKey(pluginId)) {
return (LinkedHashMap<String, Object>) plugins.get(pluginId);
} else {
String[] parts = pluginId.split(":");
if (parts.length >= 3){ // groupId:artifactId:version
//first check without version
String newId = parts[0] + ":" + parts[1];
if (plugins.containsKey(newId)) {
return (LinkedHashMap<String, Object>) plugins.get(newId);
} else if (plugins.containsKey(parts[1])){ // just the id, no groupId or version
return (LinkedHashMap<String, Object>) plugins.get(parts[1]);
}
}
throw new SparklerException("No configuration found for Plugin: " + pluginId);
}
} else {
throw new SparklerException("No plugin configuration found!");
}
}
@Nonnull
protected Policy parsePolicy() {
Policy policy = new Policy(this.origin);
LinkedHashMap<Class<? extends Directive>, Directive<? extends DirectiveValue>> directives = new LinkedHashMap<>();
while (this.hasNext()) {
if (this.hasNext(PolicySeparatorToken.class)) {
break;
}
if (this.eat(DirectiveSeparatorToken.class)) {
continue;
}
try {
Directive<? extends DirectiveValue> directive = this.parseDirective();
// only add a directive if it doesn't exist; used for handling duplicate directives in CSP headers
if (!directives.containsKey(directive.getClass())) {
directives.put(directive.getClass(), directive);
} else {
this.warn(this.tokens[this.index - 2], "Policy contains more than one " + directive.name + " directive. All but the first instance will be ignored.");
}
} catch (DirectiveParseException ignored) {
}
}
policy.addDirectives(directives.values());
return policy;
}
private static void analyzeMethods(
final Method mget,
final DslJson json,
final LinkedHashMap<String, JsonWriter.WriteObject> foundWrite,
final HashMap<Type, Type> genericMappings) {
if (mget.getParameterTypes().length != 0) return;
if (!canRead(mget.getModifiers())) return;
final String name = Analysis.beanOrActualName(mget.getName());
if (foundWrite.containsKey(name)) return;
final Type type = mget.getGenericReturnType();
final Type concreteType = Generics.makeConcrete(type, genericMappings);
final boolean isUnknown = Generics.isUnknownType(type);
if (isUnknown || json.tryFindWriter(concreteType) != null && json.tryFindReader(concreteType) != null) {
foundWrite.put(
name,
Settings.createEncoder(
new Reflection.ReadMethod(mget),
name,
json,
isUnknown ? null : concreteType));
}
}
/**
* Transforms a list of PIDs to the list of digital objects to be exported.
* When an object is the article then its parent is listed instead and
* the article is included in the attached set.
* Other children of the parent are ignored during the export.
* @param pids input PIDs
* @param crawler the search index
* @param ctx the context
* @return the list of unique digital objects and their articles to include.
* The {@code null} Set means include all children.
*/
private LinkedHashMap<DigitalObjectElement, Set<DigitalObjectElement>> prepareInputQueue(
List<String> pids, final DigitalObjectCrawler crawler, CejshContext ctx) {
LinkedHashMap<DigitalObjectElement, Set<DigitalObjectElement>> dobjs =
new LinkedHashMap<DigitalObjectElement, Set<DigitalObjectElement>>(pids.size());
for (String pid : pids) {
try {
DigitalObjectElement elm = crawler.getEntry(pid);
if (BornDigitalModsPlugin.MODEL_ARTICLE.equals(elm.getModelId())) {
// add article as inlude filter
DigitalObjectElement parent = crawler.getParent(pid);
if (parent == DigitalObjectElement.NULL) {
ctx.getStatus().error(elm, "No parent!", null, null);
break;
}
Set<DigitalObjectElement> children = dobjs.get(parent);
if (children == null) {
children = new HashSet<DigitalObjectElement>();
dobjs.put(parent, children);
}
children.add(elm);
} else {
if (!dobjs.containsKey(elm)) {
dobjs.put(elm, null);
}
}
} catch (DigitalObjectException ex) {
ctx.getStatus().error(pid, "No parent!", ex);
}
}
return dobjs;
}
public BoardsListAdapter(BoardsListFragment fragment) {
super(fragment.activity, 0);
this.inflater = LayoutInflater.from(fragment.activity);
this.resources = fragment.resources;
String lastCategory = "";
LinkedHashMap<String, String> favBoards = new LinkedHashMap<>();
for (String board : fragment.database.getFavoriteBoards(fragment.chan)) favBoards.put(board, "");
if (!favBoards.isEmpty()) {
lastCategory = resources.getString(R.string.boardslist_favorite_boards);
add(new BoardsListEntry(lastCategory));
for (int i=0; i<fragment.boardsList.length; ++i)
if (favBoards.containsKey(fragment.boardsList[i].boardName))
favBoards.put(fragment.boardsList[i].boardName, fragment.boardsList[i].boardDescription);
for (Map.Entry<String, String> entry : favBoards.entrySet()) {
SimpleBoardModel model = new SimpleBoardModel();
model.chan = fragment.chan.getChanName();
model.boardName = entry.getKey();
model.boardDescription = entry.getValue();
model.boardCategory = lastCategory;
add(new BoardsListEntry(model));
}
}
for (int i=0; i<fragment.boardsList.length; ++i) {
if (!fragment.settings.showNSFWBoards() && fragment.boardsList[i].nsfw) continue;
String curCategory = fragment.boardsList[i].boardCategory != null ? fragment.boardsList[i].boardCategory : "";
if (!curCategory.equals(lastCategory)) {
add(new BoardsListEntry(curCategory));
lastCategory = curCategory;
}
add(new BoardsListEntry(fragment.boardsList[i]));
}
}
static void testLinkedHashMap() {
LinkedHashMap m = new LinkedHashMap();
Object o = new Object();
if (m.containsKey(o)) {
m.get(o).toString();
}
}
static public LinkedHashMap<String, ProteinSequence> getProteinSequences(Collection<ChromosomeSequence> chromosomeSequences) throws Exception {
LinkedHashMap<String, ProteinSequence> proteinSequenceHashMap = new LinkedHashMap<String, ProteinSequence>();
for (ChromosomeSequence dnaSequence : chromosomeSequences) {
for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) {
for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {
//TODO remove?
// DNASequence dnaCodingSequence = transcriptSequence.getDNACodingSequence();
// logger.info("CDS={}", dnaCodingSequence.getSequenceAsString());
try {
ProteinSequence proteinSequence = transcriptSequence.getProteinSequence();
// logger.info("{} {}", proteinSequence.getAccession().getID(), proteinSequence);
if (proteinSequenceHashMap.containsKey(proteinSequence.getAccession().getID())) {
throw new Exception("Duplicate protein sequence id=" + proteinSequence.getAccession().getID() + " found at Gene id=" + geneSequence.getAccession().getID());
} else {
proteinSequenceHashMap.put(proteinSequence.getAccession().getID(), proteinSequence);
}
} catch (Exception e) {
logger.error("Exception: ", e);
}
}
}
}
return proteinSequenceHashMap;
}
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLRUMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
}
// init lru
LinkedHashMap<String, String> lruItem = jobLRUMap.get(jobId);
if (lruItem == null) {
/**
* LinkedHashMap
* a、accessOrder:ture=访问顺序排序(get/put时排序);false=插入顺序排期;
* b、removeEldestEntry:新增元素时将会调用,返回true时会删除最老元素;可封装LinkedHashMap并重写该方法,比如定义最大容量,超出是返回true即可实现固定长度的LRU算法;
*/
lruItem = new LinkedHashMap<String, String>(16, 0.75f, true);
jobLRUMap.putIfAbsent(jobId, lruItem);
}
// put
for (String address : addressList) {
if (!lruItem.containsKey(address)) {
lruItem.put(address, address);
}
}
// load
String eldestKey = lruItem.entrySet().iterator().next().getKey();
String eldestValue = lruItem.get(eldestKey);
return eldestValue;
}
/**
* Parse results given by table read. The function returns a list of strings, where each string
* represents a single column. The list constitutes the entire result set (columns in all of the
* records).
*/
private static List<String> parseResultSet(
Struct struct, LinkedHashMap<String, BiFunction<Struct, String, String>> parsers) {
List<String> result = Lists.newArrayList();
for (String columnName : parsers.keySet()) {
if (!parsers.containsKey(columnName)) {
throw new RuntimeException("No parser for column: " + columnName);
}
result.add(parsers.get(columnName).apply(struct, columnName));
}
return result;
}
private boolean setBulkRequests(String entryName,
DcODataProducer producer,
LinkedHashMap<String, BulkRequest> bulkRequests,
Map<String, String> fileNameMap) {
BulkRequest bulkRequest = new BulkRequest();
String key = DcUUID.randomUUID();
try {
// entityType名を取得する
String entityTypeName = getEntityTypeName(entryName);
if (producer.getMetadata().findEdmEntitySet(entityTypeName) == null) {
throw DcCoreException.OData.NO_SUCH_ENTITY_SET;
}
// ZipArchiveImputStreamからユーザデータのJSONをStringReader形式で取得する
StringReader stringReader = getStringReaderFromZais();
// リクエストボディを生成する
ODataResource odataResource = odataEntityResource.getOdataResource();
ODataEntitiesResource resource = new ODataEntitiesResource(odataResource, entityTypeName);
OEntity oEntity = resource.getOEntityWrapper(stringReader, odataResource, producer.getMetadata());
UserDataODataProducer userDataProducer = (UserDataODataProducer) producer;
EntitySetDocHandler docHandler = producer.getEntitySetDocHandler(entityTypeName, oEntity);
String docType = UserDataODataProducer.USER_ODATA_NAMESPACE;
docHandler.setType(docType);
docHandler.setEntityTypeId(userDataProducer.getEntityTypeId(oEntity.getEntitySetName()));
odataEntityResource.setOdataProducer(userDataProducer);
// データ内でのID競合チェック
// TODO 複合主キー対応、ユニークキーのチェック、NTKP対応
key = oEntity.getEntitySetName() + ":" + (String) docHandler.getStaticFields().get("__id");
if (bulkRequests.containsKey(key)) {
throw DcCoreException.OData.ENTITY_ALREADY_EXISTS;
}
// ID指定がない場合はUUIDを払い出す
if (docHandler.getId() == null) {
docHandler.setId(DcUUID.randomUUID());
}
bulkRequest.setEntitySetName(entityTypeName);
bulkRequest.setDocHandler(docHandler);
} catch (Exception e) {
writeOutputStream(true, "PL-BI-1004", entryName, e.getMessage());
log.info(entryName + " : " + e.getMessage());
bulkRequest.setError(e);
return false;
}
bulkRequests.put(key, bulkRequest);
fileNameMap.put(key, entryName);
return true;
}
@Override
protected Void doInBackground(Void... params) {
BookmarkIterator bookmarkIterator = getAvailableBookmarks();
if (bookmarkIterator == null) return null;
// Get a snapshot of the bookmarks.
LinkedHashMap<Long, Bookmark> idMap = new LinkedHashMap<Long, Bookmark>();
HashSet<String> urlSet = new HashSet<String>();
Bookmark rootBookmarksFolder = createRootBookmarksFolderBookmark();
idMap.put(ROOT_FOLDER_ID, rootBookmarksFolder);
while (bookmarkIterator.hasNext()) {
Bookmark bookmark = bookmarkIterator.next();
if (bookmark == null) continue;
// Check for duplicate ids.
if (idMap.containsKey(bookmark.mId)) {
Log.i(TAG, "Duplicate bookmark id: "
+ bookmark.mId + ". Dropping bookmark.");
continue;
}
// Check for duplicate URLs.
if (!bookmark.mIsFolder && urlSet.contains(bookmark.mUrl)) {
Log.i(TAG, "More than one bookmark pointing to "
+ bookmark.mUrl
+ ". Keeping only the first one for consistency with Chromium.");
continue;
}
idMap.put(bookmark.mId, bookmark);
urlSet.add(bookmark.mUrl);
}
bookmarkIterator.close();
// Recreate the folder hierarchy and read it.
recreateFolderHierarchy(idMap);
if (rootBookmarksFolder.mEntries.size() == 0) {
Log.e(TAG, "ATTENTION: not using partner bookmarks as none were provided");
return null;
}
if (rootBookmarksFolder.mEntries.size() != 1) {
Log.e(TAG, "ATTENTION: more than one top-level partner bookmarks, ignored");
return null;
}
readBookmarkHierarchy(
rootBookmarksFolder,
new HashSet<PartnerBookmarksReader.Bookmark>());
return null;
}
protected final static ArrayList<RandomizationListCodeInVO> sanitizeRandomizationListCodesInput(String randomizationBlock, Collection<RandomizationListCodeInVO> codes)
throws ServiceException {
if (codes != null) {
LinkedHashSet<String> textValues = new LinkedHashSet<String>();
splitInputFieldTextValues(randomizationBlock, textValues);
LinkedHashMap<String, RandomizationListCodeInVO> codeMap = new LinkedHashMap<String, RandomizationListCodeInVO>(codes.size());
Iterator<RandomizationListCodeInVO> codesIt = codes.iterator();
while (codesIt.hasNext()) {
RandomizationListCodeInVO code = codesIt.next();
String value = code.getCode();
if (CommonUtil.isEmptyString(value)) {
throw L10nUtil.initServiceException(ServiceExceptionCodes.EMPTY_RANDOMIZATION_CODE_VALUE);
} else {
value = (TRIM_INPUT_FIELD_TEXT_VALUE ? value.trim() : value);
if (codeMap.containsKey(value)) {
throw L10nUtil.initServiceException(ServiceExceptionCodes.DUPLICATE_RANDOMIZATION_CODE_VALUE, value);
} else if (textValues.remove(value)) {
if (TRIM_INPUT_FIELD_TEXT_VALUE) {
code = new RandomizationListCodeInVO(code);
code.setCode(value);
}
codeMap.put(value, code);
} else {
throw L10nUtil.initServiceException(ServiceExceptionCodes.UNKNOWN_RANDOMIZATION_CODE_VALUE, value);
}
}
}
if (textValues.size() > 0) {
Iterator<String> it = textValues.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(it.next());
}
throw L10nUtil.initServiceException(ServiceExceptionCodes.MISSING_RANDOMIZATION_CODE_VALUES, sb.toString());
} else {
return new ArrayList<RandomizationListCodeInVO>(codeMap.values());
}
}
return null;
}
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLRUMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// init lru
LinkedHashMap<String, String> lruItem = jobLRUMap.get(jobId);
if (lruItem == null) {
/**
* LinkedHashMap
* a、accessOrder:true=访问顺序排序(get/put时排序);false=插入顺序排期;
* b、removeEldestEntry:新增元素时将会调用,返回true时会删除最老元素;可封装LinkedHashMap并重写该方法,比如定义最大容量,超出是返回true即可实现固定长度的LRU算法;
*/
lruItem = new LinkedHashMap<String, String>(16, 0.75f, true);
jobLRUMap.putIfAbsent(jobId, lruItem);
}
// put new
for (String address: addressList) {
if (!lruItem.containsKey(address)) {
lruItem.put(address, address);
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lruItem.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lruItem.remove(delKey);
}
}
// load
String eldestKey = lruItem.entrySet().iterator().next().getKey();
String eldestValue = lruItem.get(eldestKey);
return eldestValue;
}
@Override
protected Void doInBackground(Void... params) {
BookmarkIterator bookmarkIterator = getAvailableBookmarks();
if (bookmarkIterator == null) return null;
// Get a snapshot of the bookmarks.
LinkedHashMap<Long, Bookmark> idMap = new LinkedHashMap<Long, Bookmark>();
HashSet<String> urlSet = new HashSet<String>();
Bookmark rootBookmarksFolder = createRootBookmarksFolderBookmark();
idMap.put(ROOT_FOLDER_ID, rootBookmarksFolder);
while (bookmarkIterator.hasNext()) {
Bookmark bookmark = bookmarkIterator.next();
if (bookmark == null) continue;
// Check for duplicate ids.
if (idMap.containsKey(bookmark.mId)) {
Log.i(TAG, "Duplicate bookmark id: "
+ bookmark.mId + ". Dropping bookmark.");
continue;
}
// Check for duplicate URLs.
if (!bookmark.mIsFolder && urlSet.contains(bookmark.mUrl)) {
Log.i(TAG, "More than one bookmark pointing to "
+ bookmark.mUrl
+ ". Keeping only the first one for consistency with Chromium.");
continue;
}
idMap.put(bookmark.mId, bookmark);
urlSet.add(bookmark.mUrl);
}
bookmarkIterator.close();
// Recreate the folder hierarchy and read it.
recreateFolderHierarchy(idMap);
if (rootBookmarksFolder.mEntries.size() == 0) {
Log.e(TAG, "ATTENTION: not using partner bookmarks as none were provided");
return null;
}
if (rootBookmarksFolder.mEntries.size() != 1) {
Log.e(TAG, "ATTENTION: more than one top-level partner bookmarks, ignored");
return null;
}
readBookmarkHierarchy(
rootBookmarksFolder,
new HashSet<PartnerBookmarksReader.Bookmark>());
return null;
}