public Set<String> getDownloadEntries(final NodeRef downloadNode) { return transactionHelper.doInTransaction(new RetryingTransactionCallback<Set<String>>() { @Override public Set<String> execute() throws Throwable { Set<String> entryNames = new TreeSet<String>(); ContentReader reader = contentService.getReader(downloadNode, ContentModel.PROP_CONTENT); try (ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(reader.getContentInputStream())) { ZipArchiveEntry zipEntry = null; while ((zipEntry = zipInputStream.getNextZipEntry()) != null) { String name = zipEntry.getName(); entryNames.add(name); } } return entryNames; } }); }
/** * 按最后播放时间降序排序 */ public static List<DBSongInfo> descSortByLastPlayTime(List<DBSongInfo> list) { TreeSet<DBSongInfo> set = new TreeSet<>(new Comparator<DBSongInfo>() { @Override public int compare(DBSongInfo o1, DBSongInfo o2) { int rs; if (o1.lastPlayTime > o2.lastPlayTime) { rs = -1; } else if (o1.lastPlayTime < o2.lastPlayTime) { rs = 1; } else { rs = -1; // equals set 不能重复,会丢失数据 } return rs; } }); for (DBSongInfo s : list) { set.add(s); } return new ArrayList<>(set); }
protected String getTransactionTraceSignature(Procedure catalog_proc, TransactionTrace txn_trace, Integer interval) { SortedSet<String> queries = new TreeSet<String>(); for (QueryTrace query_trace : txn_trace.getQueries()) { Statement catalog_stmt = query_trace.getCatalogItem(catalog_db); queries.add(this.getQueryTraceSignature(catalog_stmt, query_trace)); } // FOR String signature = catalog_proc.getName() + "->"; if (interval != null) signature += "INT[" + interval + "]"; signature += this.getParamSignature(txn_trace, this.target_proc_params.get(catalog_proc)); for (String q : queries) { signature += "\n" + q; } // FOR if (trace.val) LOG.trace(txn_trace + " ==> " + signature); return (signature); }
/** * Mark a path to be deleted on JVM shutdown. * * @param f the existing path to delete. * * @return true if deleteOnExit is successful, otherwise false. * * @throws AccessControlException If access is denied * @throws UnsupportedFileSystemException If file system for <code>f</code> is * not supported * @throws IOException If an I/O error occurred * * Exceptions applicable to file systems accessed over RPC: * @throws RpcClientException If an exception occurred in the RPC client * @throws RpcServerException If an exception occurred in the RPC server * @throws UnexpectedServerException If server implementation throws * undeclared exception to RPC server */ public boolean deleteOnExit(Path f) throws AccessControlException, IOException { if (!this.util().exists(f)) { return false; } synchronized (DELETE_ON_EXIT) { if (DELETE_ON_EXIT.isEmpty()) { ShutdownHookManager.get().addShutdownHook(FINALIZER, SHUTDOWN_HOOK_PRIORITY); } Set<Path> set = DELETE_ON_EXIT.get(this); if (set == null) { set = new TreeSet<Path>(); DELETE_ON_EXIT.put(this, set); } set.add(f); } return true; }
@Override public void addInterfaceElements(Interface interfaze) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); FullyQualifiedJavaType parameterType = new FullyQualifiedJavaType( introspectedTable.getBaseRecordType()); importedTypes.add(parameterType); Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); method.setReturnType(FullyQualifiedJavaType.getIntInstance()); method.setName(introspectedTable.getUpdateByPrimaryKeyStatementId()); method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$ context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable); addMapperAnnotations(interfaze, method); if (context.getPlugins() .clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(method, interfaze, introspectedTable)) { interfaze.addImportedTypes(importedTypes); interfaze.addMethod(method); } }
@Parameters public static Iterable<Object[]> getParameters() { return Arrays.asList(new Object[][] { // @formatter:off // (0) There aren't any unused ports: { new StepInput("apps-to-deploy-02.json", new TreeSet<>(Arrays.asList(10002, 10003)), true), new StepOutput(new TreeSet<>(Arrays.asList(10002, 10003))), }, // (1) There are unused ports: { new StepInput("apps-to-deploy-02.json", new TreeSet<>(Arrays.asList(10001, 10002, 10003)), true), new StepOutput(new TreeSet<>(Arrays.asList(10002, 10003))), }, // (2) Host based routing: { new StepInput("apps-to-deploy-02.json", Collections.emptySet(), false), new StepOutput(Collections.emptySet()), }, // @formatter:on }); }
/** * Tests data serializing an {@link TreeSet} */ @Test public void testTreeSet() throws Exception { Random random = getRandom(); TreeSet set = new TreeSet(); int size = random.nextInt(50); for (int i = 0; i < size; i++) { set.add(new Long(random.nextLong())); } DataOutputStream out = getDataOutput(); DataSerializer.writeTreeSet(null, out); DataSerializer.writeTreeSet(new TreeSet(), out); DataSerializer.writeTreeSet(set, out); out.flush(); DataInput in = getDataInput(); assertEquals(null, DataSerializer.readTreeSet(in)); assertEquals(new TreeSet(), DataSerializer.readTreeSet(in)); TreeSet set2 = DataSerializer.readTreeSet(in); assertEquals(set, set2); }
private void addExtensions(TarArchiveOutputStream tos, Integration integration) throws IOException { final Set<String> extensions = collectDependencies(integration).stream() .filter(Dependency::isExtension) .map(Dependency::getId) .collect(Collectors.toCollection(TreeSet::new)); if (!extensions.isEmpty()) { addTarEntry(tos, "src/main/resources/loader.properties", generateExtensionLoader(extensions)); for (String extensionId : extensions) { addTarEntry( tos, "extensions/" + Names.sanitize(extensionId) + ".jar", IOUtils.toByteArray( extensionDataManager.getExtensionBinaryFile(extensionId) ) ); } } }
/** * Called to identify a transformer that cannot be used during working out * available transformers. */ public void unavailableTransformer(ContentTransformer transformer, String sourceMimetype, String targetMimetype, long maxSourceSizeKBytes) { if (isEnabled()) { Deque<Frame> ourStack = ThreadInfo.getStack(); Frame frame = ourStack.peek(); if (frame != null) { Deque<String> isTransformableStack = ThreadInfo.getIsTransformableStack(); String name = (!isTransformableStack.isEmpty()) ? isTransformableStack.getFirst() : getName(transformer); boolean debug = (maxSourceSizeKBytes != 0); if (frame.unavailableTransformers == null) { frame.unavailableTransformers = new TreeSet<UnavailableTransformer>(); } String priority = gePriority(transformer, sourceMimetype, targetMimetype); frame.unavailableTransformers.add(new UnavailableTransformer(name, priority, maxSourceSizeKBytes, debug)); } } }
public static void setupDepartments(HttpServletRequest request, SessionContext context, boolean includeExternal) throws Exception { TreeSet<Department> departments = Department.getUserDepartments(context.getUser()); if (includeExternal) departments.addAll(Department.findAllExternal(context.getUser().getCurrentAcademicSessionId())); List<LabelValueBean> deptList = new ArrayList<LabelValueBean>(); for (Department d: departments) { String code = d.getDeptCode().trim(); String abbv = d.getName().trim(); if (d.isExternalManager()) deptList.add(new LabelValueBean(code + " - " + abbv + " (" + d.getExternalMgrLabel() + ")", code)); else deptList.add(new LabelValueBean(code + " - " + abbv, code)); } request.setAttribute(Department.DEPT_ATTR_NAME, deptList); }
protected boolean addCategory(String id, String category, String value, String score) { if (noData(category)) return false; if (noData(value)) return false; if (noData(score)) return false; Collection<ClassificationScore> categoryCollection = categories.get(category); if (categoryCollection == null) { categoryCollection = new TreeSet<ClassificationScore>(); categories.put(category, categoryCollection); } try { ClassificationScore classificationScore = new ClassificationScore(category, value, score); if (!noData(id)) classificationScore.setId(id); categoryCollection.add(classificationScore); return true; } catch (NumberFormatException e) { logger.warn("Bad format for score: " + score); return false; } }
private static List<DateRange> getSegmentDateRanges(final List<DecisionTreeRule> rules, final Set<ValueGroup> changeGroup) { final Set<Instant> times = new TreeSet<>(); rules.forEach(rule -> { times.add(rule.getStart()); times.add(rule.getEnd()); }); changeGroup.forEach(group -> { times.add(group.getRange().getStart()); times.add(group.getRange().getFinish()); }); final List<Instant> ordered = new ArrayList<>(times); final List<DateRange> slices = new ArrayList<>(1); for (int i = 0; i < times.size() - 1; ++i) { final DateRange dateTimeSlice = new DateRange(ordered.get(i), ordered.get(i + 1)); slices.add(dateTimeSlice); } return slices; }
private void getEventTimes(TreeSet<Long> out, boolean descendsPNode) { boolean isPNode = TAG_P.equals(tag); if (descendsPNode || isPNode) { if (startTimeUs != UNDEFINED_TIME) { out.add(startTimeUs); } if (endTimeUs != UNDEFINED_TIME) { out.add(endTimeUs); } } if (children == null) { return; } for (int i = 0; i < children.size(); i++) { children.get(i).getEventTimes(out, descendsPNode || isPNode); } }
public static String dayCodes2str(Collection dayCodes, String delim) { StringBuffer sb = new StringBuffer(); for (Iterator i=(new TreeSet(dayCodes)).iterator();i.hasNext();) { int dayCode = ((TimePatternDays)i.next()).getDayCode().intValue(); int nrDays = 0; for (int j=0;j<Constants.NR_DAYS;j++) if ((dayCode&Constants.DAY_CODES[j])!=0) nrDays++; for (int j=0;j<Constants.NR_DAYS;j++) { if ((Constants.DAY_CODES[j]&dayCode)==0) continue; sb.append(nrDays==1?CONSTANTS.days()[j]:CONSTANTS.shortDays()[j]); } if (i.hasNext()) sb.append(delim); } return sb.toString(); }
@Override public List<Change> getMigrations() { Collection<String> filenames = new TreeSet<>(); for (Resource res : getResources("/*.sql")) { filenames.add(res.getFilename()); } filenames.remove(BOOTSTRAP_SQL); filenames.remove(ONABORT_SQL); return filenames.stream() .map(this::parseChangeFromFilename) .collect(Collectors.toList()); }
@Override public boolean add(final E e) { if (innerSet.contains(e)) { return false; } else { innerSet.add(e); for (final Function<E, Object> fn : indexMap.keySet()) { final Map<Object, Set<E>> map = indexMap.get(fn); final Object value = fn.apply(e); if (map.containsKey(value)) { map.get(value).add(e); } else { final Set<E> set = new TreeSet<>(comparator); set.add(e); map.put(value, set); } } return true; } }
protected String getMeetingRooms(boolean html, Class_ clazz) { String meetingRooms = ""; Assignment assignment = clazz.getCommittedAssignment(); TreeSet<Meeting> meetings = (clazz.getEvent()==null?null:new TreeSet(clazz.getEvent().getMeetings())); TreeSet<Location> locations = new TreeSet<Location>(); if (meetings!=null && !meetings.isEmpty()) { for (Meeting meeting : meetings) if (meeting.getLocation()!=null) locations.add(meeting.getLocation()); } else if (assignment!=null && assignment.getDatePattern()!=null) { for (Iterator i=assignment.getRooms().iterator();i.hasNext();) { locations.add((Location)i.next()); } } for (Location location: locations) { if (meetingRooms.length()>0) meetingRooms+=", "; meetingRooms+=(html ? location.getLabelWithHint() : location.getLabel()); } return meetingRooms; }
/** * Removes the specified list of authentication domains from the never save list. * @throws IOException if the credential storage metadata cannot be modified. */ public void removeFromNeverSaveList(List<AuthenticationDomain> authDomains) throws IOException { CredentialMeta meta = readCredentialMeta(); TreeSet<String> neverSaveDomains = new TreeSet<>(); for (String neverSaveDomain : meta.getNeverSaveList()) { neverSaveDomains.add(neverSaveDomain); } for (AuthenticationDomain authDomain : authDomains) { neverSaveDomains.remove(authDomain.toString()); } writeCredentialMeta( meta.toBuilder() .clearNeverSave() .addAllNeverSave(neverSaveDomains) .build()); }
static @CheckForNull Set<String> existingModes(NewTCIterator.DataModel data) throws IOException { FileSystem fs = data.getProject().getLookup().lookup(NbModuleProvider.class).getEffectiveSystemFilesystem(); data.setSFS(fs); FileObject foRoot = fs.getRoot().getFileObject("Windows2/Modes"); //NOI18N if (foRoot != null) { FileObject[] fos = foRoot.getChildren(); Set<String> col = new TreeSet<String>(); for (FileObject fo : fos) { if (fo.isData() && "wsmode".equals(fo.getExt())) { //NOI18N col.add(fo.getName()); data.existingMode(fo.getName()); } } return col; } else { return null; } }
public void testRecursiveScanOptimization() throws Exception { FileObject src = nbRoot().getFileObject("apisupport.project/test/unit/src"); assertNotNull("apisupport.project/test/unit/src", src); Logger logger = Logger.getLogger("org.netbeans.modules.apisupport.project.Evaluator"); MyHandler h = new MyHandler(); logger.addHandler(h); Level origL = logger.getLevel(); try { logger.setLevel(Level.FINE); ClassPath cp = ClassPath.getClassPath(src, ClassPath.EXECUTE); assertNotNull("have an EXECUTE classpath", cp); Set<String> expectedRoots = new TreeSet<String>(); // 247 entries & 5848 processed module entries before optimization // 142 processed entries with duplicate entries pruned assertTrue("Each module entry processed at most once", h.c <= 2 * cp.getRoots().length); } finally { logger.setLevel(origL); logger.removeHandler(h); } }
/** * * @param msg * the group details in json format to be parsed * @return the group id of the group contained in the message * -2 if this message has already been received */ private int extractGroupInfo(String msg) { TreeSet<Node> set = new TreeSet<>(); Group group = null; JsonObject obj = new JsonObject(msg); String prime = obj.getString(Constants.PRIME); String generator = obj.getString(Constants.GENERATOR); JsonArray members = obj.getJsonArray(Constants.MEMBERS); Iterator<?> iter = members.iterator(); while (iter.hasNext()) { JsonObject member = (JsonObject) iter.next(); String ip = member.getString(Constants.IP); String port = member.getString(Constants.PORT); Node n = new Node(ip, port); set.add(n); } group = new Group(generator, prime, set); if (stateMappings.containsKey(group.getGroupId()) && !stateMappings.get(group.getGroupId()).isDone()) return -2; // message received twice group.setGenerator(new BigInteger(generator)); group.setPrime(new BigInteger(prime)); groupMappings.put(group.getGroupId(), group); stateMappings.put(group.getGroupId(), new ExchangeState(group.getGroupId(), group.getGenerator())); return group.getGroupId(); }
@Override public void addImplementationElements(TopLevelClass topLevelClass) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); Method method = getMethodShell(importedTypes); StringBuilder sb = new StringBuilder(); sb.append("int rows = "); //$NON-NLS-1$ sb.append(daoTemplate.getDeleteMethod(introspectedTable .getIbatis2SqlMapNamespace(), introspectedTable .getDeleteByExampleStatementId(), "example")); //$NON-NLS-1$ method.addBodyLine(sb.toString()); method.addBodyLine("return rows;"); //$NON-NLS-1$ if (context.getPlugins().clientDeleteByExampleMethodGenerated( method, topLevelClass, introspectedTable)) { topLevelClass.addImportedTypes(importedTypes); topLevelClass.addMethod(method); } }
public SubtypeLocaleAdapter(final Context context) { super(context, android.R.layout.simple_spinner_item); setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final TreeSet<SubtypeLocaleItem> items = new TreeSet<>(); final InputMethodInfo imi = RichInputMethodManager.getInstance() .getInputMethodInfoOfThisIme(); final int count = imi.getSubtypeCount(); for (int i = 0; i < count; i++) { final InputMethodSubtype subtype = imi.getSubtypeAt(i); if (DEBUG_SUBTYPE_ID) { Log.d(TAG_SUBTYPE, String.format("%-6s 0x%08x %11d %s", subtype.getLocale(), subtype.hashCode(), subtype.hashCode(), SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype))); } if (InputMethodSubtypeCompatUtils.isAsciiCapable(subtype)) { items.add(new SubtypeLocaleItem(subtype)); } } // TODO: Should filter out already existing combinations of locale and layout. addAll(items); }
/** * Returns sorted arrays of CNBs of available friends for this module. */ String[] getAvailableFriends() { SortedSet<String> set = new TreeSet<String>(); if (isSuiteComponent()) { for (Iterator it = SuiteUtils.getSubProjects(getSuite()).iterator(); it.hasNext();) { Project prj = (Project) it.next(); String cnb = ProjectUtils.getInformation(prj).getName(); if (!getCodeNameBase().equals(cnb)) { set.add(cnb); } } } else if (isNetBeansOrg()) { Set<ModuleDependency> deps = getUniverseDependencies(false); for (Iterator it = deps.iterator(); it.hasNext();) { ModuleDependency dep = (ModuleDependency) it.next(); set.add(dep.getModuleEntry().getCodeNameBase()); } } // else standalone module - leave empty (see the UI spec) return set.toArray(new String[set.size()]); }
private void dumpSystemInfo() { // output all the possible target system information -- this may help to // devise the configuration differences in case of errors LogManager.logEntry("dumping target system information"); // NOI18N LogManager.logIndent("system properties:"); // NOI18N for (Object key: new TreeSet<Object>(System.getProperties().keySet())) { LogManager.log(key.toString() + " => " + // NOI18N System.getProperties().get(key).toString()); } LogManager.unindent(); LogManager.logExit("... end of target system information"); // NOI18N }
@Override public SynthesizedPlanFragment[] generateRestorePlan(Table catalogTable) { SystemProcedureExecutionContext context = this.getSystemProcedureExecutionContext(); assert (context != null); Host catalog_host = context.getHost(); Collection<Site> catalog_sites = CatalogUtil.getSitesForHost(catalog_host); LOG.info("Replicated :: Table: " + getTableName()); Set<Integer> execution_site_ids = new TreeSet<Integer>(); for (Site catalog_site : catalog_sites) { execution_site_ids.add(catalog_site.getId()); } for (int hostId : m_hostsWithThisTable) { m_sitesWithThisTable.addAll(execution_site_ids); } SynthesizedPlanFragment[] restore_plan = null; if (catalogTable.getIsreplicated()) { restore_plan = generateReplicatedToReplicatedPlan(); } else { // XXX Not implemented until we're going to support catalog changes } return restore_plan; }
@Override public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) { List<JCTree> result = super.translateTopLevelClass(env, cdef, make); Map<Symbol, JCMethodDecl> declarations = new HashMap<>(); Set<Symbol> toDump = new TreeSet<>(symbolComparator); new TreeScanner() { @Override public void visitMethodDef(JCMethodDecl tree) { if (tree.name.toString().startsWith("dump")) { toDump.add(tree.sym); } declarations.put(tree.sym, tree); super.visitMethodDef(tree); } }.scan(result); for (Symbol d : toDump) { dump(d, declarations, new HashSet<>()); } return result; }
public static TreeSet<StudentSectioningQueue> getItems(org.hibernate.Session hibSession, Long sessionId, Date lastTimeStamp) { if (sessionId != null) { if (lastTimeStamp == null) { return new TreeSet<StudentSectioningQueue>( hibSession.createQuery("select q from StudentSectioningQueue q where q.sessionId = :sessionId") .setLong("sessionId", sessionId).list()); } else { return new TreeSet<StudentSectioningQueue>( hibSession.createQuery("select q from StudentSectioningQueue q where q.sessionId = :sessionId and q.timeStamp > :timeStamp") .setLong("sessionId", sessionId).setTimestamp("timeStamp", lastTimeStamp).list()); } } else { if (lastTimeStamp == null) { return new TreeSet<StudentSectioningQueue>( hibSession.createQuery("select q from StudentSectioningQueue q").list()); } else { return new TreeSet<StudentSectioningQueue>( hibSession.createQuery("select q from StudentSectioningQueue q where q.timeStamp > :timeStamp") .setTimestamp("timeStamp", lastTimeStamp).list()); } } }
private TreeSet<LSDFact> expandPackageLevelCluster2TypeElements(PrintStream p, List<LSDFact> packageLevelCluster) { TreeSet<LSDFact> ontheflyDeltaKB = new TreeSet<LSDFact>(); TreeSet<String> packageConstants = null; // collect a list of package name constants if (packageLevelCluster !=null) { packageConstants = new TreeSet<String>(); for (LSDFact packageF: packageLevelCluster) { packageConstants.add(packageF.getBindings().get(0).getGroundConst()); } } for (String kind: typeLevel.keySet()) { for (LSDFact typeF: typeLevel.get(kind)) { String containerPackage= typeF.getBindings().get(2).getGroundConst(); if (packageConstants==null || packageConstants.contains(containerPackage)) { if (p!=null) p.println("\t" + typeF); ontheflyDeltaKB.add(typeF); } } } return ontheflyDeltaKB; }
/** * @return A json representation of the topology. Intended for printing only. */ public static final String toJson(ITopology topo, boolean pretty) throws IOException { ObjectMapper mapper = new ObjectMapper(); if (pretty) mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); JsonFactory f = mapper.getFactory(); JsonGenerator g = f.createGenerator(sw); g.writeStartObject(); // use TreeSet to sort the list g.writeObjectField("switches", new TreeSet<String>(topo.getSwitches().keySet())); g.writeObjectField("links", new TreeSet<String>(topo.getLinks().keySet())); g.writeEndObject(); g.close(); return sw.toString(); }
public void testAllVersionsTested() throws Exception { SortedSet<String> expectedVersions = new TreeSet<>(); for (Version v : VersionUtils.allReleasedVersions()) { if (VersionUtils.isSnapshot(v)) continue; // snapshots are unreleased, so there is no backcompat yet if (v.isRelease() == false) continue; // no guarantees for prereleases if (v.before(Version.CURRENT.minimumIndexCompatibilityVersion())) continue; // we can only support one major version backward if (v.equals(Version.CURRENT)) continue; // the current version is always compatible with itself expectedVersions.add("index-" + v.toString() + ".zip"); } for (String index : indexes) { if (expectedVersions.remove(index) == false) { logger.warn("Old indexes tests contain extra index: {}", index); } } if (expectedVersions.isEmpty() == false) { StringBuilder msg = new StringBuilder("Old index tests are missing indexes:"); for (String expected : expectedVersions) { msg.append("\n" + expected); } fail(msg.toString()); } }
public void populate(TreeSet<CurriculumClassificationInterface> classifications) { int col = 0; for (AcademicClassificationInterface clasf: iClassifications) { CurriculumClassificationInterface ci = null; if (classifications != null && !classifications.isEmpty()) for (CurriculumClassificationInterface x: classifications) { if (x.getAcademicClassification().getId().equals(clasf.getId())) { ci = x; break; } } if (ci == null) { setName(col, clasf.getCode()); setExpected(col, null); setEnrollment(col, null); setLastLike(col, null); setProjection(col, null); setRequested(col, null); setSnapshotExpected(col, null); setSnapshotProjection(col, null); } else { setName(col, ci.getName()); setExpected(col, ci.getExpected()); setEnrollment(col, ci.getEnrollment()); setLastLike(col, ci.getLastLike()); setProjection(col, ci.getProjection()); setRequested(col, ci.getRequested()); setSnapshotExpected(col, (!ci.isSessionHasSnapshotData() ? null : ci.getSnapshotExpected())); setSnapshotProjection(col, (!ci.isSessionHasSnapshotData() ? null : ci.getSnapshotProjection())); } col++; } }
public void testUserHasPreferenceOverFSs() throws Exception { FileObject global = FileUtil.createData(FileUtil.getConfigRoot(), "dir/file.txt"); global.setAttribute("global", 3); write(global, "global"); FileObject fo1 = FileUtil.createData(fs1.getRoot(), "dir/file.txt"); fo1.setAttribute("one", 1); write(fo1, "fileone"); FileObject fo2 = FileUtil.createData(fs2.getRoot(), "dir/file.txt"); fo2.setAttribute("two", 2); write(fo2, "two"); events.clear(); MainLookup.register(fs1, this); MainLookup.register(fs2, this); Enumeration<String> en = global.getAttributes(); TreeSet<String> t = new TreeSet<String>(); while (en.hasMoreElements()) { t.add(en.nextElement()); } assertEquals("three elements: " + t, 3, t.size()); assertTrue(t.contains("two")); assertTrue(t.contains("one")); assertTrue(t.contains("global")); assertEquals(1, global.getAttribute("one")); assertEquals(2, global.getAttribute("two")); assertEquals(3, global.getAttribute("global")); assertEquals("contains global", 6, global.getSize()); assertEquals("global", read(global)); assertTrue("no events: " + events, events.isEmpty()); }
@Override public String htmlLabel() { Set<TeachingClassRequest> requests = new TreeSet<TeachingClassRequest>(getClassRequests()); String classes = null; for (TeachingClassRequest r: requests) { if (classes == null) classes = r.getTeachingClass().htmlLabel(); else classes += ", " + r.getTeachingClass().htmlLabel(); } return getOffering().getCourseName() + (classes == null ? "" : " " + classes); }
private static String normaliseMetaStoreUris(String metaStoreUris) { try { String[] rawUris = metaStoreUris.split(","); Set<String> uris = new TreeSet<>(); for (String rawUri : rawUris) { URI uri = new URI(rawUri); uris.add(uri.toString()); } return Joiner.on(",").join(uris); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
private void printReturnInMethod(PrintStream p, TreeSet<LSDFact> ontheflyDeltaKB, LSDFact methodF) { for (LSDFact fact:originalDeltaKB) { if (fact.getPredicate().getName().indexOf("_return")>0 && fact.getBindings().get(0).getGroundConst().equals(methodF.getBindings().get(0).getGroundConst())){ if (filter.methodLevel) ontheflyDeltaKB.add(fact); if (filter.methodLevel&& p!=null) p.println("\t\t\t"+ fact); } } }
/** Ordered set of distribution objects */ public Set<DistributionObject> getOrderedSetOfDistributionObjects() { try { return new TreeSet<DistributionObject>(getDistributionObjects()); } catch (ObjectNotFoundException ex) { (new DistributionPrefDAO()).getSession().refresh(this); return new TreeSet<DistributionObject>(getDistributionObjects()); } }
@Override public void addInterfaceElements(Interface interfaze) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); Method method = getMethodShell(importedTypes); if (context.getPlugins().clientSelectByPrimaryKeyMethodGenerated( method, interfaze, introspectedTable)) { interfaze.addImportedTypes(importedTypes); interfaze.addMethod(method); } }
private static Set<String> getTableSet(ServerConnection c, Map<String, String> parm) { TreeSet<String> tableSet = new TreeSet<String>(); MycatConfig conf = MycatServer.getInstance().getConfig(); Map<String, UserConfig> users = conf.getUsers(); UserConfig user = users == null ? null : users.get(c.getUser()); if (user != null) { Map<String, SchemaConfig> schemas = conf.getSchemas(); for (String name:schemas.keySet()){ if (null !=parm.get(SCHEMA_KEY) && parm.get(SCHEMA_KEY).toUpperCase().equals(name.toUpperCase()) ){ if(null==parm.get("LIKE_KEY")){ tableSet.addAll(schemas.get(name).getTables().keySet()); }else{ String p = "^" + parm.get("LIKE_KEY").replaceAll("%", ".*"); Pattern pattern = Pattern.compile(p,Pattern.CASE_INSENSITIVE); Matcher ma ; for (String tname : schemas.get(name).getTables().keySet()){ ma=pattern.matcher(tname); if(ma.matches()){ tableSet.add(tname); } } } } }; } return tableSet; }
/** * Similar to {@link File#listFiles()}, but returns a sorted set. * Never returns {@code null}, instead a warning is logged, and an empty set is returned. */ public static SortedSet<File> listFiles(File dir) { File[] files = dir.listFiles(); if (files == null) { Log.w(TAG, String.format("Failed to list children for %s", dir.getPath())); return new TreeSet<File>(); } return new TreeSet<File>(Arrays.asList(files)); }