List of usage examples for java.util LinkedHashMap values
public Collection<V> values()
From source file:org.pentaho.reporting.platform.plugin.ParameterXmlContentHandler.java
private Map<String, Object> computeRealInput(final ParameterContext parameterContext, final LinkedHashMap<String, ParameterDefinitionEntry> reportParameters, final String computedOutputTarget, final ValidationResult result) { final Map<String, Object> realInputs = new HashMap<String, Object>(); realInputs.put(SYS_PARAM_DESTINATION, lookupDestination()); final ReportParameterValues parameterValues = result.getParameterValues(); for (final ParameterDefinitionEntry parameter : reportParameters.values()) { final String parameterName = parameter.getName(); final Object parameterFromReport = parameterValues.get(parameterName); if (parameterFromReport != null) { // always prefer the report parameter. The user's input has been filtered already and values // may have been replaced by a post-processing formula. ////from www.jav a 2 s . co m realInputs.put(parameterName, parameterFromReport); continue; } // the parameter values collection only contains declared parameter. So everything else will // be handled now. This is also the time to handle rejected parameter. For these parameter, // the calculated value for the report is <null>. final Object value = inputs.get(parameterName); if (value == null) { // have no value, so we use the default value .. realInputs.put(parameterName, null); continue; } try { final Object translatedValue = ReportContentUtil.computeParameterValue(parameterContext, parameter, value); if (translatedValue != null) { realInputs.put(parameterName, translatedValue); } else { realInputs.put(parameterName, null); } } catch (Exception be) { if (logger.isDebugEnabled()) { logger.debug(Messages.getInstance().getString("ReportPlugin.debugParameterCannotBeConverted", parameter.getName(), String.valueOf(value)), be); } } } // thou cannot override the output target with invalid values .. realInputs.put(SYS_PARAM_OUTPUT_TARGET, computedOutputTarget); return realInputs; }
From source file:org.apache.atlas.hive.hook.HiveHook.java
private <T extends Entity> void processHiveEntity(HiveMetaStoreBridge dgiBridge, HiveEventContext event, T entity, Set<String> dataSetsProcessed, SortedMap<T, Referenceable> dataSets, Set<Referenceable> entities) throws AtlasHookException { try {//from w ww. j a v a2 s. co m if (entity.getType() == Type.TABLE || entity.getType() == Type.PARTITION) { final String tblQFName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), entity.getTable()); if (!dataSetsProcessed.contains(tblQFName)) { LinkedHashMap<Type, Referenceable> result = createOrUpdateEntities(dgiBridge, event, entity, false); dataSets.put(entity, result.get(Type.TABLE)); dataSetsProcessed.add(tblQFName); entities.addAll(result.values()); } } else if (entity.getType() == Type.DFS_DIR) { URI location = entity.getLocation(); if (location != null) { final String pathUri = lower(new Path(location).toString()); LOG.debug("Registering DFS Path {} ", pathUri); if (!dataSetsProcessed.contains(pathUri)) { Referenceable hdfsPath = dgiBridge.fillHDFSDataSet(pathUri); dataSets.put(entity, hdfsPath); dataSetsProcessed.add(pathUri); entities.add(hdfsPath); } } } } catch (Exception e) { throw new AtlasHookException("HiveHook.processHiveEntity() failed.", e); } }
From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java
/** * For the given server with serverKey ID, takes his {@link #getBaseLogListFrom(String)} * reply as toProcessLogList and fill the serversLogPresenceList for each base log * adding the serverKey to the list of presence for that base log. * /*w w w . j a v a2s . c o m*/ * If finalLogList is not null, also adds the missing entries to it. * * @param serverKey * @param toProcessLogList * @param finalLogList * @param serversLogPresenceList */ private void fillServerPresenceList(String serverKey, LinkedHashMap<FTPFile, String> toProcessLogList, LinkedHashMap<FTPFile, String> finalLogList, LinkedHashMap<String, String> serversLogPresenceList) { if (toProcessLogList != null && !toProcessLogList.isEmpty()) { if (finalLogList == null || finalLogList.isEmpty()) { for (String partialUri : toProcessLogList.values()) { serversLogPresenceList.put(partialUri, serverKey); } if (finalLogList != null) finalLogList.putAll(toProcessLogList); } else { for (FTPFile ftpFile : toProcessLogList.keySet()) { String val = toProcessLogList.get(ftpFile); if (finalLogList.containsValue(val)) { serversLogPresenceList.put(val, serversLogPresenceList.get(val) + " " + serverKey); continue; } else { finalLogList.put(ftpFile, val); serversLogPresenceList.put(val, serverKey); } } } } }
From source file:com.day.cq.wcm.foundation.List.java
@SuppressWarnings("unchecked") private boolean init() { if (!inited) { initConfig();/*www . ja v a 2 s .c o m*/ // Note: this iter can also be set from the outside (setPageIterator()) if (pageIterator == null) { PageManager pm = request.getResourceResolver().adaptTo(PageManager.class); // per default we don't want duplicate pages in the result boolean allowDuplicates = properties.get(ALLOW_DUPLICATES_PROPERTY_NAME, false); try { Session session = resource.getResourceResolver().adaptTo(Session.class); // advanced search = querybuilder if (SOURCE_QUERYBUILDER.equals(source)) { QueryBuilder queryBuilder = resource.getResourceResolver().adaptTo(QueryBuilder.class); if (session != null && queryBuilder != null) { try { Query query = queryBuilder .loadQuery(resource.getPath() + "/" + SAVEDQUERY_PROPERTY_NAME, session); if (query != null) { query.setHitsPerPage(limit); SearchResult result = query.getResult(); // store as both page and node iterator pageIterator = new HitBasedPageIterator(pm, result.getHits().iterator(), !allowDuplicates, this.pageFilter); nodeIterator = result.getNodes(); } } catch (Exception e) { log.error("error loading stored querybuilder query from " + resource.getPath(), e); } } // simple search } else if (SOURCE_SEARCH.equals(source)) { if (DEFAULT_QUERY.equals(query)) { pageIterator = EmptyIterator.INSTANCE; } if (queryType != null) { javax.jcr.query.Query jcrQuery = session.getWorkspace().getQueryManager() .createQuery(query, queryType); QueryResult result = jcrQuery.execute(); pageIterator = new NodeBasedPageIterator(pm, result.getNodes(), !allowDuplicates, this.pageFilter); } else { SimpleSearch search = getSearch(resource.getPath()); search.setQuery(query); search.setSearchIn(startIn); // ensure we only get pages search.addPredicate(new Predicate("type", "type").set("type", NameConstants.NT_PAGE)); search.setHitsPerPage(100000); // run simple search SearchResult result = search.getResult(); pageIterator = new HitBasedPageIterator(pm, result.getHits().iterator(), !allowDuplicates, this.pageFilter); } // list child pages } else if (SOURCE_CHILDREN.equals(source)) { // default to current page String parentPath = properties.get(PARENT_PAGE_PROPERTY_NAME, resource.getPath()); Page startPage = pm.getContainingPage(parentPath); if (startPage != null) { // only get pages that are valid (on/off times, hide in nav) // Use default page filter if there is no page filter, because it was working this way // before adding PageFilter support pageIterator = startPage .listChildren(this.pageFilter != null ? this.pageFilter : new PageFilter()); } else { pageIterator = EmptyIterator.INSTANCE; } // list from tags } else if (SOURCE_TAGS.equals(source)) { // default to current page String parentPath = properties.get(TAGS_SEARCH_ROOT_PROPERTY_NAME, resource.getPath()); String[] tags = properties.get(TAGS_PROPERTY_NAME, new String[0]); boolean matchAny = properties.get(TAGS_MATCH_PROPERTY_NAME, "any").equals("any"); Page startPage = pm.getContainingPage(parentPath); if (startPage != null && tags.length > 0) { TagManager tagManager = request.getResourceResolver().adaptTo(TagManager.class); RangeIterator<Resource> results = tagManager.find(startPage.getPath(), tags, matchAny); LinkedHashMap<String, Page> pages = new LinkedHashMap<String, Page>(); while (results.hasNext()) { Resource r = results.next(); Page page = pm.getContainingPage(r); if (page != null && (pageFilter == null || pageFilter.includes(page))) { pages.put(page.getPath(), page); } } pageIterator = pages.values().iterator(); } else { pageIterator = EmptyIterator.INSTANCE; } // fixed list of pages } else { ArrayList<Page> staticPages = new ArrayList<Page>(); String[] statics = properties.get(PAGES_PROPERTY_NAME, new String[0]); for (String path : statics) { Page p = pm.getContainingPage(path); if (p != null && (pageFilter == null || pageFilter.includes(p))) { staticPages.add(p); } } pageIterator = staticPages.iterator(); } } catch (Exception e) { log.error("error creating page iterator", e); } } pages = new ArrayList<Page>(); resources = new ArrayList<Resource>(); if (pageIterator == null) { return false; } // build list of pages and resources from page iterator while (pageIterator.hasNext()) { Page page = pageIterator.next(); pages.add(page); } // apply sort order if present if (orderComparator != null) { Collections.sort(pages, orderComparator); } else if (orderBy != null) { Collections.sort(pages, new PageComparator<Page>(orderBy)); } // apply limit if (pages.size() > limit) { pages = pages.subList(0, limit); } for (Page p : pages) { resources.add(p.getContentResource()); } inited = true; } return true; }
From source file:org.opencms.ui.dialogs.CmsNewDialog.java
/** * Initializes the view selector, using the given view id as an initial value.<p> * * @param startId the start view/*from ww w . jav a 2 s. co m*/ * * @return the start view */ private CmsElementView initViews(CmsUUID startId) { Map<CmsUUID, CmsElementView> viewMap = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()); List<CmsElementView> viewList = new ArrayList<CmsElementView>(viewMap.values()); Collections.sort(viewList, new Comparator<CmsElementView>() { public int compare(CmsElementView arg0, CmsElementView arg1) { return ComparisonChain.start().compare(arg0.getOrder(), arg1.getOrder()).result(); } }); m_viewSelector.setItemCaptionMode(ItemCaptionMode.EXPLICIT); m_typeHelper = createTypeHelper(); m_typeHelper.precomputeTypeLists(A_CmsUI.getCmsObject(), m_folderResource.getRootPath(), A_CmsUI.getCmsObject().getRequestContext().removeSiteRoot(m_folderResource.getRootPath()), viewList, null); // also collect types in LinkedHashMap to preserve order and ensure uniqueness LinkedHashMap<String, CmsResourceTypeBean> allTypes = Maps.newLinkedHashMap(); for (CmsElementView view : viewList) { if (view.hasPermission(A_CmsUI.getCmsObject(), m_folderResource)) { List<CmsResourceTypeBean> typeBeans = m_typeHelper.getPrecomputedTypes(view); if (typeBeans.isEmpty()) { continue; } for (CmsResourceTypeBean typeBean : typeBeans) { allTypes.put(typeBean.getType(), typeBean); } m_viewSelector.addItem(view.getId()); m_viewSelector.setItemCaption(view.getId(), view.getTitle(A_CmsUI.getCmsObject(), A_CmsUI.get().getLocale())); } } m_viewSelector.addItem(VIEW_ALL.getId()); m_viewSelector.setItemCaption(VIEW_ALL.getId(), CmsVaadinUtils.getMessageText(Messages.GUI_VIEW_ALL_0)); m_allTypes = Lists.newArrayList(allTypes.values()); if (allTypes.size() <= 8) { startId = ID_VIEW_ALL; } if (m_viewSelector.getItem(startId) == null) { startId = (CmsUUID) (m_viewSelector.getItemIds().iterator().next()); } m_viewSelector.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { CmsUUID viewId = (CmsUUID) (event.getProperty().getValue()); CmsElementView selectedView; if (viewId.equals(ID_VIEW_ALL)) { selectedView = VIEW_ALL; } else { selectedView = OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()) .get(event.getProperty().getValue()); } init(selectedView, m_defaultLocationCheckbox.getValue().booleanValue()); if (selectedView != VIEW_ALL) { VaadinService.getCurrentRequest().getWrappedSession().setAttribute(SETTING_STANDARD_VIEW, (event.getProperty().getValue())); } } }); if (startId.equals(ID_VIEW_ALL)) { return VIEW_ALL; } else { return OpenCms.getADEManager().getElementViews(A_CmsUI.getCmsObject()).get(startId); } }
From source file:com.impetus.ankush.common.framework.ClusterPreValidator.java
public Map validate(final Map params) { final LinkedHashMap result = new LinkedHashMap(); if (notContainsKey(params, "nodePorts", result)) { return result; }//from w ww. ja v a 2s .c om if (params.containsKey(Constant.Keys.CLUSTERID)) { // Get cluster manager GenericManager<Cluster, Long> clusterManager = AppStoreWrapper.getManager(Constant.Manager.CLUSTER, Cluster.class); // get cluster id string String clusterIdStr = (String) params.get(Constant.Keys.CLUSTERID); // convert cluster id string into long value. Long clusterId = ParserUtil.getLongValue(clusterIdStr, 0); // Get the cluster object from database. Cluster cluster = clusterManager.get(clusterId); ClusterConfig clusterConfig = cluster.getClusterConfig(); // set username params.put(Constant.Keys.USERNAME, clusterConfig.getAuthConf().getUsername()); String pass = clusterConfig.getAuthConf().getPassword(); if (pass != null && !pass.isEmpty()) { params.put(Constant.Keys.PASSWORD, pass); } else { params.put(Constant.Keys.PRIVATEKEY, clusterConfig.getAuthConf().getPrivateKey()); } params.put(Constant.Agent.Key.AGENT_INSTALL_DIR, clusterConfig.getAgentInstallDir()); } else { if (notContainsKey(params, Constant.Keys.USERNAME, result)) { return result; } if (notContainsKey(params, Constant.Keys.PASSWORD, result)) { return result; } if (notContainsKey(params, Constant.Keys.PRIVATEKEY, result)) { return result; } } final String username = (String) params.get(Constant.Keys.USERNAME); final String password = (String) params.get(Constant.Keys.PASSWORD); final String privateKey = (String) params.get(Constant.Keys.PRIVATEKEY); final Map nodePorts = (Map) params.get("nodePorts"); Set<String> nodes = nodePorts.keySet(); final boolean authUsingPassword = (password != null && !password.isEmpty()); final String authInfo = authUsingPassword ? password : privateKey; try { final Semaphore semaphore = new Semaphore(nodes.size()); for (final String hostname : nodes) { semaphore.acquire(); AppStoreWrapper.getExecutor().execute(new Runnable() { @Override public void run() { SSHExec conn = null; LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); try { conn = SSHUtils.connectToNode(hostname, username, password, privateKey); map = getValidationMap(params, username, password, nodePorts, authUsingPassword, authInfo, hostname, conn); } catch (Exception e) { map.put("error", new Status("Error", "Unable to perform validations", CRITICAL)); logger.error(e.getMessage(), e); } finally { // setting overall status. map.put("status", getOverAllStatus((Collection) map.values())); // putting map against node. result.put(hostname, map); if (semaphore != null) { semaphore.release(); } if (conn != null) { conn.disconnect(); } } } }); } semaphore.acquire(nodes.size()); result.put("status", true); } catch (Exception e) { String message = e.getMessage(); if (message == null) { message = "Unable to validate nodes"; } result.put("error", Collections.singletonList(message)); result.put("status", false); logger.error(e.getMessage(), e); } return result; }
From source file:com.tesora.dve.common.catalog.CatalogDAO.java
public PersistentGroup buildAllSitesGroup() throws PEException { List<PersistentSite> sites = findAllPersistentSites(); final LinkedHashMap<String, PersistentSite> uniqueURLS = new LinkedHashMap<String, PersistentSite>(); for (PersistentSite ps : sites) { String key = ps.getMasterUrl(); PersistentSite already = uniqueURLS.get(key); if (already == null) uniqueURLS.put(key, ps);// www .jav a 2 s . c o m } return new PersistentGroup(uniqueURLS.values()); }
From source file:net.minecraftforge.registries.GameData.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static Multimap<ResourceLocation, ResourceLocation> injectSnapshot( Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot, boolean injectFrozenData, boolean isLocalWorld) { FMLLog.log.info("Injecting existing registry data into this {} instance", FMLCommonHandler.instance().getEffectiveSide().isServer() ? "server" : "client"); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.validateContent(name)); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name)); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates()); List<ResourceLocation> missingRegs = snapshot.keySet().stream() .filter(name -> !RegistryManager.ACTIVE.registries.containsKey(name)).collect(Collectors.toList()); if (missingRegs.size() > 0) { String text = "Forge Mod Loader detected missing/unknown registrie(s).\n\n" + "There are " + missingRegs.size() + " missing registries in this save.\n" + "If you continue the missing registries will get removed.\n" + "This may cause issues, it is advised that you create a world backup before continuing.\n\n" + "Missing Registries:\n"; for (ResourceLocation s : missingRegs) text += s.toString() + "\n"; if (!StartupQuery.confirm(text)) StartupQuery.abort();//from ww w.ja v a 2 s. com } RegistryManager STAGING = new RegistryManager("STAGING"); final Map<ResourceLocation, Map<ResourceLocation, Integer[]>> remaps = Maps.newHashMap(); final LinkedHashMap<ResourceLocation, Map<ResourceLocation, Integer>> missing = Maps.newLinkedHashMap(); // Load the snapshot into the "STAGING" registry snapshot.forEach((key, value) -> { final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(key); remaps.put(key, Maps.newLinkedHashMap()); missing.put(key, Maps.newHashMap()); loadPersistentDataToStagingRegistry(RegistryManager.ACTIVE, STAGING, remaps.get(key), missing.get(key), key, value, clazz); }); snapshot.forEach((key, value) -> { value.dummied.forEach(dummy -> { Map<ResourceLocation, Integer> m = missing.get(key); ForgeRegistry<?> reg = STAGING.getRegistry(key); // Currently missing locally, we just inject and carry on if (m.containsKey(dummy)) { if (reg.markDummy(dummy, m.get(dummy))) m.remove(dummy); } else if (isLocalWorld) { if (ForgeRegistry.DEBUG) FMLLog.log.debug("Registry {}: Resuscitating dummy entry {}", key, dummy); } else { // The server believes this is a dummy block identity, but we seem to have one locally. This is likely a conflict // in mod setup - Mark this entry as a dummy int id = reg.getID(dummy); FMLLog.log.warn( "Registry {}: The ID {} is currently locally mapped - it will be replaced with a dummy for this session", key, id); reg.markDummy(dummy, id); } }); }); int count = missing.values().stream().mapToInt(Map::size).sum(); if (count > 0) { FMLLog.log.debug("There are {} mappings missing - attempting a mod remap", count); Multimap<ResourceLocation, ResourceLocation> defaulted = ArrayListMultimap.create(); Multimap<ResourceLocation, ResourceLocation> failed = ArrayListMultimap.create(); missing.entrySet().stream().filter(e -> e.getValue().size() > 0).forEach(m -> { ResourceLocation name = m.getKey(); ForgeRegistry<?> reg = STAGING.getRegistry(name); RegistryEvent.MissingMappings<?> event = reg.getMissingEvent(name, m.getValue()); MinecraftForge.EVENT_BUS.post(event); List<MissingMappings.Mapping<?>> lst = event.getAllMappings().stream() .filter(e -> e.getAction() == MissingMappings.Action.DEFAULT).collect(Collectors.toList()); if (!lst.isEmpty()) { FMLLog.log.error("Unidentified mapping from registry {}", name); lst.forEach(map -> { FMLLog.log.error(" {}: {}", map.key, map.id); if (!isLocalWorld) defaulted.put(name, map.key); }); } event.getAllMappings().stream().filter(e -> e.getAction() == MissingMappings.Action.FAIL) .forEach(fail -> failed.put(name, fail.key)); final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name); processMissing(clazz, name, STAGING, event, m.getValue(), remaps.get(name), defaulted.get(name), failed.get(name)); }); if (!defaulted.isEmpty() && !isLocalWorld) return defaulted; if (!defaulted.isEmpty()) { StringBuilder buf = new StringBuilder(); buf.append("Forge Mod Loader detected missing registry entries.\n\n").append("There are ") .append(defaulted.size()).append(" missing entries in this save.\n") .append("If you continue the missing entries will get removed.\n") .append("A world backup will be automatically created in your saves directory.\n\n"); defaulted.asMap().forEach((name, entries) -> { buf.append("Missing ").append(name).append(":\n"); entries.forEach(rl -> buf.append(" ").append(rl).append("\n")); }); boolean confirmed = StartupQuery.confirm(buf.toString()); if (!confirmed) StartupQuery.abort(); try { String skip = System.getProperty("fml.doNotBackup"); if (skip == null || !"true".equals(skip)) { ZipperUtil.backupWorld(); } else { for (int x = 0; x < 10; x++) FMLLog.log.error("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!"); } } catch (IOException e) { StartupQuery.notify("The world backup couldn't be created.\n\n" + e); StartupQuery.abort(); } } if (!defaulted.isEmpty()) { if (isLocalWorld) FMLLog.log.error( "There are unidentified mappings in this world - we are going to attempt to process anyway"); } } if (injectFrozenData) { // If we're loading from disk, we can actually substitute air in the block map for anything that is otherwise "missing". This keeps the reference in the map, in case // the block comes back later missing.forEach((name, m) -> { ForgeRegistry<?> reg = STAGING.getRegistry(name); m.forEach((rl, id) -> reg.markDummy(rl, id)); }); // If we're loading up the world from disk, we want to add in the new data that might have been provisioned by mods // So we load it from the frozen persistent registry RegistryManager.ACTIVE.registries.forEach((name, reg) -> { final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name); loadFrozenDataToStagingRegistry(STAGING, name, remaps.get(name), clazz); }); } // Validate that all the STAGING data is good STAGING.registries.forEach((name, reg) -> reg.validateContent(name)); // Load the STAGING registry into the ACTIVE registry for (Map.Entry<ResourceLocation, ForgeRegistry<? extends IForgeRegistryEntry<?>>> r : RegistryManager.ACTIVE.registries .entrySet()) { final Class<? extends IForgeRegistryEntry> registrySuperType = RegistryManager.ACTIVE .getSuperType(r.getKey()); loadRegistry(r.getKey(), STAGING, RegistryManager.ACTIVE, registrySuperType, true); } // Dump the active registry RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name)); // Tell mods that the ids have changed Loader.instance().fireRemapEvent(remaps, false); // The id map changed, ensure we apply object holders ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // Return an empty list, because we're good return ArrayListMultimap.create(); }
From source file:org.powertac.common.config.Configurator.java
/** * Creates and configures instances of the given class. In the configuration, * we expect to see a property of the form pkg.class.instances = a, b, c, ... * where a, b, c, etc. are the names of instances of the class to be created * and configured. These names are provided to the instances through their * constructors, and are expected to show up in the configuration as * instance names in clauses of the form * pkg.class.name.property = value./* w w w . ja v a 2 s . c om*/ * Returns empty list in case instances cannot be created. */ public Collection<?> configureInstances(Class<?> type) { // If we don't have a configuration, we cannot do much. if (config == null) { log.error("Cannot configure - no Configuration set"); return new ArrayList<Object>(); } // compute the key for the instance list String classname = type.getName(); log.debug("configuring instances for type " + classname); Configuration subset = extractSubsetForClassname(classname); // we should have a clause with the key "instances" giving the item // names, and a set of clauses for each item if (null == createdInstances.get(type)) { createdInstances.put(type, new HashSet<>()); } Set<String> existingNames = createdInstances.get(type); List<Object> rawNames = subset.getList("instances"); List<String> names = rawNames.stream().map(n -> n.toString()).filter(n -> !n.isEmpty()) .collect(Collectors.toList()); if (names.size() == 0) { log.warn("No instance names specified for class " + classname); return names; } dumpInstanceListMaybe(type, existingNames, names); // for each name, create an instance, add it to the result, and // configure it. LinkedHashMap<String, Object> itemMap = new LinkedHashMap<String, Object>(); for (String name : names) { existingNames.add(name); try { Constructor<?> constructor = type.getConstructor(String.class); Object item = constructor.newInstance(name); itemMap.put(name, item); } catch (Exception e) { log.error("Unable to create instance " + name + " of class " + type + ": " + e.toString()); } } // We now have a map of names and items to be configured. // We iterate through the map to avoid problems with items that did // not get created, although that seems far-fetched. for (String name : itemMap.keySet()) { configureInstance(itemMap.get(name), subset.subset(name), name); } return itemMap.values(); }
From source file:me.piebridge.bible.Bible.java
private boolean addSuggest(LinkedHashMap<String, String> osiss, String value, String osis, int limit) { if (!osiss.values().contains(osis)) { String text = get(TYPE.HUMAN, bible.getPosition(TYPE.OSIS, osis)); Log.d(TAG, "add suggest, text=" + text + ", data=" + osis); osiss.put(text, osis);//ww w .j a va 2 s . c o m } if (limit != -1 && osiss.size() >= limit) { Log.d(TAG, "arrive limit " + limit); return true; } return false; }