List of usage examples for java.util HashSet contains
public boolean contains(Object o)
From source file:com.tamingtext.tagrecommender.TestStackOverflowTagger.java
public void execute() { PrintStream out = null;//from w w w . j a va 2 s .c om try { OpenObjectIntHashMap<String> tagCounts = new OpenObjectIntHashMap<String>(); OpenObjectIntHashMap<String> tagCorrect = new OpenObjectIntHashMap<String>(); loadTags(tagCounts); StackOverflowStream stream = new StackOverflowStream(); stream.open(inputFile.getAbsolutePath()); out = new PrintStream(new FileOutputStream(outputFile)); int correctTagCount = 0; int postCount = 0; HashSet<String> postTags = new HashSet<String>(); float postPctCorrect; int totalSingleCorrect = 0; int totalHalfCorrect = 0; for (StackOverflowPost post : stream) { correctTagCount = 0; postCount++; postTags.clear(); postTags.addAll(post.getTags()); for (String tag : post.getTags()) { if (tagCounts.containsKey(tag)) { tagCounts.adjustOrPutValue(tag, 1, 1); } } ScoreTag[] tags = client.getTags(post.getTitle() + "\n" + post.getBody(), maxTags); for (ScoreTag tag : tags) { if (postTags.contains(tag.getTag())) { correctTagCount += 1; tagCorrect.adjustOrPutValue(tag.getTag(), 1, 1); } } if (correctTagCount > 0) { totalSingleCorrect += 1; } postPctCorrect = correctTagCount / (float) postTags.size(); if (postPctCorrect >= 0.50f) { totalHalfCorrect += 1; } if ((postCount % 100) == 0) { dumpStats(System.err, postCount, totalSingleCorrect, totalHalfCorrect); } } dumpStats(System.err, postCount, totalSingleCorrect, totalHalfCorrect); dumpStats(out, postCount, totalSingleCorrect, totalHalfCorrect); dumpTags(out, tagCounts, tagCorrect); } catch (Exception ex) { throw (RuntimeException) new RuntimeException().initCause(ex); } finally { if (out != null) { out.close(); } } }
From source file:com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookieResult.java
@Override public void createResultCookie(Cookie cookie, HttpServletRequest request, HttpServletResponse response) throws ServletException { UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); ConfigManager mgr = holder.getConfig(); HashSet<String> mechs = new HashSet<String>(); for (String mechName : mgr.getAuthMechs().keySet()) { MechanismType mech = mgr.getAuthMechs().get(mechName); if (mech.getClassName() .equalsIgnoreCase("com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie")) { mechs.add(mechName);/*from w ww . j a va2 s .c o m*/ } } AuthController authCtl = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL); String chainName = authCtl.getAuthInfo().getAuthChain(); AuthChainType chain = mgr.getAuthChains().get(chainName); int millisToLive = 0; String keyAlias = ""; boolean useSSLSession = false; for (AuthMechType amt : chain.getAuthMech()) { if (mechs.contains(amt.getName())) { for (ParamType pt : amt.getParams().getParam()) { if (pt.getName().equalsIgnoreCase("millisToLive")) { millisToLive = Integer.parseInt(pt.getValue()); } if (pt.getName().equalsIgnoreCase("useSSLSessionID") && pt.getValue().equalsIgnoreCase("true")) { useSSLSession = true; } else if (pt.getName().equalsIgnoreCase("keyAlias")) { keyAlias = pt.getValue(); } } } } DateTime now = new DateTime(); DateTime expires = now.plusMillis(millisToLive); com.tremolosecurity.lastmile.LastMile lastmile = null; try { lastmile = new com.tremolosecurity.lastmile.LastMile("/", now, expires, 0, "NONE"); } catch (URISyntaxException e) { //not possible } lastmile.getAttributes().add(new Attribute("DN", authCtl.getAuthInfo().getUserDN())); lastmile.getAttributes().add(new Attribute("CLIENT_IP", request.getRemoteAddr())); if (useSSLSession) { Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id"); if (sessionID instanceof byte[]) { sessionID = new String(Base64.encodeBase64((byte[]) sessionID)); } lastmile.getAttributes().add(new Attribute("SSL_SESSION_ID", (String) sessionID)); } try { cookie.setValue(new StringBuilder().append('"') .append(lastmile.generateLastMileToken(mgr.getSecretKey(keyAlias))).append('"').toString()); } catch (Exception e) { throw new ServletException("Could not encrypt persistent cookie", e); } cookie.setMaxAge(millisToLive / 1000); }
From source file:com.nike.cerberus.service.CloudFormationService.java
/** * Blocking call that waits for a stack change to complete. Times out if waiting more than 30 minutes. * * @param endStatuses Status to end on/*from w w w . j a va 2 s. c o m*/ * @return The final status */ public StackStatus waitForStatus(final String stackId, final HashSet<StackStatus> endStatuses) { DateTime now = DateTime.now(DateTimeZone.UTC).minusSeconds(10); DateTime timeoutDateTime = now.plusMinutes(90); Set<String> recordedStackEvents = Sets.newHashSet(); boolean isRunning = true; StackStatus stackStatus = null; while (isRunning) { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { logger.warn("Thread sleep interrupted. Continuing...", e); } stackStatus = getStackStatus(stackId); if (endStatuses.contains(stackStatus) || stackStatus == null) { isRunning = false; } if (stackStatus != null) { List<StackEvent> stackEvents = getStackEvents(stackId); stackEvents.sort((o1, o2) -> o1.getTimestamp().compareTo(o2.getTimestamp())); for (StackEvent stackEvent : stackEvents) { DateTime eventTime = new DateTime(stackEvent.getTimestamp()); if (!recordedStackEvents.contains(stackEvent.getEventId()) && now.isBefore(eventTime)) { logger.info(String.format("TS: %s, Status: %s, Type: %s, Reason: %s", Chalk.on(stackEvent.getTimestamp().toString()).yellow(), getStatusColor(stackEvent.getResourceStatus()), Chalk.on(stackEvent.getResourceType()).yellow(), Chalk.on(stackEvent.getResourceStatusReason()).yellow())); recordedStackEvents.add(stackEvent.getEventId()); } } } if (timeoutDateTime.isBeforeNow()) { logger.error("Timed out waiting for CloudFormation completion status."); isRunning = false; } } return stackStatus; }
From source file:com.jaspersoft.studio.handlers.ResourcePage.java
/** * Return the File to all the resources referenced by this template. This can be an expensive operation, since the * jrxml representing the template may be loaded in order locate all the referenced resources. In the returned list * are avoided duplicated files to the same resource * //from ww w .j ava 2s .c o m */ public List<File> getResourceNames() { List<File> resourceNames = new ArrayList<File>(); //This set is used to avoid duplicated resources HashSet<String> alredyAddedElements = new HashSet<String>(); List<JRDesignElement> list = ModelUtils.getAllGElements(bundle.getJasperDesign()); for (JRDesignElement el : list) { if (el instanceof JRImage) { JRImage im = (JRImage) el; String res = evalResourceName(im.getExpression()); File resFile = findFile(reportFile, res); if (resFile != null && !alredyAddedElements.contains(resFile.getAbsolutePath())) { resourceNames.add(resFile); alredyAddedElements.add(resFile.getAbsolutePath()); } } if (el instanceof JRSubreport) { JRSubreport sr = (JRSubreport) el; String res = evalResourceName(sr.getExpression()); if (res != null && res.endsWith(".jasper")) { //$NON-NLS-1$ res = res.substring(0, res.length() - ".jasper".length()) + ".jrxml"; //$NON-NLS-1$ //$NON-NLS-2$ File resFile = findFile(reportFile, res); if (!alredyAddedElements.contains(resFile.getAbsolutePath())) { resourceNames.add(resFile); alredyAddedElements.add(resFile.getAbsolutePath()); } } } } List<JRReportTemplate> templates = bundle.getJasperDesign().getTemplatesList(); for (JRReportTemplate t : templates) { String res = evalResourceName(t.getSourceExpression()); File resFile = findFile(reportFile, res); if (resFile != null && !alredyAddedElements.contains(resFile.getAbsolutePath())) { resourceNames.add(resFile); alredyAddedElements.add(resFile.getAbsolutePath()); } } return resourceNames; }
From source file:net.dempsy.container.TestContainer.java
@Test public void testInvokeOutput() throws Exception { outputMessages = Collections.newSetFromMap(new ConcurrentHashMap<>()); cache = new ConcurrentHashMap<>(); final TestAdaptor adaptor = context.getBean(TestAdaptor.class); assertNotNull(adaptor.dispatcher);// ww w . j a va2 s . com adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("foo")); adaptor.dispatcher.dispatchAnnotated(new ContainerTestMessage("bar")); assertTrue(poll(container, c -> c.getProcessorCount() > 1)); Thread.sleep(100); assertEquals("number of MP instances", 2, container.getProcessorCount()); try (NodeManager nman = addOutputCatchStage();) { final TestProcessor mp = cache.get("foo"); assertTrue(poll(mp, m -> mp.invocationCount > 0)); Thread.sleep(100); assertEquals("invocation count, 1st message", 1, mp.invocationCount); // because the sessionFactory is shared and the appname is the same, we should be in the same app container.outputPass(); assertTrue(poll(outputMessages, o -> o.size() > 1)); Thread.sleep(100); assertEquals(2, outputMessages.size()); // no new mps created in the first one assertEquals("did not create MP", 2, container.getProcessorCount()); // but the invocation count should have increased since the output cycles feeds messages back to this cluster assertTrue(poll(mp, m -> mp.invocationCount > 1)); Thread.sleep(100); assertEquals("invocation count, 1st message", 2, mp.invocationCount); // // order of messages is not guaranteed, so we need to aggregate keys final HashSet<String> messageKeys = new HashSet<String>(); final Iterator<OutputMessage> iter = outputMessages.iterator(); messageKeys.add(iter.next().getKey()); messageKeys.add(iter.next().getKey()); assertTrue("first MP sent output", messageKeys.contains("foo")); assertTrue("second MP sent output", messageKeys.contains("bar")); } }
From source file:com.jaspersoft.studio.custom.adapter.wizard.NewDataAdapterWizard.java
/** * Given a list package names generate an equal number of import strings to import everything inside that packages * //from ww w . ja v a 2 s . co m * @param packagesName * a not null list of package * @return the code to import the content of the packages */ private String getImportStrings(List<String> packagesName) { HashSet<String> generatedPackages = new HashSet<String>(); String result = ""; for (String packageName : packagesName) { String newPackage = "import " + packageName; if (packageName.endsWith(".*")) newPackage += ";"; else newPackage += ".*;"; if (!generatedPackages.contains(newPackage)) { result += newPackage + "\n"; generatedPackages.add(newPackage); } } return result; }
From source file:edu.cornell.mannlib.semservices.service.impl.AgrovocService.java
@Override public List<Concept> getConcepts(String term) throws Exception { List<Concept> conceptList = new ArrayList<Concept>(); //For the RDF webservices mechanism, utilize the following /*/*from ww w . ja v a2s . c om*/ String result = getTermExpansion(this.ontologyName, term, this.searchMode, this.format, this.lang); // return empty conceptList if conceptUri is empty if (StringUtils.isEmpty(result)) { return conceptList; } // Get the list of the concept URIs in the RDF List<String> conceptUris = getConceptURIsListFromRDF(result); */ //For the SKOSMos search mechanism, utilize this instead String result = getSKOSMosSearchResults(term, this.lang); List<String> conceptUris = getConceptURIsListFromSkosMosResult(result); if (conceptUris.size() == 0) return conceptList; int conceptCounter = 0; HashSet<String> encounteredURI = new HashSet<String>(); // Loop through each of these URIs and load using the SKOSManager for (String conceptUri : conceptUris) { conceptCounter++; if (StringUtils.isEmpty(conceptUri)) { // If the conceptURI is empty, keep going continue; } if (encounteredURI.contains(conceptUri)) { //If we have already encountered this concept URI, do not redisplay or reprocess continue; } encounteredURI.add(conceptUri); // Test and see if the URI is valid URI uri = null; try { uri = new URI(conceptUri); } catch (URISyntaxException e) { logger.error("Error occurred with creating the URI ", e); continue; } // Returns concept information in the format specified, which is // currently XML // Utilizing Agrovoc's getConceptInfo returns alternate and // preferred labels but // none of the exact match or close match descriptions String bestMatch = "false"; //Assume the first result is considered the 'best match' //Although that is not something we are actually retrieving from the service itself explicitly if (conceptCounter == 1) { bestMatch = "true"; } Concept c = this.createConcept(bestMatch, conceptUri); if (c != null) { // Get definition from dbpedia references stored in the close // Match list List<String> closeMatches = c.getCloseMatchURIList(); for (String closeMatch : closeMatches) { if (closeMatch.startsWith("http://dbpedia.org")) { try { String description = getDbpediaDescription(closeMatch); // System.out.println("description: "+ description); c.setDefinition(description); } catch (Exception ex) { logger.error("An error occurred in the process of retrieving dbpedia description", ex); } } } conceptList.add(c); } } return conceptList; }
From source file:biomine.bmvis2.Vis.java
public void zoomToNodes(final String[] nameStrings) { Logging.info("js", "zoomToNodes called with params: " + nameStrings); SwingUtilities.invokeLater(new Runnable() { public void run() { GraphTab tab = (GraphTab) tabs.getSelectedComponent(); Collection<VisualNode> nodes = tab.getVisualGraph().getNodes(); HashSet<String> names = new HashSet<String>(Arrays.asList(nameStrings)); tab.getVisualGraph().clearSelected(); ArrayList<VisualNode> zoomNodes = new ArrayList<VisualNode>(); for (VisualNode vn : nodes) { String id = vn.getBMNode().getType() + "_" + vn.getBMNode().getId(); if (names.contains(id)) zoomNodes.add(vn);//from w ww .ja v a2s . c o m } tab.getVisualGraph().selectionChanged(); tab.getVisualizer().getGraphArea().zoomTo(zoomNodes); } }); }
From source file:com.otway.picasasync.syncutil.SyncManager.java
private List<File> getNewSubFolders(List<AlbumEntry> albums, File rootFolder) throws ServiceException { List<File> result = new ArrayList<File>(); log.info("Looking for new local sub folders in " + rootFolder + "..."); final HashSet<String> albumNameLookup = new HashSet<String>(); for (AlbumEntry remoteAlbum : albums) albumNameLookup.add(remoteAlbum.getTitle().getPlainText()); File[] newFolders = rootFolder.listFiles(new FilenameFilter() { public boolean accept(File current, String name) { File file = new File(current, name); if (file.isDirectory() && !file.isHidden()) { if (!albumNameLookup.contains(file.getName()) && !file.getName().equals(PicasawebClient.AUTO_BACKUP_FOLDER)) { return true; }// w ww . j a va 2 s. c om } return false; } }); if (newFolders != null) { result = Arrays.asList(newFolders); TimeUtils.sortFoldersNewestFirst(result); } return result; }
From source file:dpfmanager.conformancechecker.tiff.implementation_checker.TiffImplementationChecker.java
TiffIfd createIfdNode(TagValue tv, String nodeName) { TiffIfd ifd = new TiffIfd(); ifd.setThumbnail(-1);/*from w w w. java2 s .c o m*/ List<TiffTag> tags = new ArrayList<TiffTag>(); int prevTagId = -1; boolean correctTagOrdering = true; boolean duplicatedTags = false; HashSet tagIds = new HashSet<>(); IFD exif = (IFD) tv.getValue().get(0); for (TagValue tvv : exif.getTags().getTags()) { if (tvv.getId() <= prevTagId) { correctTagOrdering = false; } if (tagIds.contains(tvv.getId())) { duplicatedTags = true; } else { tagIds.add(tvv.getId()); } prevTagId = tvv.getId(); tags.add(CreateTiffTag(tvv, 0)); } TiffTags tiffTags = new TiffTags(); tiffTags.setTagsCount(tags.size()); tiffTags.setTags(tags); ifd.setTags(tiffTags); ifd.setTagOrdering(correctTagOrdering ? 1 : 0); ifd.setDuplicateTags(duplicatedTags ? 1 : 0); ifd.setClassElement(nodeName); return ifd; }