List of usage examples for java.util Set clear
void clear();
From source file:org.aksw.simba.cetus.yago.YagoBasedTypeSearcher.java
protected void searchDolceSuperClasses(Set<Resource> types) { Queue<Resource> queue = new LinkedList<Resource>(types); Resource classResource, superClass; RDFNode node;/*from w w w.j av a2s. c o m*/ NodeIterator nodeIterator; Set<Resource> yagoSuperClasses = new HashSet<Resource>(); Set<Resource> dolceSuperClasses = new HashSet<Resource>(); boolean dolceClassFound = false; while (!queue.isEmpty()) { classResource = queue.poll(); // If this resource is a DOLCE resource if (dolceClassModel.containsResource(classResource)) { dolceClassFound = true; } else { nodeIterator = classesModel.listObjectsOfProperty(classResource, RDFS.subClassOf); yagoSuperClasses.clear(); dolceSuperClasses.clear(); while (nodeIterator.hasNext()) { node = nodeIterator.next(); if (node.isResource()) { superClass = node.asResource(); if (dolceClassModel.containsResource(superClass)) { dolceSuperClasses.add(superClass); } else { yagoSuperClasses.add(superClass); } } else { LOGGER.error("Expected a resource in the statement (" + classResource + ", rdfs:subClassOf, " + node + "). Ignoring this statement."); } } // If a DOLCE class has been found if (dolceSuperClasses.size() > 0) { // add only the DOLCE classes and discard all others types.addAll(dolceSuperClasses); dolceClassFound = true; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Added super classes of " + classResource.getURI() + " --> " + Arrays.toString(dolceSuperClasses.toArray())); } } else { for (Resource r : yagoSuperClasses) { // If they have not been found before (and already have // been // added to the queue) if (!types.contains(r)) { types.add(r); queue.add(r); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Added super classes of " + classResource.getURI() + " --> " + Arrays.toString(yagoSuperClasses.toArray())); } } } } } if (!dolceClassFound) { LOGGER.warn("Couldn't find a DOLCE class for the following list of types: " + Arrays.toString(types.toArray())); } }
From source file:forge.game.mana.ManaCostBeingPaid.java
public ManaCostShard getShardToPayByPriority(Iterable<ManaCostShard> payableShards, byte possibleUses) { Set<ManaCostShard> choice = EnumSet.noneOf(ManaCostShard.class); int priority = Integer.MIN_VALUE; for (ManaCostShard toPay : payableShards) { // if m is a better to pay than choice int toPayPriority = getPayPriority(toPay, possibleUses); if (toPayPriority > priority) { priority = toPayPriority;/* ww w . ja v a2 s.c o m*/ choice.clear(); } if (toPayPriority == priority) { choice.add(toPay); } } if (choice.isEmpty()) { return null; } return Iterables.getFirst(choice, null); }
From source file:eu.europa.ec.fisheries.uvms.spatial.service.bean.impl.MapConfigServiceBean.java
private void clearReportConectServiceAreas(ReportConnectSpatialEntity entity) { Set<ReportConnectServiceAreasEntity> areas = entity.getReportConnectServiceAreas(); if (areas != null) { areas.clear(); entity.setReportConnectServiceAreas(areas); }//from w w w .ja v a 2 s . c o m }
From source file:moe.johnny.tombstone.ui.PreventFragment.java
private void selectAll(boolean checked) { if (mActivity != null && mAdapter != null) { Set<String> selections = mActivity.getSelection(); if (checked) { selections.addAll(mAdapter.getAllPreventablePackages()); } else {// ww w .j ava 2s .c o m selections.clear(); } mAdapter.notifyDataSetChanged(); } }
From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByConsumerByService.java
/** * {@inheritDoc}//from ww w .j a va 2 s . c o m */ @Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try { PreparedStatement cmd = null; ResultSet rs = null; DefaultCategoryDataset set = new DefaultCategoryDataset(); JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append( "<table class=\"table table-hover\"><tr><th>Consumer</th><th>URL</th><th>Invocations</th></tr>"); Set<String> consumers = new HashSet<String>(); // for (int i = 0; i < (consumers.size()-1); i++) { for (int k = 0; k < urls.size(); k++) { if (!isPolicyTypeOf(urls.get(k), PolicyType.TRANSACTIONAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(k), classification, ctx)) { continue; } String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(k))); consumers.clear(); try { try { cmd = con.prepareStatement( "select consumeridentity from rawdata where uri=? and (UTCdatetime > ?) and (UTCdatetime < ?) group by consumeridentity;"); cmd.setString(1, urls.get(k)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); while (rs.next()) { String s = rs.getString(1); if (!Utility.stringIsNullOrEmpty(s)) { String ids[] = s.split(";"); for (int i = 0; i < ids.length; i++) { if (!Utility.stringIsNullOrEmpty(ids[i])) { consumers.add(ids[i]); } } } } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } consumers.add("unspecified"); //ok for this service, count the times each consumer as hit it Iterator<String> iterator = consumers.iterator(); while (iterator.hasNext()) { String user = iterator.next(); long count = 0; try { cmd = con.prepareStatement("select count(*) from RawData where URI=? and " + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity ~* ?;"); cmd.setString(1, urls.get(k)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); cmd.setString(4, user); rs = cmd.executeQuery(); try { if (rs.next()) { count = rs.getLong(1); } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } if (count > 0) { //cut down on the chatter data.append("<tr><td>").append(url).append("</td><td>").append(Utility.encodeHTML(user)) .append("</td><td>"); data.append(count + ""); data.append("</td></tr>"); set.addValue(count, user, urls.get(k)); } } //this is for anonymous users or for when an identity was not //recorded by the agent long count = 0; try { cmd = con.prepareStatement("select count(*) from RawData where URI=? and " + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity is null;"); cmd.setString(1, urls.get(k)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); try { if (rs.next()) { count = rs.getLong(1); } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } if (count > 0) { //cut down on the chatter data.append("<tr><td>").append(url).append("</td><td>(not recorded)</td><td>"); data.append(count + ""); data.append("</td></tr>"); set.addValue(count, "unspecified", url); } } catch (Exception ex) { data.append("0 bytes</td></tr>"); log.log(Level.ERROR, "Error opening or querying the database.", ex); } } // insert query for unspecified chart = org.jfree.chart.ChartFactory.createBarChart(toFriendlyName(get.getType()), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false); data.append("</table>"); chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false); try { int height = pixelHeightCalc(set.getColumnCount()); ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, height); } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:com.npower.dm.hibernate.management.ProfileConfigManagementBeanImp.java
/** * Add or UpdateEntity the value of ProfileAttributeEntity ownen by the * ProfileConfigEntity. If not found ProfileAttributeValueEntity by the * attributename, will create a single value, text mode value object. If found * it, will override the attribute to single value, text mode value's object. * all of multi-value item will be deleted. * /*from www.ja v a 2s . c om*/ * Caution: Assign null to value is permitted. this will set the value to * null, AttributeValue will not be deleted! * * Caution: Order of AttributeValue will automaticlly increased! The * AttributeValue added lastestly will be bottom. * * @param name * @param value * @throws DMException */ public void setAttributeValue(ProfileConfig config, String name, String value) throws DMException { // update this profile config, first. make sure the profileID will generated // by hibernate. Session hsession = this.getHibernateSession(); hsession.saveOrUpdate(config); Clob clobValue = (value != null) ? Hibernate.createClob(value) : null; // Check exists? Set<ProfileValueMap> vMaps = ((ProfileConfigEntity) config).getProfileValueMaps(); for (Iterator<ProfileValueMap> i = vMaps.iterator(); i.hasNext();) { ProfileValueMap vMap = (ProfileValueMap) i.next(); ProfileAttributeValueEntity v = (ProfileAttributeValueEntity) vMap.getProfileAttribValue(); if (name.equals(v.getProfileAttribute().getName())) { v.setRawData(clobValue); // Set to single value mode v.setIsMultiValued(false); v.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_BIN); v.setMFormat(DDFNode.DDF_FORMAT_CHR); Set<?> valueItemSet = v.getProfileValueItems(); for (Iterator<?> j = valueItemSet.iterator(); j.hasNext();) { hsession.delete(j.next()); } valueItemSet.clear(); return; } } // Create a new AttributeValue ProfileTemplate template = config.getProfileTemplate(); ManagementBeanFactory factory = this.getManagementBeanFactory(); ProfileAttribute attr = factory.createProfileTemplateBean().getProfileAttributeByName(template.getName(), name); if (attr == null) { throw new DMException( "Could not find attribute by name: " + name + " from the template: " + template.getName()); } ProfileAttributeValue av = new ProfileAttributeValueEntity(); av.setProfileAttribute(attr); av.setRawData(clobValue); av.setIsMultiValued(false); av.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_BIN); av.setMFormat(DDFNode.DDF_FORMAT_CHR); hsession.saveOrUpdate(av); // New a ValueMapID ProfileValueMapID mapID = new ProfileValueMapID(); mapID.setAttributeValueId(av.getID()); mapID.setProfileId(config.getID()); // New a ProfileValueMap long index = ((ProfileConfigEntity) config).getProfileValueMaps().size() + 1; ProfileValueMap map = new ProfileValueMap(mapID, av, config, index); // Link to ProfileConfigEntity ((ProfileConfigEntity) config).getProfileValueMaps().add(map); hsession.saveOrUpdate(map); }
From source file:com.npower.dm.hibernate.management.ProfileConfigManagementBeanImp.java
/** * Add or UpdateEntity the value of ProfileAttributeEntity ownen by the * ProfileConfigEntity. If not found ProfileAttributeValueEntity by the * attributename, will create a single value, binary mode value object. If * found it, will override the attribute to single value, binary mode value's * object. all of multi-value item will be deleted. * //from ww w . ja v a 2s . c o m * Caution: Assign null to value is permitted. this will set the value to * null, AttributeValue will not be deleted! * * Caution: Order of AttributeValue will automaticlly increased! The * AttributeValue added lastestly will be bottom. * * @param name * @param value * @throws DMException */ public void setAttributeValue(ProfileConfig config, String name, InputStream value) throws DMException, IOException { // update this profile config, first. make sure the profileID will generated // by hibernate. Session hsession = this.getHibernateSession(); hsession.saveOrUpdate(config); Blob blobValue = null; try { blobValue = (value != null) ? Hibernate.createBlob(value) : null; } catch (IOException e) { throw e; } // Check exists? Set<ProfileValueMap> vMaps = ((ProfileConfigEntity) config).getProfileValueMaps(); for (Iterator<ProfileValueMap> i = vMaps.iterator(); i.hasNext();) { ProfileValueMap vMap = (ProfileValueMap) i.next(); ProfileAttributeValueEntity v = (ProfileAttributeValueEntity) vMap.getProfileAttribValue(); if (name.equals(v.getProfileAttribute().getName())) { v.setBinaryData(blobValue); // Set to single value mode v.setIsMultiValued(false); v.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_TEXT); v.setMFormat(DDFNode.DDF_FORMAT_BIN); // Delete multiple value Set<?> valueItemSet = v.getProfileValueItems(); for (Iterator<?> j = valueItemSet.iterator(); j.hasNext();) { hsession.delete(j.next()); } valueItemSet.clear(); return; } } // Create a new AttributeValue ProfileTemplate template = config.getProfileTemplate(); ManagementBeanFactory factory = this.getManagementBeanFactory(); ProfileAttribute attr = factory.createProfileTemplateBean().getProfileAttributeByName(template.getName(), name); if (attr == null) { throw new DMException( "Could not find attribute by name: " + name + " from the template: " + template.getName()); } ProfileAttributeValue av = new ProfileAttributeValueEntity(); av.setProfileAttribute(attr); av.setBinaryData(blobValue); av.setIsMultiValued(false); av.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_TEXT); av.setMFormat(DDFNode.DDF_FORMAT_BIN); hsession.saveOrUpdate(av); // New a ValueMapID ProfileValueMapID mapID = new ProfileValueMapID(); mapID.setAttributeValueId(av.getID()); mapID.setProfileId(config.getID()); // New a ProfileValueMap long index = ((ProfileConfigEntity) config).getProfileValueMaps().size() + 1; ProfileValueMap map = new ProfileValueMap(mapID, av, config, index); // Link to ProfileConfigEntity ((ProfileConfigEntity) config).getProfileValueMaps().add(map); hsession.saveOrUpdate(map); }
From source file:org.apache.syncope.core.util.ImportExport.java
private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames, final String schema) throws SQLException { Set<MultiParentNode<String>> roots = new HashSet<MultiParentNode<String>>(); final DatabaseMetaData meta = conn.getMetaData(); final Map<String, MultiParentNode<String>> exploited = new TreeMap<String, MultiParentNode<String>>( String.CASE_INSENSITIVE_ORDER); final Set<String> pkTableNames = new HashSet<String>(); for (String tableName : tableNames) { MultiParentNode<String> node = exploited.get(tableName); if (node == null) { node = new MultiParentNode<String>(tableName); roots.add(node);// w w w . j a va2 s.c o m exploited.put(tableName, node); } ResultSet rs = null; pkTableNames.clear(); try { rs = meta.getImportedKeys(conn.getCatalog(), readSchema(), tableName); // this is to avoid repetition while (rs.next()) { pkTableNames.add(rs.getString("PKTABLE_NAME")); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } } for (String pkTableName : pkTableNames) { if (!tableName.equalsIgnoreCase(pkTableName)) { MultiParentNode<String> pkNode = exploited.get(pkTableName); if (pkNode == null) { pkNode = new MultiParentNode<String>(pkTableName); roots.add(pkNode); exploited.put(pkTableName, pkNode); } pkNode.addChild(node); if (roots.contains(node)) { roots.remove(node); } } } } final List<String> sortedTableNames = new ArrayList<String>(tableNames.size()); MultiParentNodeOp.traverseTree(roots, sortedTableNames); Collections.reverse(sortedTableNames); return sortedTableNames; }
From source file:com.mapr.synth.CommonPointOfCompromiseTest.java
@Test public void testCompromise() throws IOException, ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long start = df.parse("2014-01-01 00:00:00").getTime(); SchemaSampler s = new SchemaSampler( Resources.asCharSource(Resources.getResource("schema013.json"), Charsets.UTF_8).read()); long exploitStart = df.parse("2014-01-20 00:00:00").getTime(); long exploitEnd = df.parse("2014-02-20 00:00:00").getTime(); int exploitStartDay = (int) TimeUnit.DAYS.convert(exploitStart - start, TimeUnit.MILLISECONDS); int[] transactionsByDay = new int[DAYS_COUNTED]; int[] compromiseByDay = new int[DAYS_COUNTED]; int[] fraudByDay = new int[DAYS_COUNTED]; Multiset<Integer> fraudUserCounts = HashMultiset.create(); Multiset<Integer> nonfraudUserCounts = HashMultiset.create(); Multiset<Integer> allMerchantCounts = HashMultiset.create(); int fraudAccounts = 0; Set<Integer> merchantHistory = Sets.newHashSet(); // these collect the evolution of the contingency table for just merchant 0 and are indexed by time relative to exploit window. int exploitLength = (int) (TimeUnit.DAYS.convert(exploitEnd - exploitStart, TimeUnit.MILLISECONDS)) + 1; // exploitLength = 5; int[] atmTotal = new int[exploitLength]; int[] atmFraud = new int[exploitLength]; int[] atmNonFraud = new int[exploitLength]; int[] nonAtmFraud = new int[exploitLength]; int[] nonAtmNonFraud = new int[exploitLength]; for (int userId = 0; userId < USER_COUNT; userId++) { JsonNode sample = s.sample();// www . jav a 2 s . c om merchantHistory.clear(); boolean userHasFraud = false; int[] hasFraudPerUser = new int[exploitLength]; for (JsonNode record : sample.get("history")) { long timestamp = record.get("timestamp").asLong() * 1000; int day = (int) ((timestamp - start) / TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); if (day >= DAYS_COUNTED || day >= exploitStartDay + exploitLength) { break; } if (record.get("compromise").asInt() > 0) { compromiseByDay[day]++; } boolean isFraud = record.get("fraud").asInt() > 0; if (isFraud) { fraudByDay[day]++; } transactionsByDay[day]++; // only record history up to the beginning of the exploit window int merchant = record.get("merchant").asInt(); if (timestamp < exploitStart) { merchantHistory.add(merchant); } // only consider fraud indicators during the exploit window if (timestamp >= exploitStart && timestamp <= exploitEnd) { // any fraud in the window marks the user if (isFraud) { // first time we see fraud indication in exploit window, we set flags for the rest of the window if (!userHasFraud) { int eday = day - exploitStartDay; for (int i = eday; i < exploitLength; i++) { hasFraudPerUser[i] = 1; } } userHasFraud = true; } } } // we collect flags for each day and then only count this user once. Necessary because multiple // transactions can occur on each day and we don't want to count all of them. int atmInHistory = merchantHistory.contains(0) ? 1 : 0; for (int day = 0; day < exploitLength; day++) { atmTotal[day] += atmInHistory; atmFraud[day] += atmInHistory * hasFraudPerUser[day]; atmNonFraud[day] += atmInHistory * (1 - hasFraudPerUser[day]); nonAtmFraud[day] += (1 - atmInHistory) * hasFraudPerUser[day]; nonAtmNonFraud[day] += (1 - atmInHistory) * (1 - hasFraudPerUser[day]); } if (userHasFraud) { fraudAccounts++; for (Integer merchant : merchantHistory) { fraudUserCounts.add(merchant); allMerchantCounts.add(merchant); } } else { for (Integer merchant : merchantHistory) { nonfraudUserCounts.add(merchant); allMerchantCounts.add(merchant); } } } int k1 = fraudAccounts; int k2 = USER_COUNT - k1; try (PrintStream out = new PrintStream(new FileOutputStream("scores.tsv"))) { out.printf("merchant\tk11\tk12\tk21\tk22\tk.1\tscore\n"); for (Integer merchant : allMerchantCounts.elementSet()) { int k11 = fraudUserCounts.count(merchant); int k12 = k1 - k11; int k21 = nonfraudUserCounts.count(merchant); int k22 = k2 - k21; out.printf("%d\t%d\t%d\t%d\t%d\t%d\t%.1f\n", merchant, k11, k12, k21, k22, allMerchantCounts.count(merchant), LogLikelihood.rootLogLikelihoodRatio(k11, k12, k21, k22)); } } try (PrintStream out = new PrintStream(new FileOutputStream("counts.tsv"))) { out.printf("day\tcompromises\tfrauds\ttransactions\n"); for (int i = 0; i < compromiseByDay.length; i++) { out.printf("%d\t%d\t%d\t%d\n", i, compromiseByDay[i], fraudByDay[i], transactionsByDay[i]); } } try (PrintStream out = new PrintStream(new FileOutputStream("growth.tsv"))) { out.printf("day\tatm.total\tk11\tk12\tk21\tk22\tscore\n"); for (int i = 0; i < exploitLength; i++) { int k11 = atmFraud[i]; int k12 = nonAtmFraud[i]; int k21 = atmNonFraud[i]; int k22 = nonAtmNonFraud[i]; out.printf("%d\t%d\t%d\t%d\t%d\t%d\t%.1f\n", i, atmTotal[i], k11, k12, k21, k22, LogLikelihood.rootLogLikelihoodRatio(k11, k12, k21, k22)); } } }