List of usage examples for java.util LinkedHashMap entrySet
public Set<Map.Entry<K, V>> entrySet()
From source file:net.sf.jabref.importer.fetcher.ACMPortalFetcher.java
@Override public boolean processQueryGetPreview(String query, FetcherPreviewDialog preview, OutputPrinter status) { this.terms = query; piv = 0;/*from ww w . j a v a 2 s .co m*/ shouldContinue = true; acmOrGuide = acmButton.isSelected(); fetchAbstract = absCheckBox.isSelected(); String address = makeUrl(); LinkedHashMap<String, JLabel> previews = new LinkedHashMap<>(); try { URLDownload dl = new URLDownload(address); String page = dl.downloadToString(Globals.prefs.getDefaultEncoding()); int hits = getNumberOfHits(page, RESULTS_FOUND_PATTERN, ACMPortalFetcher.HITS_PATTERN); int index = page.indexOf(RESULTS_FOUND_PATTERN); if (index >= 0) { page = page.substring(index + RESULTS_FOUND_PATTERN.length()); } if (hits == 0) { status.showMessage(Localization.lang("No entries found for the search string '%0'", terms), Localization.lang("Search %0", getTitle()), JOptionPane.INFORMATION_MESSAGE); return false; } else if (hits > 20) { status.showMessage( Localization.lang("%0 entries found. To reduce server load, only %1 will be downloaded.", String.valueOf(hits), String.valueOf(PER_PAGE)), Localization.lang("Search %0", getTitle()), JOptionPane.INFORMATION_MESSAGE); } hits = getNumberOfHits(page, PAGE_RANGE_PATTERN, ACMPortalFetcher.MAX_HITS_PATTERN); parse(page, Math.min(hits, PER_PAGE), previews); for (Map.Entry<String, JLabel> entry : previews.entrySet()) { preview.addEntry(entry.getKey(), entry.getValue()); } return true; } catch (MalformedURLException e) { LOGGER.warn("Problem with ACM fetcher URL", e); } catch (ConnectException e) { status.showMessage(Localization.lang("Could not connect to %0", getTitle()), Localization.lang("Search %0", getTitle()), JOptionPane.ERROR_MESSAGE); LOGGER.warn("Problem with ACM connection", e); } catch (IOException e) { status.showMessage(e.getMessage(), Localization.lang("Search %0", getTitle()), JOptionPane.ERROR_MESSAGE); LOGGER.warn("Problem with ACM Portal", e); } return false; }
From source file:me.piebridge.bible.Bible.java
public LinkedHashMap<String, String> getOsiss(String book, int limit) { LinkedHashMap<String, String> osiss = new LinkedHashMap<String, String>(); if (book != null) { // fix for zhcn book = book.replace("", ""); book = book.replace("", ""); book = book.replace("", "??"); book = book.replace(SearchManager.SUGGEST_URI_PATH_QUERY, "").replace(" ", "").toLowerCase(Locale.US); }/*from w w w . j a v a 2 s . c om*/ Log.d(TAG, "book: " + book); ArrayList<Entry<String, String>> maps = new ArrayList<Entry<String, String>>(); for (Entry<String, String> entry : searchshort.entrySet()) { maps.add(entry); } for (Entry<String, String> entry : searchfull.entrySet()) { maps.add(entry); } for (LinkedHashMap<String, String> map : getMaps(TYPE.HUMAN)) { for (Entry<String, String> entry : map.entrySet()) { maps.add(entry); } } for (LinkedHashMap<String, String> map : getMaps(TYPE.OSIS)) { for (Entry<String, String> entry : map.entrySet()) { maps.add(entry); } } if (book == null || "".equals(book)) { for (int i = 0; i < this.osiss.size() && i < limit; ++i) { osiss.put(humans.get(i), this.osiss.get(i)); } return osiss; } for (Entry<String, String> entry : maps) { if (checkStartSuggest(osiss, entry.getValue(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkContainSuggest(osiss, entry.getValue(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkStartSuggest(osiss, entry.getKey(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkContainSuggest(osiss, entry.getKey(), entry.getValue(), book, limit)) { return osiss; } } String osis = ""; String chapter = ""; if (osiss.size() == 0) { ArrayList<OsisItem> items = OsisItem.parseSearch(book, mContext); if (items.size() == 1) { OsisItem item = items.get(0); osis = item.book; chapter = item.chapter; } } else if (osiss.size() == 1) { for (Entry<String, String> entry : osiss.entrySet()) { osis = entry.getValue(); chapter = "0"; } } if ("".equals(osis)) { return osiss; } String bookname = get(TYPE.HUMAN, bible.getPosition(TYPE.OSIS, osis)); if (bookname == null) { bookname = osis; } int chapternum = 0; int maxchapter = 0; try { chapternum = Integer.parseInt(chapter); } catch (Exception e) { } try { maxchapter = Integer.parseInt(get(TYPE.CHAPTER, getPosition(TYPE.OSIS, osis))); } catch (Exception e) { return osiss; } if (bookname == null || "".equals(bookname)) { return osiss; } if (chapternum != 0) { osiss.put(bookname + " " + chapternum, osis + chapternum); } for (int i = 0 + chapternum * 10; i <= maxchapter && i < 10 * chapternum + 10; i++) { if (i != 0) { osiss.put(bookname + " " + i, osis + i); } } return osiss; }
From source file:org.jahia.ajax.gwt.helper.NodeHelper.java
GWTJahiaNode getGWTJahiaNode(JCRNodeWrapper node, List<String> fields, Locale uiLocale) { if (fields == null) { fields = Collections.emptyList(); }//w ww. j a va2 s.c om GWTJahiaNode n = new GWTJahiaNode(); // get uuid try { n.setUUID(node.getIdentifier()); } catch (RepositoryException e) { logger.debug("Unable to get uuid for node " + node.getName(), e); } populateNames(n, node, uiLocale); populateDescription(n, node); n.setPath(node.getPath()); n.setUrl(node.getUrl()); populateNodeTypes(n, node); JCRStoreProvider provider = node.getProvider(); if (provider.isDynamicallyMounted()) { n.setProviderKey(StringUtils.substringAfterLast(provider.getMountPoint(), "/")); } else { n.setProviderKey(provider.getKey()); } if (fields.contains(GWTJahiaNode.PERMISSIONS)) { populatePermissions(n, node); } if (fields.contains(GWTJahiaNode.LOCKS_INFO) && !provider.isSlowConnection()) { populateLocksInfo(n, node); } if (fields.contains(GWTJahiaNode.VISIBILITY_INFO)) { populateVisibilityInfo(n, node); } n.setVersioned(node.isVersioned()); n.setLanguageCode(node.getLanguage()); populateSiteInfo(n, node); if (node.isFile()) { n.setSize(node.getFileContent().getContentLength()); } n.setFile(node.isFile()); n.setIsShared(false); try { if (node.isNodeType("mix:shareable") && node.getSharedSet().getSize() > 1) { n.setIsShared(true); } } catch (RepositoryException e) { logger.error("Error when getting shares", e); } try { n.setReference(node.isNodeType("jmix:nodeReference")); } catch (RepositoryException e1) { logger.error("Error checking node type", e1); } if (fields.contains(GWTJahiaNode.CHILDREN_INFO)) { populateChildrenInfo(n, node); } if (fields.contains(GWTJahiaNode.TAGS)) { populateTags(n, node); } // icons if (fields.contains(GWTJahiaNode.ICON)) { populateIcon(n, node); } populateThumbnails(n, node); // count if (fields.contains(GWTJahiaNode.COUNT)) { populateCount(n, node); } populateStatusInfo(n, node); if (supportsWorkspaceManagement(node)) { if (fields.contains(GWTJahiaNode.PUBLICATION_INFO)) { populatePublicationInfo(n, node); } if (fields.contains(GWTJahiaNode.QUICK_PUBLICATION_INFO)) { populateQuickPublicationInfo(n, node); } if (fields.contains(GWTJahiaNode.PUBLICATION_INFOS)) { populatePublicationInfos(n, node); } n.set("supportsPublication", supportsPublication(node)); } if (fields.contains(GWTJahiaNode.WORKFLOW_INFO) || fields.contains(GWTJahiaNode.PUBLICATION_INFO)) { populateWorkflowInfo(n, node, uiLocale); } if (fields.contains(GWTJahiaNode.WORKFLOW_INFOS)) { populateWorkflowInfos(n, node, uiLocale); } if (fields.contains(GWTJahiaNode.AVAILABLE_WORKKFLOWS)) { populateAvailableWorkflows(n, node); } if (fields.contains(GWTJahiaNode.PRIMARY_TYPE_LABEL)) { populatePrimaryTypeLabel(n, node); } JCRStoreProvider p = JCRSessionFactory.getInstance().getMountPoints().get(n.getPath()); if (p != null && p.isDynamicallyMounted()) { n.set("j:isDynamicMountPoint", Boolean.TRUE); } if (n.isFile() && (n.isNodeType("jmix:image") || n.isNodeType("jmix:size"))) { // handle width and height try { if (node.hasProperty("j:height")) { n.set("j:height", node.getProperty("j:height").getString()); } } catch (RepositoryException e) { logger.error("Cannot get property j:height on node {}", node.getPath()); } try { if (node.hasProperty("j:width")) { n.set("j:width", node.getProperty("j:width").getString()); } } catch (RepositoryException e) { logger.error("Cannot get property j:width on node {}", node.getPath()); } } if (fields.contains("j:view") && n.isNodeType("jmix:renderable")) { try { if (node.hasProperty("j:view")) { n.set("j:view", node.getProperty("j:view").getString()); } } catch (RepositoryException e) { logger.error("Cannot get property j:view on node {}", node.getPath()); } } if (fields.contains(GWTJahiaNode.SITE_LANGUAGES)) { populateSiteLanguages(n, node); } if ((node instanceof JCRSiteNode) && fields.contains("j:resolvedDependencies")) { populateDependencies(n, node); } if (fields.contains(GWTJahiaNode.SUBNODES_CONSTRAINTS_INFO)) { populateSubnodesConstraintsInfo(n, node); } if (fields.contains(GWTJahiaNode.DEFAULT_LANGUAGE)) { populateDefaultLanguage(n, node); } if ((node instanceof JCRSiteNode) && fields.contains(GWTJahiaNode.HOMEPAGE_PATH)) { populateHomePage(n, node); } Boolean isModuleNode = null; final JahiaTemplateManagerService templateManagerService = ServicesRegistry.getInstance() .getJahiaTemplateManagerService(); try { if (fields.contains("j:versionInfo")) { isModuleNode = node.isNodeType("jnt:module"); if (isModuleNode) { populateVersionInfoForModule(n, node); } } } catch (RepositoryException e) { logger.error("Cannot get property module version"); } // properties for (String field : fields) { if (!GWTJahiaNode.RESERVED_FIELDS.contains(field)) { try { if (field.startsWith("fields-")) { String type = field.substring("fields-".length()); PropertyIterator pi = node.getProperties(); while (pi.hasNext()) { JCRPropertyWrapper property = (JCRPropertyWrapper) pi.next(); if (((ExtendedPropertyDefinition) property.getDefinition()).getItemType() .equals(type)) { setPropertyValue(n, property, node.getSession()); } } } else if (node.hasProperty(field)) { final JCRPropertyWrapper property = node.getProperty(field); setPropertyValue(n, property, node.getSession()); } else if (isModuleNode != null ? isModuleNode.booleanValue() : (isModuleNode = node.isNodeType("jnt:module"))) { JahiaTemplatesPackage templatePackageByFileName = templateManagerService .getTemplatePackageById(node.getName()); if (templatePackageByFileName != null) { JCRNodeWrapper versionNode = node .getNode(templatePackageByFileName.getVersion().toString()); if (versionNode.hasProperty(field)) { final JCRPropertyWrapper property = versionNode.getProperty(field); setPropertyValue(n, property, node.getSession()); } } } } catch (RepositoryException e) { logger.error("Cannot get property {} on node {}", field, node.getPath()); } } } // versions if (fields.contains(GWTJahiaNode.VERSIONS) && node.isVersioned()) { populateVersions(n, node); } // resource bundle if (fields.contains(GWTJahiaNode.RESOURCE_BUNDLE)) { GWTResourceBundle b = GWTResourceBundleUtils.load(node, uiLocale); if (b != null) { n.set(GWTJahiaNode.RESOURCE_BUNDLE, b); } } populateReference(n, node, fields, uiLocale); populateOrdering(n, node); populateChildConstraints(n, node); populateWCAG(n, node); populateInvalidLanguages(n, node); List<String> installedModules = (List<String>) n.get("j:installedModules"); if (installedModules != null) { List<JahiaTemplatesPackage> s = new ArrayList<>(); LinkedHashMap<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> deps = new LinkedHashMap<>(); for (String packId : installedModules) { JahiaTemplatesPackage pack = templateManagerService.getTemplatePackageById(packId); if (pack != null) { deps.put(pack, new ArrayList<JahiaTemplatesPackage>()); } } installedModules.clear(); for (Map.Entry<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> entry : deps.entrySet()) { List<JahiaTemplatesPackage> allDeps = entry.getKey().getDependencies(); for (JahiaTemplatesPackage dep : allDeps) { if (deps.keySet().contains(dep)) { entry.getValue().add(dep); } } if (entry.getValue().isEmpty()) { s.add(entry.getKey()); } } while (!s.isEmpty()) { JahiaTemplatesPackage pack = s.remove(0); installedModules.add(pack.getId()); for (Map.Entry<JahiaTemplatesPackage, List<JahiaTemplatesPackage>> entry : deps.entrySet()) { if (entry.getValue().contains(pack)) { entry.getValue().remove(pack); if (entry.getValue().isEmpty()) { s.add(entry.getKey()); } } } } } return n; }
From source file:lob.VisualisationGUI.java
public void updatePriceTable(LinkedHashMap<Float, Long> askTree, LinkedHashMap<Float, Long> bidTree) { //Clear old entries clearTable(jTable2);/*from w w w . j a v a2 s . c o m*/ //Get the number of points on each side int numberAskPoints = askTree.size(); int numberBidPoints = bidTree.size(); int currentTableRow = 7; //Fill ask entries for (Map.Entry<Float, Long> entry : askTree.entrySet()) { float key = entry.getKey(); long value = entry.getValue(); jTable2.getModel().setValueAt(key, currentTableRow, 2); jTable2.getModel().setValueAt(value, currentTableRow, 1); currentTableRow--; if (currentTableRow < 1) break; } //Fill bid entries currentTableRow = 8 + numberBidPoints; for (Map.Entry<Float, Long> entry : bidTree.entrySet()) { float key = entry.getKey(); long value = entry.getValue(); jTable2.getModel().setValueAt(key, currentTableRow, 0); jTable2.getModel().setValueAt(value, currentTableRow, 1); currentTableRow--; if (currentTableRow < 9) break; } }
From source file:org.karsha.controler.UploadDocumentServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SecurityManager sm = System.getSecurityManager(); HttpSession session = request.getSession(); String userPath = request.getServletPath(); String url = ""; List items = null;/*from www .j a v a2 s.c o m*/ if (userPath.equals("/uploaddocuments")) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5000000); // FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // items = upload. items = upload.parseRequest(request); } catch (Exception ex) { Logger.getLogger(UploadDocumentServlet.class.getName()).log(Level.SEVERE, null, ex); } HashMap requestParameters = new HashMap(); try { Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { requestParameters.put(item.getFieldName(), item.getString()); } else { PDFBookmark pdfBookmark = new PDFBookmark(); byte[] fileContent = item.get(); LinkedHashMap<String, String> docSectionMap = pdfBookmark .splitPDFByBookmarks(fileContent); if (!docSectionMap.isEmpty()) { Document newDocument = new Document(); newDocument.setDocumentName(requestParameters.get("docName").toString()); newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString())); String a = requestParameters.get("collection_type_new").toString(); newDocument.setCollectionId(Integer.parseInt(a)); // newDocument.setDocumentContent(fileContent); request.setAttribute("requestParameters", requestParameters); if (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) { url = "/WEB-INF/view/uploaddoc.jsp?error=File name already exists, please enter another file name"; } else { //DocumentDB.insert(newDocument); DocumentDB.insertDocMetaData(newDocument); int docId = DocumentDB .getDocumentDataByDocName(requestParameters.get("docName").toString()) .getDocId(); DocSection docSection = new DocSection(); for (Map.Entry entry : docSectionMap.entrySet()) { docSection.setParentDocId(docId); docSection.setSectionName((String) entry.getKey()); byte[] byte1 = ((String) entry.getValue()).getBytes(); docSection.setSectionContent(byte1); docSection.setUserId( Integer.parseInt(session.getAttribute("userId").toString())); //To-Do set this correctly //docSection.setSectionCatog(Integer.parseInt(session.getAttribute("sectioncat").toString())); docSection.setSectionCatog(4); DocSectionDB.insert(docSection); } url = "/WEB-INF/view/uploaddoc.jsp?succuss=File Uploaded Successfully"; } } /* * check wheter text can be extracted */ /* * if(DocumentValidator.isDocValidated(fileContent)){ * * * Document newDocument = new Document(); * newDocument.setDocumentName(requestParameters.get("docName").toString()); * newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString())); * String a = * requestParameters.get("collection_type_new").toString(); * newDocument.setCollectionId(Integer.parseInt(a)); * newDocument.setDocumentContent(fileContent); * * request.setAttribute("requestParameters", * requestParameters); * * if * (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) * { url = "/WEB-INF/view/uploaddoc.jsp?error=File * name already exists, please enter another file * name"; } else { //DocumentDB.insert(newDocument); * DocumentDB.insertDocMetaData(newDocument); url = * "/WEB-INF/view/uploaddoc.jsp?succuss=File * Uploaded Successfully"; } * * * } * */ else { url = "/WEB-INF/view/uploaddoc.jsp?error=Text can't be extracted from file, Please try onother"; } } } } // catch (FileUploadException e) { // e.printStackTrace(); // // // } // catch (Exception e) { e.printStackTrace(); } } request.getRequestDispatcher(url).forward(request, response); } }
From source file:org.apache.ode.daohib.bpel.ql.HibernateInstancesQueryCompiler.java
protected OrderByEvaluator<Collection<Order>, Object> compileOrderBy(OrderBy orderBy) { final LinkedHashMap<String, Boolean> orders = new LinkedHashMap<String, Boolean>(); for (OrderByElement idOrder : orderBy.getOrders()) { if (!(idOrder.getIdentifier() instanceof Field)) { throw new IllegalArgumentException("Only field identifier supported by order by operator."); }// w w w .j a va 2 s . c o m String idName = idOrder.getIdentifier().getName(); if (INSTANCE_STATUS_FIELD.equals(idName)) { if (orderBy.getOrders().size() > 1) { //TODO throw appropriate exception throw new RuntimeException("Status field should be used alone in <order by> construction."); } orderByStatus = true; orderByStatusDesc = idOrder.getType() == OrderByType.DESC; return null; } String dbField = getDBField(idName); orders.put(dbField, idOrder.getType() == null || idOrder.getType() == OrderByType.ASC); } return new OrderByEvaluator<Collection<Order>, Object>() { public Collection<Order> evaluate(Object paramValue) { Collection<Order> hibernateOrders = new ArrayList<Order>(orders.size()); for (Map.Entry<String, Boolean> order : orders.entrySet()) { hibernateOrders.add(order.getValue() ? Order.asc(order.getKey()) : Order.desc(order.getKey())); } return hibernateOrders; } }; }
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();/* w ww . ja va 2 s . co m*/ } 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.jahia.services.render.filter.StaticAssetsFilter.java
private String aggregate(Map<String, Resource> pathsToAggregate, String type, long maxLastModified) throws IOException { String aggregatedKey = generateAggregateName(pathsToAggregate.keySet()); String minifiedAggregatedFileName = aggregatedKey + ".min." + type; String minifiedAggregatedRealPath = getFileSystemPath(minifiedAggregatedFileName); File minifiedAggregatedFile = new File(minifiedAggregatedRealPath); String minifiedAggregatedPath = GENERATED_RESOURCES_URL_PATH + minifiedAggregatedFileName; if (addLastModifiedDate) { minifiedAggregatedPath += "?" + maxLastModified; }/*from w w w. ja v a 2 s. c om*/ if (!minifiedAggregatedFile.exists()) { generatedResourcesFolder.mkdirs(); // aggregate minified resources LinkedHashMap<String, String> minifiedFileNames = new LinkedHashMap<String, String>(); for (Map.Entry<String, Resource> entry : pathsToAggregate.entrySet()) { String path = entry.getKey(); Resource resource = entry.getValue(); String minifiedFileName = Patterns.SLASH.matcher(path).replaceAll("_") + ".min." + type; File minifiedFile = new File(getFileSystemPath(minifiedFileName)); if (!minifiedFile.exists()) { minify(path, resource, type, minifiedFile); } minifiedFileNames.put(path, minifiedFileName); } try { File tmpMinifiedAggregatedFile = new File(minifiedAggregatedFile.getParentFile(), minifiedAggregatedFile.getName() + "." + System.nanoTime()); OutputStream outMerged = new BufferedOutputStream(new FileOutputStream(tmpMinifiedAggregatedFile)); InputStream is = null; try { for (Map.Entry<String, String> entry : minifiedFileNames.entrySet()) { if (type.equals("js")) { outMerged.write("//".getBytes(ASSET_ENCODING)); outMerged.write(entry.getValue().getBytes(ASSET_ENCODING)); outMerged.write("\n".getBytes(ASSET_ENCODING)); } is = new FileInputStream(getFileSystemPath(entry.getValue())); IOUtils.copy(is, outMerged); if (type.equals("js")) { outMerged.write(";\n".getBytes(ASSET_ENCODING)); } IOUtils.closeQuietly(is); } } finally { IOUtils.closeQuietly(outMerged); IOUtils.closeQuietly(is); atomicMove(tmpMinifiedAggregatedFile, minifiedAggregatedFile); } } catch (IOException e) { logger.error(e.getMessage(), e); } } return minifiedAggregatedPath; }
From source file:com.espertech.esper.epl.core.SelectExprProcessorHelper.java
private TypeAndFunctionPair handleInsertIntoTypableExpression(ExpressionReturnType insertIntoTarget, ExprEvaluator exprEvaluator, EngineImportService engineImportService) throws ExprValidationException { if (!(exprEvaluator instanceof ExprEvaluatorTypableReturn) || insertIntoTarget == null || (insertIntoTarget.getSingleEventEventType() == null && insertIntoTarget.getCollOfEventEventType() == null)) { return null; }// w w w .j ava2 s. c o m final EventType targetType = insertIntoTarget.getSingleEventEventType() != null ? insertIntoTarget.getSingleEventEventType() : insertIntoTarget.getCollOfEventEventType(); final ExprEvaluatorTypableReturn typable = (ExprEvaluatorTypableReturn) exprEvaluator; if (typable.isMultirow() == null) { // not typable after all return null; } LinkedHashMap<String, Object> eventTypeExpr = typable.getRowProperties(); if (eventTypeExpr == null) { return null; } Set<WriteablePropertyDescriptor> writables = eventAdapterService.getWriteableProperties(targetType, false); List<WriteablePropertyDescriptor> written = new ArrayList<WriteablePropertyDescriptor>(); List<Map.Entry<String, Object>> writtenOffered = new ArrayList<Map.Entry<String, Object>>(); // from Map<String, Object> determine properties and type widening that may be required for (Map.Entry<String, Object> offeredProperty : eventTypeExpr.entrySet()) { WriteablePropertyDescriptor writable = EventTypeUtility.findWritable(offeredProperty.getKey(), writables); if (writable == null) { throw new ExprValidationException("Failed to find property '" + offeredProperty.getKey() + "' among properties for target event type '" + targetType.getName() + "'"); } written.add(writable); writtenOffered.add(offeredProperty); } // determine widening and column type compatibility final TypeWidener[] wideners = new TypeWidener[written.size()]; for (int i = 0; i < written.size(); i++) { Class expected = written.get(i).getType(); Map.Entry<String, Object> provided = writtenOffered.get(i); if (provided.getValue() instanceof Class) { wideners[i] = TypeWidenerFactory.getCheckPropertyAssignType(provided.getKey(), (Class) provided.getValue(), expected, written.get(i).getPropertyName()); } } final boolean hasWideners = !CollectionUtil.isAllNullArray(wideners); // obtain factory WriteablePropertyDescriptor[] writtenArray = written .toArray(new WriteablePropertyDescriptor[written.size()]); EventBeanManufacturer manufacturer; try { manufacturer = eventAdapterService.getManufacturer(targetType, writtenArray, engineImportService, false); } catch (EventBeanManufactureException e) { throw new ExprValidationException("Failed to obtain eventbean factory: " + e.getMessage(), e); } // handle collection final EventBeanManufacturer factory = manufacturer; if (insertIntoTarget.getCollOfEventEventType() != null && typable.isMultirow()) { ExprEvaluator evaluatorFragment = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { Object[][] rows = typable.evaluateTypableMulti(eventsPerStream, isNewData, exprEvaluatorContext); if (rows == null) { return null; } if (rows.length == 0) { return new EventBean[0]; } if (hasWideners) { applyWideners(rows, wideners); } EventBean[] events = new EventBean[rows.length]; for (int i = 0; i < events.length; i++) { events[i] = factory.make(rows[i]); } return events; } public Class getType() { return JavaClassHelper.getArrayType(targetType.getUnderlyingType()); } }; return new TypeAndFunctionPair(new EventType[] { targetType }, evaluatorFragment); } else if (insertIntoTarget.getCollOfEventEventType() != null && !typable.isMultirow()) { ExprEvaluator evaluatorFragment = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { Object[] row = typable.evaluateTypableSingle(eventsPerStream, isNewData, exprEvaluatorContext); if (row == null) { return null; } if (hasWideners) { applyWideners(row, wideners); } return new EventBean[] { factory.make(row) }; } public Class getType() { return JavaClassHelper.getArrayType(targetType.getUnderlyingType()); } }; return new TypeAndFunctionPair(new EventType[] { targetType }, evaluatorFragment); } else if (insertIntoTarget.getSingleEventEventType() != null && !typable.isMultirow()) { ExprEvaluator evaluatorFragment = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { Object[] row = typable.evaluateTypableSingle(eventsPerStream, isNewData, exprEvaluatorContext); if (row == null) { return null; } if (hasWideners) { applyWideners(row, wideners); } return factory.make(row); } public Class getType() { return JavaClassHelper.getArrayType(targetType.getUnderlyingType()); } }; return new TypeAndFunctionPair(targetType, evaluatorFragment); } // we are discarding all but the first row ExprEvaluator evaluatorFragment = new ExprEvaluator() { public Object evaluate(EventBean[] eventsPerStream, boolean isNewData, ExprEvaluatorContext exprEvaluatorContext) { Object[][] rows = typable.evaluateTypableMulti(eventsPerStream, isNewData, exprEvaluatorContext); if (rows == null) { return null; } if (rows.length == 0) { return new EventBean[0]; } if (hasWideners) { applyWideners(rows[0], wideners); } return factory.make(rows[0]); } public Class getType() { return JavaClassHelper.getArrayType(targetType.getUnderlyingType()); } }; return new TypeAndFunctionPair(targetType, evaluatorFragment); }
From source file:org.kontalk.provider.UsersProvider.java
/** * Computes counts by the address book index labels and returns it as {@link Bundle} which * will be appended to a {@link Cursor} as extras. *//*from w w w . j a v a 2s. c o m*/ private Bundle getFastScrollingIndexExtras(Cursor cursor) { try { LinkedHashMap<String, Counter> groups = new LinkedHashMap<>(); int count = cursor.getCount(); for (int i = 0; i < count; i++) { cursor.moveToNext(); String source = cursor.getString(Contact.COLUMN_DISPLAY_NAME); // use phone number if we don't have a display name if (source == null) source = cursor.getString(Contact.COLUMN_NUMBER); String label = mLocaleUtils.getLabel(source); Counter counter = groups.get(label); if (counter == null) { counter = new Counter(1); groups.put(label, counter); } else { counter.inc(); } } int numLabels = groups.size(); String labels[] = new String[numLabels]; int counts[] = new int[numLabels]; int i = 0; for (Map.Entry<String, Counter> entry : groups.entrySet()) { labels[i] = entry.getKey(); counts[i] = entry.getValue().value; i++; } return FastScrollingIndexCache.buildExtraBundle(labels, counts); } finally { // reset the cursor cursor.move(-1); } }