List of usage examples for java.util IdentityHashMap put
public V put(K key, V value)
From source file:org.apache.solr.handler.component.StatsField.java
/** * Computes a base {@link DocSet} for the current request to be used * when computing global stats for the local index. * * This is typically the same as the main DocSet for the {@link ResponseBuilder} * unless {@link CommonParams#TAG tag}ged filter queries have been excluded using * the {@link CommonParams#EXCLUDE ex} local param *//*w w w .j a va 2 s . c o m*/ public DocSet computeBaseDocSet() throws IOException { DocSet docs = rb.getResults().docSet; Map<?, ?> tagMap = (Map<?, ?>) rb.req.getContext().get("tags"); if (excludeTagList.isEmpty() || null == tagMap) { // either the exclude list is empty, or there // aren't any tagged filters to exclude anyway. return docs; } IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<Query, Boolean>(); for (String excludeTag : excludeTagList) { Object olst = tagMap.get(excludeTag); // tagMap has entries of List<String,List<QParser>>, but subject to change in the future if (!(olst instanceof Collection)) continue; for (Object o : (Collection<?>) olst) { if (!(o instanceof QParser)) continue; QParser qp = (QParser) o; try { excludeSet.put(qp.getQuery(), Boolean.TRUE); } catch (SyntaxError e) { // this shouldn't be possible since the request should have already // failed when attempting to execute the query, but just in case... throw new SolrException(ErrorCode.BAD_REQUEST, "Excluded query can't be parsed: " + originalParam + " due to: " + e.getMessage(), e); } } } if (excludeSet.size() == 0) return docs; List<Query> qlist = new ArrayList<Query>(); // add the base query if (!excludeSet.containsKey(rb.getQuery())) { qlist.add(rb.getQuery()); } // add the filters if (rb.getFilters() != null) { for (Query q : rb.getFilters()) { if (!excludeSet.containsKey(q)) { qlist.add(q); } } } // get the new base docset for this facet return searcher.getDocSet(qlist); }
From source file:org.lilyproject.process.test.DecoratorTest.java
@Test public void test() throws Exception { LilyProxy lilyProxy = createLilyProxy(); LilyClient client = lilyProxy.getLilyServerProxy().getClient(); RepositoryModelImpl repositoryModel = new RepositoryModelImpl( lilyProxy.getLilyServerProxy().getZooKeeper()); repositoryModel.create("repo1"); assertTrue(repositoryModel.waitUntilRepositoryInState("repo1", RepositoryLifecycleState.ACTIVE, 60000L)); repositoryModel.create("repo2"); assertTrue(repositoryModel.waitUntilRepositoryInState("repo2", RepositoryLifecycleState.ACTIVE, 60000L)); repositoryModel.close();/*from w w w . ja v a2s. c o m*/ // Make a schema TypeManager typeMgr = client.getDefaultRepository().getTypeManager(); QName field1 = new QName("ns", "f1"); FieldType fieldType1 = typeMgr.newFieldType(typeMgr.getValueType("STRING"), field1, Scope.NON_VERSIONED); fieldType1 = typeMgr.createFieldType(fieldType1); QName field2 = new QName("ns", "f2"); FieldType fieldType2 = typeMgr.newFieldType(typeMgr.getValueType("STRING"), field2, Scope.NON_VERSIONED); fieldType2 = typeMgr.createFieldType(fieldType2); QName typeName = new QName("ns", "rt1"); RecordType recordType = typeMgr.newRecordType(typeName); recordType.addFieldTypeEntry(fieldType1.getId(), false); recordType.addFieldTypeEntry(fieldType2.getId(), false); recordType = typeMgr.createRecordType(recordType); DecoratingRepositoryManager repositoryMgr = (DecoratingRepositoryManager) lilyProxy.getLilyServerProxy() .getLilyServerTestingUtility().getRuntime().getModuleById("repository").getApplicationContext() .getBean("repositoryManager"); IdentityHashMap<Object, Object> chains = new IdentityHashMap<Object, Object>(); // Test the decorator is applied for each repository and each table for (String repositoryName : new String[] { "default", "repo1", "repo2" }) { LRepository repository = client.getRepository(repositoryName); repository.getTableManager().createTable("table1"); repository.getTableManager().createTable("table2"); for (String tableName : new String[] { "record", "table1", "table2" }) { LTable table = repository.getTable(tableName); Record record = table.newRecord(); record.setRecordType(typeName); record.setField(field1, "foobar"); record = table.create(record); assertEquals("foo", record.getField(field2)); assertEquals("foo", table.read(record.getId()).getField(field2)); // Test we can get access to our test decorator: this is something that is occasionally useful // in test cases to check certain conditions, e.g. if the decorator would have async side effects. RepositoryDecoratorChain chain = repositoryMgr.getRepositoryDecoratorChain(repositoryName, tableName); assertNotNull(chain); assertNotNull(chain.getDecorator(TestRepositoryDecoratorFactory.NAME)); chains.put(chain.getDecorator(TestRepositoryDecoratorFactory.NAME), null); assertEquals(2, chain.getEntries().size()); } } // There should be one instance of the decorator created for each repository-table combination (that // was accessed) assertEquals(3 * 3, chains.size()); // Check that if we ask the same table twice, we get the same instance (verifies cache works) assertTrue(client.getRepository("repo1").getTable("table1") == client.getRepository("repo1") .getTable("table1")); lilyProxy.stop(); // Check each of the decorators was properly closed assertEquals(9, TestRepositoryDecoratorFactory.CLOSE_COUNT.get()); }
From source file:org.apache.solr.request.SimpleFacets.java
License:asdf
protected DocSet computeDocSet(DocSet baseDocSet, List<String> excludeTagList) throws SyntaxError, IOException { Map<?, ?> tagMap = (Map<?, ?>) req.getContext().get("tags"); // rb can be null if facets are being calculated from a RequestHandler e.g. MoreLikeThisHandler if (tagMap == null || rb == null) { return baseDocSet; }/* www . jav a2 s .co m*/ IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<>(); for (String excludeTag : excludeTagList) { Object olst = tagMap.get(excludeTag); // tagMap has entries of List<String,List<QParser>>, but subject to change in the future if (!(olst instanceof Collection)) continue; for (Object o : (Collection<?>) olst) { if (!(o instanceof QParser)) continue; QParser qp = (QParser) o; excludeSet.put(qp.getQuery(), Boolean.TRUE); } } if (excludeSet.size() == 0) return baseDocSet; List<Query> qlist = new ArrayList<>(); // add the base query if (!excludeSet.containsKey(rb.getQuery())) { qlist.add(rb.getQuery()); } // add the filters if (rb.getFilters() != null) { for (Query q : rb.getFilters()) { if (!excludeSet.containsKey(q)) { qlist.add(q); } } } // get the new base docset for this facet DocSet base = searcher.getDocSet(qlist); if (rb.grouping() && rb.getGroupingSpec().isTruncateGroups()) { Grouping grouping = new Grouping(searcher, null, rb.getQueryCommand(), false, 0, false); grouping.setWithinGroupSort(rb.getGroupingSpec().getSortWithinGroup()); if (rb.getGroupingSpec().getFields().length > 0) { grouping.addFieldCommand(rb.getGroupingSpec().getFields()[0], req); } else if (rb.getGroupingSpec().getFunctions().length > 0) { grouping.addFunctionCommand(rb.getGroupingSpec().getFunctions()[0], req); } else { return base; } AllGroupHeadsCollector allGroupHeadsCollector = grouping.getCommands().get(0).createAllGroupCollector(); searcher.search(base.getTopFilter(), allGroupHeadsCollector); return new BitDocSet(allGroupHeadsCollector.retrieveGroupHeads(searcher.maxDoc())); } else { return base; } }
From source file:ome.services.util.ServiceHandler.java
/** * public for testing purposes./*from w ww . j av a2 s.co m*/ */ public String getResultsString(Object o, IdentityHashMap<Object, String> cache) { if (o == null) { return "null"; } if (cache == null) { cache = new IdentityHashMap<Object, String>(); } else { if (cache.containsKey(o)) { return (String) cache.get(o); } } if (o instanceof Collection) { int count = 0; StringBuilder sb = new StringBuilder(128); sb.append("("); Collection c = (Collection) o; for (Object obj : (c)) { if (count > 0) { sb.append(", "); } if (count > 2) { sb.append("... "); sb.append(c.size() - 3); sb.append(" more"); break; } sb.append(obj); count++; } sb.append(")"); return sb.toString(); } else if (o instanceof Map) { Map map = (Map) o; int count = 0; StringBuilder sb = new StringBuilder(); sb.append("{"); for (Object k : map.keySet()) { if (count > 0) { sb.append(", "); } if (count > 2) { sb.append("... "); sb.append(map.size() - 3); sb.append(" more"); break; } sb.append(k); sb.append("="); cache.put(o, o.getClass().getName() + ":" + System.identityHashCode(o)); sb.append(getResultsString(map.get(k), cache)); count++; } sb.append("}"); return sb.toString(); } else if (o.getClass().isArray()) { int length = Array.getLength(o); if (length == 0) { return "[]"; } StringBuilder sb = new StringBuilder(128); sb.append("["); for (int i = 0; i < length; i++) { if (i != 0) { sb.append(", "); } if (i > 2) { sb.append("... "); sb.append(i - 2); sb.append(" more"); break; } sb.append(Array.get(o, i)); } sb.append("]"); return sb.toString(); } else { return o.toString(); } }
From source file:org.openmrs.module.ModuleFileParser.java
/** * load in extensions/* ww w. j a v a 2 s . c o m*/ * * @param root * @param configVersion * @return */ private IdentityHashMap<String, String> getExtensions(Element root, String configVersion) { IdentityHashMap<String, String> extensions = new IdentityHashMap<String, String>(); NodeList extensionNodes = root.getElementsByTagName("extension"); if (extensionNodes.getLength() > 0) { log.debug("# extensions: " + extensionNodes.getLength()); int i = 0; while (i < extensionNodes.getLength()) { Node node = extensionNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String point = "", extClass = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("point".equals(childNode.getNodeName())) { point = childNode.getTextContent().trim(); } else if ("class".equals(childNode.getNodeName())) { extClass = childNode.getTextContent().trim(); } x++; } log.debug("point: " + point + " class: " + extClass); // point and class are required if (point.length() > 0 && extClass.length() > 0) { if (point.indexOf(Extension.extensionIdSeparator) != -1) { log.warn("Point id contains illegal character: '" + Extension.extensionIdSeparator + "'"); } else { extensions.put(point, extClass); } } else { log.warn("'point' and 'class' are required for extensions. Given '" + point + "' and '" + extClass + "'"); } i++; } } return extensions; }
From source file:org.batoo.jpa.core.impl.manager.EntityManagerImpl.java
/** * Cascaded implementation of {@link #merge(Object)}. * <p>/*from w w w.jav a 2 s. c o m*/ * Also manages a direct or indirect requirement to an implicit flush. * * @param entity * the entity to cascade * @param requiresFlush * if an implicit flush is required * @param processed * registry of processed entities * @param instances * the persisted instances * @param cascade * cascades the merge operation * @param <T> * the type of the entity * @return true if an implicit flush is required, false otherwise * * @since 2.0.0 */ @SuppressWarnings("unchecked") public <T> T mergeImpl(T entity, MutableBoolean requiresFlush, IdentityHashMap<Object, Object> processed, LinkedList<ManagedInstance<?>> instances, boolean cascade) { if (entity == null) { return null; } // if already processed just return final T processedEntity = (T) processed.get(entity); if (processedEntity != null) { return processedEntity; } // try to locate the instance in the session ManagedInstance<T> instance = this.session.get(entity); Class<?> clazz = entity.getClass(); if (entity instanceof EnhancedInstance) { clazz = clazz.getSuperclass(); } final EntityTypeImpl<T> type = (EntityTypeImpl<T>) this.metamodel.entity(clazz); // if it is in the session then test its status if (instance != null) { // if it is a removed entity then throw if (instance.getStatus() == Status.REMOVED) { throw new IllegalArgumentException("Entity has been previously removed"); } // if it is an existing instance then merge and return if ((instance.getStatus() == Status.MANAGED) || (instance.getStatus() == Status.NEW)) { processed.put(entity, instance.getInstance()); if (instance.getStatus() == Status.NEW) { instances.add(instance); } if (instance.getInstance() != entity) { instance.mergeWith(this, entity, requiresFlush, processed, instances); } else { this.cascadeMerge(type, entity, requiresFlush, processed, instances); } return instance.getInstance(); } } // get the id of the entity final Object id = type.getInstanceId(entity); // if it has an id try to locate instance in the database if (id != null) { T existingEntity = null; try { existingEntity = this.find((Class<T>) clazz, id); } catch (final NoResultException e) { } // if it is found in the database then merge and return if (existingEntity != null) { instance = (ManagedInstance<T>) ((EnhancedInstance) existingEntity) .__enhanced__$$__getManagedInstance(); processed.put(entity, instance.getInstance()); instance.mergeWith(this, entity, requiresFlush, processed, instances); return instance.getInstance(); } } // it is a new instance, create a new instance and merge with it final ManagedId<T> managedId = new ManagedId<T>(id, type); instance = type.getManagedInstanceById(this.session, managedId, false); instance.setStatus(Status.NEW); instance.enhanceCollections(); this.session.putExternal(instance); processed.put(entity, instance.getInstance()); instances.add(instance); instance.mergeWith(this, entity, requiresFlush, processed, instances); if (!instance.fillIdValues()) { requiresFlush.setValue(true); } return instance.getInstance(); }
From source file:net.sf.jasperreports.extensions.DefaultExtensionsRegistry.java
protected List<ExtensionsRegistry> loadRegistries() { //there is no identity linked hash map/set, using separate map and list IdentityHashMap<ExtensionsRegistry, Object> registrySet = new IdentityHashMap<>(); List<ExtensionsRegistry> allRegistries = new ArrayList<ExtensionsRegistry>(); List<ClassLoaderResource> extensionResources = loadExtensionPropertyResources(); for (ClassLoaderResource extensionResource : extensionResources) { ClassLoader classLoader = extensionResource.getClassLoader(); Map<URL, URLRegistries> classLoaderRegistries = getClassLoaderRegistries(classLoader); URL url = extensionResource.getUrl(); List<ExtensionsRegistry> registries; Map<String, Exception> registryExceptions = new LinkedHashMap<String, Exception>(); synchronized (classLoaderRegistries) { URLRegistries urlRegistries = classLoaderRegistries.get(url); if (urlRegistries == null) { if (log.isDebugEnabled()) { log.debug("Loading JasperReports extension properties resource " + url); }/* www. j a va2 s .c o m*/ JRPropertiesMap properties = JRPropertiesMap.loadProperties(url); URL duplicateURL = detectDuplicate(properties, classLoaderRegistries);//search across classloaders? if (duplicateURL == null) { registries = loadRegistries(properties, registryExceptions); } else { log.warn("Extension resource " + url + " was found to be a duplicate of " + duplicateURL + " in classloader " + classLoader); registries = Collections.emptyList(); } classLoaderRegistries.put(url, new URLRegistries(properties, registries)); } else { registries = urlRegistries.registries; } } for (Map.Entry<String, Exception> entry : registryExceptions.entrySet()) { log.error("Error instantiating extensions registry for " + entry.getKey() + " from " + url, entry.getValue()); } for (ExtensionsRegistry extensionsRegistry : registries) { //detecting identity duplicates boolean added = registrySet.put(extensionsRegistry, Boolean.FALSE) == null; if (added) { allRegistries.add(extensionsRegistry); } else if (log.isDebugEnabled()) { log.debug("Found duplicate extension registry " + extensionsRegistry); } } } return allRegistries; }
From source file:ded.ui.DiagramController.java
/** Copy the selected entities to the (application) clipboard. */ public void copySelected() { IdentityHashSet<Controller> selControllers = this.getAllSelected(); if (selControllers.isEmpty()) { this.errorMessageBox("Nothing is selected to copy."); return;//from w ww .ja v a2 s . c o m } // Collect all the selected elements. IdentityHashSet<Entity> selEntities = new IdentityHashSet<Entity>(); IdentityHashSet<Inheritance> selInheritances = new IdentityHashSet<Inheritance>(); IdentityHashSet<Relation> selRelations = new IdentityHashSet<Relation>(); for (Controller c : selControllers) { if (c instanceof EntityController) { selEntities.add(((EntityController) c).entity); } if (c instanceof InheritanceController) { selInheritances.add(((InheritanceController) c).inheritance); } if (c instanceof RelationController) { selRelations.add(((RelationController) c).relation); } } // Map from elements in the original to their counterpart in the copy. IdentityHashMap<Entity, Entity> entityToCopy = new IdentityHashMap<Entity, Entity>(); IdentityHashMap<Inheritance, Inheritance> inheritanceToCopy = new IdentityHashMap<Inheritance, Inheritance>(); // Construct a new Diagram with just the selected elements. Diagram copy = new Diagram(); for (Entity e : selEntities) { Entity eCopy = new Entity(e); entityToCopy.put(e, eCopy); copy.entities.add(eCopy); } for (Inheritance i : selInheritances) { // See if the parent entity is among those we are copying. Entity parentCopy = entityToCopy.get(i.parent); if (parentCopy == null) { // No, so we'll skip the inheritance too. } else { Inheritance iCopy = new Inheritance(i, parentCopy); inheritanceToCopy.put(i, iCopy); copy.inheritances.add(iCopy); } } for (Relation r : selRelations) { RelationEndpoint startCopy = copyRelationEndpoint(r.start, entityToCopy, inheritanceToCopy); RelationEndpoint endCopy = copyRelationEndpoint(r.end, entityToCopy, inheritanceToCopy); if (startCopy == null || endCopy == null) { // Skip the relation. } else { copy.relations.add(new Relation(r, startCopy, endCopy)); } } // Make sure the Diagram is well-formed. try { // This is quadratic... copy.selfCheck(); } catch (Throwable t) { this.errorMessageBox("Internal error: failed to create a well-formed copy: " + t); return; } // Copy it as a string to the system clipboard. StringSelection data = new StringSelection(copy.toJSONString()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(data, data); clipboard = Toolkit.getDefaultToolkit().getSystemSelection(); if (clipboard != null) { clipboard.setContents(data, data); } }
From source file:org.jspresso.framework.application.backend.AbstractBackendController.java
private IEntity refineEntity(IComponent target, IdentityHashMap<IComponent, Object> traversed) { if (traversed.containsKey(target)) { return null; }/*from w ww .jav a2s . com*/ traversed.put(target, null); if (target instanceof IEntity) { return (IEntity) target; } if (target != null) { return refineEntity(target.getOwningComponent(), traversed); } return null; }