List of usage examples for java.util Set size
int size();
From source file:caveworld.core.ConfigHelper.java
public static String[] getStringsFromItems(Collection<ItemStack> items) { Set<String> ret = Sets.newLinkedHashSet(); for (ItemStack itemstack : items) { if (itemstack != null && itemstack.getItem() != null) { String name = GameData.getItemRegistry().getNameForObject(itemstack.getItem()); int damage = itemstack.getItemDamage(); if (itemstack.isItemStackDamageable()) { ret.add(name);// w ww .ja va 2 s.com } else if (itemstack.getHasSubtypes() || damage > 0) { ret.add(name + ":" + damage); } else { ret.add(name); } } } return ret.toArray(new String[ret.size()]); }
From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java
/** * Standard test for XSD examples./* www . ja v a2 s . c o m*/ * * @param testName * the prototype of XSD file name / package name * @param extraXewOptions * to be passed to plugin * @param generateEpisode * generate episode file and check the list of classes included into it * @param classesToCheck * expected classes/files in target directory; these files content is checked if it is present in * resources directory; {@code ObjectFactory.java} is automatically included */ static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode, String... classesToCheck) throws Exception { String resourceXsd = testName + ".xsd"; String packageName = testName.replace('-', '_'); // Force plugin to reinitialize the logger: System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY); URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd); File targetDir = new File(GENERATED_SOURCES_PREFIX); targetDir.mkdirs(); PrintStream loggingPrintStream = new PrintStream( new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] ")); String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d", targetDir.getPath(), xsdUrl.getFile()); String episodeFile = new File(targetDir, "episode.xml").getPath(); // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6 if (generateEpisode) { opts = ArrayUtils.addAll(opts, "-episode", episodeFile); } assertTrue("XJC compilation failed. Checked console for more info.", Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0); if (generateEpisode) { // FIXME: Episode file actually contains only value objects Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile); if (Arrays.asList(classesToCheck).contains("package-info")) { classReferences.add(packageName + ".package-info"); } assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size()); for (String className : classesToCheck) { assertTrue(className + " class is missing in episode file;", classReferences.contains(packageName + "." + className)); } } targetDir = new File(targetDir, packageName); Collection<String> generatedJavaSources = new HashSet<String>(); // *.properties files are ignored: for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) { // This is effectively the path of targetFile relative to targetDir: generatedJavaSources .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/')); } // This class is added and checked by default: classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory"); assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length, generatedJavaSources.size()); for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className)); } // Check the contents for those files which exist in resources: for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className); if (sourceFile.exists()) { // To avoid CR/LF conflicts: assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""), FileUtils.readFileToString(new File(targetDir, className)).replace("\r", "")); } } JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources); URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml"); if (xmlTestFile != null) { StringWriter writer = new StringWriter(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Object bean = unmarshaller.unmarshal(xmlTestFile); marshaller.marshal(bean, writer); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreWhitespace(true); Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString()); assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true); } }
From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java
public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout, TimeUnit timeUnit) throws Throwable { QueryTask.Query selfLinkClause = new QueryTask.Query() .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("/photon/*") .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD); QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification(); querySpecification.query.addBooleanClause(selfLinkClause); QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true); NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer, queryTask);//w w w . j a v a2 s . c o m Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryDocumentLinks(queryResponse); if (documentLinks == null || documentLinks.size() <= 0) { return; } CountDownLatch latch = new CountDownLatch(1); OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() { @Override public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) { if (failures != null && !failures.isEmpty()) { for (Throwable e : failures.values()) { logger.error("deleteAllDocuments failed", e); } } latch.countDown(); } }; Collection<Operation> deletes = new LinkedList<>(); for (String documentLink : documentLinks) { Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}") .setReferer(UriUtils.buildUri(host, referrer)); deletes.add(deleteOperation); } OperationJoin join = OperationJoin.create(deletes); join.setCompletion(handler); join.sendWith(host); if (!latch.await(timeout, timeUnit)) { throw new TimeoutException(String .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit)); } }
From source file:io.seldon.importer.articles.FileItemAttributesImporter.java
public static Map<String, String> getAttributes(String url, String existingCategory) { ItemProcessResult itemProcessResult = new ItemProcessResult(); itemProcessResult.client_item_id = url; itemProcessResult.extraction_status = "EXTRACTION_FAILED"; logger.info("Trying to get attributes for " + url); Map<String, String> attributes = null; String title = ""; String category = ""; String subCategory = ""; String img_url = ""; String description = ""; String tags = ""; String leadtext = ""; String link = ""; String publishDate = ""; String domain = ""; try {//from w w w . j a va 2 s . com long now = System.currentTimeMillis(); long timeSinceLastRequest = now - lastUrlFetchTime; if (timeSinceLastRequest < minFetchGapMsecs) { long timeToSleep = minFetchGapMsecs - timeSinceLastRequest; logger.info( "Sleeping " + timeToSleep + "msecs as time since last fetch is " + timeSinceLastRequest); Thread.sleep(timeToSleep); } Document articleDoc = Jsoup.connect(url).userAgent("SeldonBot/1.0").timeout(httpGetTimeout).get(); lastUrlFetchTime = System.currentTimeMillis(); //get IMAGE URL if (StringUtils.isNotBlank(imageCssSelector)) { Element imageElement = articleDoc.select(imageCssSelector).first(); if (imageElement != null) { if (imageElement.attr("content") != null) { img_url = imageElement.attr("content"); } if (StringUtils.isBlank(img_url) && imageElement.attr("src") != null) { img_url = imageElement.attr("src"); } if (StringUtils.isBlank(img_url) && imageElement.attr("href") != null) { img_url = imageElement.attr("href"); } } } if (StringUtils.isBlank(img_url) && StringUtils.isNotBlank(defImageUrl)) { logger.info("Setting image to default: " + defImageUrl); img_url = defImageUrl; } img_url = StringUtils.strip(img_url); //get TITLE if (StringUtils.isNotBlank(titleCssSelector)) { Element titleElement = articleDoc.select(titleCssSelector).first(); if (titleElement != null && titleElement.attr("content") != null) { title = titleElement.attr("content"); } } //get Lead Text if (StringUtils.isNotBlank(leadTextCssSelector)) { Element leadElement = articleDoc.select(leadTextCssSelector).first(); if (leadElement != null && leadElement.attr("content") != null) { leadtext = leadElement.attr("content"); } } //get publish date if (StringUtils.isNotBlank(publishDateCssSelector)) { //2013-01-21T10:40:55Z Element pubElement = articleDoc.select(publishDateCssSelector).first(); if (pubElement != null && pubElement.attr("content") != null) { String pubtext = pubElement.attr("content"); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date result = null; try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date withUTC format " + pubtext); } //try a simpler format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date " + pubtext); } if (result != null) publishDate = dateFormatter.format(result); else logger.error("Failed to parse date " + pubtext); } } //get Link if (StringUtils.isNotBlank(linkCssSelector)) { Element linkElement = articleDoc.select(linkCssSelector).first(); if (linkElement != null && linkElement.attr("content") != null) { link = linkElement.attr("content"); } } //get CONTENT if (StringUtils.isNotBlank(textCssSelector)) { Element descriptionElement = articleDoc.select(textCssSelector).first(); if (descriptionElement != null) description = Jsoup.parse(descriptionElement.html()).text(); } //get TAGS Set<String> tagSet = AttributesImporterUtils.getTags(articleDoc, tagsCssSelector, title); if (tagSet.size() > 0) tags = CollectionTools.join(tagSet, ","); //get CATEGORY - client specific if (StringUtils.isNotBlank(categoryCssSelector)) { Element categoryElement = articleDoc.select(categoryCssSelector).first(); if (categoryElement != null && categoryElement.attr("content") != null) { category = categoryElement.attr("content"); if (StringUtils.isNotBlank(category)) category = category.toUpperCase(); } } else if (StringUtils.isNotBlank(categoryClassPrefix)) { String className = "io.seldon.importer.articles.category." + categoryClassPrefix + "CategoryExtractor"; Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(); CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance(); category = extractor.getCategory(url, articleDoc); } //get Sub CATEGORY - client specific if (StringUtils.isNotBlank(subCategoryCssSelector)) { Element subCategoryElement = articleDoc.select(subCategoryCssSelector).first(); if (subCategoryElement != null && subCategoryElement.attr("content") != null) { subCategory = subCategoryElement.attr("content"); if (StringUtils.isNotBlank(subCategory)) subCategory = category.toUpperCase(); } } else if (StringUtils.isNotBlank(subCategoryClassPrefix)) { String className = "io.seldon.importer.articles.category." + subCategoryClassPrefix + "SubCategoryExtractor"; Class<?> clazz = Class.forName(className); Constructor<?> ctor = clazz.getConstructor(); CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance(); subCategory = extractor.getCategory(url, articleDoc); } // Get domain if (domainIsNeeded) { domain = getDomain(url); } if (StringUtils.isNotBlank(title) && (imageNotNeeded || StringUtils.isNotBlank(img_url)) && (categoryNotNeeded || StringUtils.isNotBlank(category)) && (!domainIsNeeded || StringUtils.isNotBlank(domain))) { attributes = new HashMap<String, String>(); attributes.put(TITLE, title); if (StringUtils.isNotBlank(category)) attributes.put(CATEGORY, category); if (StringUtils.isNotBlank(subCategory)) attributes.put(SUBCATEGORY, subCategory); if (StringUtils.isNotBlank(link)) attributes.put(LINK, link); if (StringUtils.isNotBlank(leadtext)) attributes.put(LEAD_TEXT, leadtext); if (StringUtils.isNotBlank(img_url)) attributes.put(IMG_URL, img_url); if (StringUtils.isNotBlank(tags)) attributes.put(TAGS, tags); attributes.put(CONTENT_TYPE, VERIFIED_CONTENT_TYPE); if (StringUtils.isNotBlank(description)) attributes.put(DESCRIPTION, description); if (StringUtils.isNotBlank(publishDate)) attributes.put(PUBLISH_DATE, publishDate); if (StringUtils.isNotBlank(domain)) attributes.put(DOMAIN, domain); System.out.println("Item: " + url + "; Category: " + category); itemProcessResult.extraction_status = "EXTRACTION_SUCCEEDED"; } else { logger.warn("Failed to get title for article " + url); logger.warn("[title=" + title + ", img_url=" + img_url + ", category=" + category + ", domain=" + domain + "]"); } { // check for failures for the log result if (StringUtils.isBlank(title)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "title"; } if (!imageNotNeeded && StringUtils.isBlank(img_url)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "img_url"; } if (!categoryNotNeeded && StringUtils.isBlank(category)) { itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "category"; } } } catch (Exception e) { logger.warn("Article: " + url + ". Attributes import FAILED", e); itemProcessResult.error = e.toString(); } AttributesImporterUtils.logResult(logger, itemProcessResult); return attributes; }
From source file:org.wrml.util.AsciiArt.java
public static String express(final ApiNavigator apiNavigator) { if (apiNavigator == null) { return ""; }//from ww w . j av a2 s. co m final StringBuilder stringBuilder = new StringBuilder(); final Api api = apiNavigator.getApi(); final URI apiUri = api.getUri(); stringBuilder.append("API URI: ").append(apiUri); stringBuilder.append("\nAPI TITLE: ").append(api.getTitle()); stringBuilder.append("\nAPI DESCRIPTION: ").append(api.getDescription()); stringBuilder.append("\nAPI RESOURCES:\n"); final ApiNavigatorAsciiTree asciiTree = AsciiArt.createApiNavigatorAsciiTree(apiNavigator); stringBuilder.append(AsciiArt.expressAsciiTree(asciiTree)); final List<LinkTemplate> linkTemplates = api.getLinkTemplates(); stringBuilder.append("\nLINK TEMPLATE COUNT: ").append(linkTemplates.size()); if (linkTemplates.size() > 0) { stringBuilder.append("\nLINK TEMPLATES:\n\n"); final Context context = api.getContext(); final ApiLoader apiLoader = context.getApiLoader(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final List<String> linkTemplateStrings = new ArrayList<>(linkTemplates.size()); for (final LinkTemplate linkTemplate : linkTemplates) { final StringBuilder sb = new StringBuilder(); final UUID referrerId = linkTemplate.getReferrerId(); final Resource referrerResource = apiNavigator.getResource(referrerId); final String referrerResourceRelativePath = referrerResource.getPathText(); final URI linkRelationUri = linkTemplate.getLinkRelationUri(); final LinkRelation linkRelation = apiLoader.loadLinkRelation(linkRelationUri); final Method method = linkRelation.getMethod(); final String methodProtocolName = method.getProtocolGivenName(); final UUID endpointId = linkTemplate.getEndPointId(); final Resource endpointResource = apiNavigator.getResource(endpointId); final String endpointResourceRelativePath = endpointResource.getPathText(); final Set<URI> responseSchemaUris = endpointResource.getResponseSchemaUris(method); final int responseSchemaCount; final List<Schema> responseSchemas; if (responseSchemaUris != null) { responseSchemas = new ArrayList<>(responseSchemaUris.size()); for (final URI responseSchemaUri : responseSchemaUris) { final Schema schema = schemaLoader.load(responseSchemaUri); responseSchemas.add(schema); } responseSchemaCount = responseSchemas.size(); } else { responseSchemaCount = 0; responseSchemas = null; } final Set<URI> requestSchemaUris = endpointResource.getRequestSchemaUris(method); final int requestSchemaCount; final List<Schema> requestSchemas; if (requestSchemaUris != null) { requestSchemas = new ArrayList<>(requestSchemaUris.size()); for (final URI requestSchemaUri : requestSchemaUris) { final Schema schema = schemaLoader.load(requestSchemaUri); requestSchemas.add(schema); } requestSchemaCount = requestSchemaUris.size(); } else { requestSchemaCount = 0; requestSchemas = null; } sb.append(referrerResourceRelativePath).append(" --[").append(methodProtocolName).append("]") .append("--> ").append(endpointResourceRelativePath); sb.append(" : "); if (responseSchemaCount == 0) { sb.append("void "); } else { for (int i = 0; i < responseSchemaCount; i++) { final Schema schema = responseSchemas.get(i); final String returnType = schema.getUniqueName().getLocalName(); sb.append(returnType).append(" "); if (i < responseSchemaCount - 1) { sb.append("| "); } } } sb.append(linkRelation.getTitle()); if (requestSchemaCount == 0) { sb.append("("); } else { sb.append("( "); for (int i = 0; i < requestSchemaCount; i++) { final Schema schema = requestSchemas.get(i); final String paramType = schema.getUniqueName().getLocalName(); sb.append(paramType).append(" "); if (i < requestSchemaCount - 1) { sb.append("| "); } } } sb.append(");\n"); linkTemplateStrings.add(sb.toString()); } Collections.sort(linkTemplateStrings); for (final String linkTemplateString : linkTemplateStrings) { stringBuilder.append(linkTemplateString); } } return stringBuilder.toString(); }
From source file:controllers.TNodes.java
/*************************************************************************************************************************/ public static void getNodeList() { String id = params.get("node_type_id"); String flag = params.get("flag"); JsonArray arr = new JsonArray(); JsonObject obj = null;/* w w w . ja va 2 s. c o m*/ List<TNode> list; // ?? if (flag.equals("0")) { if (id.equals("1")) { obj = new JsonObject(); obj.addProperty("T_NODE_NAME", ""); obj.addProperty("T_NODE_IP", ""); obj.addProperty("T_NODE_OS", ""); obj.addProperty("delete", ""); arr.add(obj); } else { TNodeType nodeType = TNodeType.findById(Long.parseLong(id)); Set<TNode> tNodes = nodeType.tNodes; if (tNodes != null && tNodes.size() > 0) { for (TNode node : tNodes) { obj = new JsonObject(); obj.addProperty("T_NODE_NAME", node.T_NODE_NAME); obj.addProperty("T_NODE_IP", node.T_NODE_IP); obj.addProperty("T_NODE_OS", node.T_NODE_OS); obj.addProperty("delete", "<button class='btn btn-danger btn-xs' type='button' onclick='deleteNode(" + node.id + ")' >" + "</button>"); arr.add(obj); } } else { obj = new JsonObject(); obj.addProperty("T_NODE_NAME", " "); obj.addProperty("T_NODE_IP", " "); obj.addProperty("T_NODE_OS", " "); obj.addProperty("delete", " "); arr.add(obj); } } } // ? if (flag.equals("1")) { // Node list = TNode.findAll(); TNodeType nodeType = TNodeType.findById(Long.parseLong(id)); Set<TNode> tNodes = nodeType.tNodes;// Iterator<TNode> iterator = tNodes.iterator(); List<Long> selectIds = new ArrayList<>(); List<Long> unSelectIds = new ArrayList<>(); while (iterator.hasNext()) { selectIds.add(iterator.next().id); } for (TNode node : list) { if (!selectIds.contains(node.id)) { unSelectIds.add(node.id); } } for (Long unId : unSelectIds) { TNode node = TNode.findById(unId); obj = new JsonObject(); obj.addProperty("id", "<input type='checkbox' class='checkedID' name='nodeCheckbox' value='" + node.id + "'></input>"); obj.addProperty("T_NODE_NAME", node.T_NODE_NAME); obj.addProperty("T_NODE_IP", node.T_NODE_IP); obj.addProperty("T_NODE_OS", node.T_NODE_OS); arr.add(obj); } } renderJSON(new DataTableSource(request, arr)); }
From source file:net.rptools.maptool.util.AssetExtractor.java
public static void extract() throws Exception { new Thread() { @Override//from w w w. ja v a 2 s.c o m public void run() { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); File newDir = new File(file.getParentFile(), file.getName().substring(0, file.getName().lastIndexOf('.')) + "_images"); JLabel label = new JLabel("", JLabel.CENTER); JFrame frame = new JFrame(); frame.setTitle("Campaign Image Extractor"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(400, 75); frame.add(label); SwingUtil.centerOnScreen(frame); frame.setVisible(true); Reader r = null; OutputStream out = null; PackedFile pakfile = null; try { newDir.mkdirs(); label.setText("Loading campaign ..."); pakfile = new PackedFile(file); Set<String> files = pakfile.getPaths(); XStream xstream = new XStream(); int count = 0; for (String filename : files) { count++; if (filename.indexOf("assets") < 0) { continue; } r = pakfile.getFileAsReader(filename); Asset asset = (Asset) xstream.fromXML(r); IOUtils.closeQuietly(r); File newFile = new File(newDir, asset.getName() + ".jpg"); label.setText("Extracting image " + count + " of " + files.size() + ": " + newFile); if (newFile.exists()) { newFile.delete(); } newFile.createNewFile(); out = new FileOutputStream(newFile); FileUtil.copyWithClose(new ByteArrayInputStream(asset.getImage()), out); } label.setText("Done."); } catch (Exception ioe) { MapTool.showInformation("AssetExtractor failure", ioe); } finally { if (pakfile != null) pakfile.close(); IOUtils.closeQuietly(r); IOUtils.closeQuietly(out); } } }.start(); }
From source file:gov.nih.nci.nbia.StandaloneDMV3.java
public static void setDefaultSize(int size) { Set<Object> keySet = UIManager.getLookAndFeelDefaults().keySet(); Object[] keys = keySet.toArray(new Object[keySet.size()]); for (Object key : keys) { if (key != null && key.toString().toLowerCase().contains("font")) { Font font = UIManager.getDefaults().getFont(key); if (font != null) { font = font.deriveFont((float) size); UIManager.put(key, font); }//from w ww .j av a2 s . com } } }
From source file:act.installer.brenda.BrendaChebiOntology.java
/** * This function fetches and construct the set of main and direct applications for each ontology that has a role. * @param ontologyMap map {chebi id -> ChebiOntology object} * @param isSubtypeOfRelationships map {chebi id -> set of chebi id for its subtypes} * @param hasRoleRelationships map {chebi id -> set of chebi id for its roles} * @return a map from ChebiOntology objects to a ChebiApplicationSet object *///from w w w .j a v a 2 s .c o m public static Map<ChebiOntology, ChebiApplicationSet> getApplications(Map<String, ChebiOntology> ontologyMap, Map<String, Set<String>> isSubtypeOfRelationships, Map<String, Set<String>> hasRoleRelationships) { Map<String, Set<String>> applicationToMainApplicationsMap = getApplicationToMainApplicationsMap( isSubtypeOfRelationships, APPLICATION_CHEBI_ID); // Filter out the roles that are not applications Map<String, Set<String>> directApplicationMap = new HashMap<>(); hasRoleRelationships.forEach((key, value) -> directApplicationMap.put(key, value.stream().filter(ontology -> applicationToMainApplicationsMap.keySet().contains(ontology)) .collect(Collectors.toSet()))); // Compute the set of main applications for each ontology that has a role (aka is a chemical entity). Map<ChebiOntology, Set<ChebiOntology>> chemicalEntityToMainApplicationMap = new HashMap<>(); for (String chemicalEntity : directApplicationMap.keySet()) { Set<ChebiOntology> mainApplicationsSet = chemicalEntityToMainApplicationMap .get(ontologyMap.get(chemicalEntity)); if (mainApplicationsSet == null) { mainApplicationsSet = new HashSet<>(); chemicalEntityToMainApplicationMap.put(ontologyMap.get(chemicalEntity), mainApplicationsSet); } for (String parentApplication : directApplicationMap.get(chemicalEntity)) { Set<String> mainApplications = applicationToMainApplicationsMap.get(parentApplication); if (mainApplications != null) { mainApplicationsSet.addAll(mainApplications.stream().map(ontologyMap::get) .filter(Objects::nonNull).collect(Collectors.toSet())); } } } // Finally, construct a ChebiApplicationSet object containing direct and main applications for the molecules. Map<ChebiOntology, ChebiApplicationSet> chemicalEntityToApplicationsMap = new HashMap<>(); for (String chemicalEntity : directApplicationMap.keySet()) { Set<ChebiOntology> directApplications = directApplicationMap.get(chemicalEntity).stream() .map(ontologyMap::get).filter(Objects::nonNull).collect(Collectors.toSet()); Set<ChebiOntology> mainApplications = chemicalEntityToMainApplicationMap .get(ontologyMap.get(chemicalEntity)); if (directApplications.size() > 0 || mainApplications.size() > 0) { ChebiApplicationSet applications = new ChebiApplicationSet(directApplications, mainApplications); chemicalEntityToApplicationsMap.put(ontologyMap.get(chemicalEntity), applications); } } return chemicalEntityToApplicationsMap; }
From source file:ch.entwine.weblounge.contentrepository.index.SearchIndexRecencyPriorityTest.java
/** * Sets up the solr search index. Since solr sometimes has a hard time * shutting down cleanly, it's done only once for all the tests. * /* w w w . j a v a 2s.c o m*/ * @throws Exception */ @BeforeClass public static void setupClass() throws Exception { // Template template = EasyMock.createNiceMock(PageTemplate.class); EasyMock.expect(template.getIdentifier()).andReturn("templateid").anyTimes(); EasyMock.expect(template.getStage()).andReturn("non-existing").anyTimes(); EasyMock.replay(template); Set<Language> languages = new HashSet<Language>(); languages.add(LanguageUtils.getLanguage("en")); languages.add(LanguageUtils.getLanguage("de")); // Site site = EasyMock.createNiceMock(Site.class); EasyMock.expect(site.getIdentifier()).andReturn("test").anyTimes(); EasyMock.expect(site.getTemplate((String) EasyMock.anyObject())).andReturn(template).anyTimes(); EasyMock.expect(site.getDefaultTemplate()).andReturn(template).anyTimes(); EasyMock.expect(site.getLanguages()).andReturn(languages.toArray(new Language[languages.size()])) .anyTimes(); EasyMock.replay(site); // Resource serializer serializer = new ResourceSerializerServiceImpl(); serializer.addSerializer(new PageSerializer()); serializer.addSerializer(new FileResourceSerializer()); serializer.addSerializer(new ImageResourceSerializer()); serializer.addSerializer(new MovieResourceSerializer()); String rootPath = PathUtils.concat(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); idxRoot = new File(rootPath); System.setProperty("weblounge.home", rootPath); ElasticSearchUtils.createIndexConfigurationAt(idxRoot); idx = new SearchIndex(site, serializer, isReadOnly); }