List of usage examples for java.util SortedSet add
boolean add(E e);
From source file:net.sourceforge.fenixedu.domain.DegreeCurricularPlan.java
/** * Method to get a filtered list of a dcp's competence courses in the given * execution year. Each competence courses is connected with a curricular * course with at least one open context in the execution year * //from w ww .j av a 2 s. c o m * @return All competence courses that are present in the dcp */ public List<CompetenceCourse> getCompetenceCourses(ExecutionYear executionYear) { SortedSet<CompetenceCourse> result = new TreeSet<CompetenceCourse>( CompetenceCourse.COMPETENCE_COURSE_COMPARATOR_BY_NAME); if (isBolonhaDegree()) { for (final CurricularCourse curricularCourse : getCurricularCourses(executionYear)) { if (!curricularCourse.isOptionalCurricularCourse()) { result.add(curricularCourse.getCompetenceCourse()); } } return new ArrayList<CompetenceCourse>(result); } else { return new ArrayList<CompetenceCourse>(); } }
From source file:org.trpr.platform.servicefw.impl.spring.web.HomeController.java
private List<ResourceInfo> findMethods(Map<String, Object> handlerMap, Set<String> urls) { SortedSet<ResourceInfo> result = new TreeSet<ResourceInfo>(); for (String key : urls) { Object handler = handlerMap.get(key); Class<?> handlerType = ClassUtils.getUserClass(handler); HandlerMethodResolver resolver = new HandlerMethodResolver(); resolver.init(handlerType);// www . ja v a 2s . com String[] typeMappings = null; RequestMapping typeMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (typeMapping != null) { typeMappings = typeMapping.value(); } Set<Method> handlerMethods = resolver.getHandlerMethods(); for (Method method : handlerMethods) { RequestMapping mapping = method.getAnnotation(RequestMapping.class); Collection<String> computedMappings = new HashSet<String>(); if (typeMappings != null) { computedMappings.addAll(Arrays.asList(typeMappings)); } for (String path : mapping.value()) { if (typeMappings != null) { for (String parent : computedMappings) { if (parent.endsWith("/")) { parent = parent.substring(0, parent.length() - 1); } computedMappings.add(parent + path); } } else { computedMappings.add(path); } } logger.debug("Analysing mappings for method:" + method.getName() + ", key:" + key + ", computed mappings: " + computedMappings); if (computedMappings.contains(key)) { RequestMethod[] methods = mapping.method(); if (methods != null && methods.length > 0) { for (RequestMethod requestMethod : methods) { logger.debug( "Added explicit mapping for path=" + key + "to RequestMethod=" + requestMethod); result.add(new ResourceInfo(key, requestMethod)); } } else { logger.debug("Added implicit mapping for path=" + key + "to RequestMethod=GET"); result.add(new ResourceInfo(key, RequestMethod.GET)); } } } if (handlerMethods.isEmpty()) { result.add(new ResourceInfo(key, RequestMethod.GET)); } } return new ArrayList<ResourceInfo>(result); }
From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java
/** * Builds list of reports available for tableid. *///from www . j a v a2s. c o m protected SortedSet<SearchResultReportServiceInfo> getReports(int tableId, final QueryBldrPane queryBuilder) { SortedSet<SearchResultReportServiceInfo> reports = new TreeSet<SearchResultReportServiceInfo>( new Comparator<SearchResultReportServiceInfo>() { public int compare(SearchResultReportServiceInfo o1, SearchResultReportServiceInfo o2) { return o1.getReportName().compareTo(o2.getReportName()); } }); boolean buildEm = true; if (AppContextMgr.isSecurityOn()) { Taskable reportsTask = ContextMgr.getTaskByClass(ReportsTask.class); if (reportsTask != null) { buildEm = reportsTask.getPermissions().canView(); } } if (buildEm) { //first add reports associated directly with the results if (queryBuilder != null) { for (SpReport rep : queryBuilder.getReportsForQuery()) { if (repContextIsActive(rep.getAppResource())) { reports.add(new SearchResultReportServiceInfo(rep.getName(), rep.getName(), true, null, rep.getAppResource().getId(), rep.getRepeats())); } } } if (tableId != -1) { //second add reports associated with the same table as the current results List<AppResourceIFace> reps = AppContextMgr.getInstance() .getResourceByMimeType(ReportsBaseTask.LABELS_MIME); reps.addAll(AppContextMgr.getInstance().getResourceByMimeType(ReportsBaseTask.REPORTS_MIME)); for (AppResourceIFace rep : reps) { String tblIdStr = rep.getMetaData("tableid"); if (tblIdStr != null) { if (tableId == Integer.valueOf(tblIdStr)) { reports.add(new SearchResultReportServiceInfo( rep.getDescription() /*'title' seems to be currently stored in description */, rep.getName() /* and filename in name */, false, null, ((SpAppResource) rep).getId(), null)); } else { //third add reports based on other queries... DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { SpReport spRep = (SpReport) session.getData( "from SpReport where appResourceId = " + ((SpAppResource) rep).getId()); if (spRep != null && spRep.getQuery() != null && spRep.getQuery().getContextTableId().intValue() == tableId) { reports.add(new SearchResultReportServiceInfo(rep.getDescription() /* * 'title' seems to be * currently stored in * description */, rep.getName() /* and filename in name */, false, spRep.getId(), ((SpAppResource) rep).getId(), null)); } } finally { session.close(); } } } } } } return reports; }
From source file:fr.cnes.sitools.proxy.AbstractDirectoryServerResource.java
/** * Returns the list of variants for the given method. * //from w ww. ja va 2 s .co m * @param method * The related method. * @return The list of variants for the given method. * * @see DirectoryServerResource.getVariants(Method method) */ public List<Variant> getVariants(Method method) { List<Variant> result = null; if ((Method.GET.equals(method) || Method.HEAD.equals(method))) { if (variantsGet != null) { result = variantsGet; } else { getLogger().fine("Getting variants for : " + getTargetUri()); if ((this.getDirectoryContent() != null) && (getReference() != null) && (getReference().getBaseRef() != null)) { // Allows to sort the list of representations SortedSet<Representation> resultSet = new TreeSet<Representation>( getRepresentationsComparator()); // Compute the base reference (from a call's client point of // view) String baseRef = getReference().getBaseRef().toString(false, false); if (!baseRef.endsWith("/")) { baseRef += "/"; } int lastIndex = this.relativePart.lastIndexOf("/"); if (lastIndex != -1) { baseRef += this.relativePart.substring(0, lastIndex); } int rootLength = getDirectoryUri().length(); if (this.getBaseName() != null) { String filePath; for (Reference ref : getVariantsReferences()) { // Add the new variant to the result list Response contextResponse = getRepresentation(ref.toString()); if (contextResponse.getStatus().isSuccess() && (contextResponse.getEntity() != null)) { filePath = ref.toString(false, false).substring(rootLength); Representation rep = contextResponse.getEntity(); if (filePath.startsWith("/")) { rep.setLocationRef(baseRef + filePath); } else { rep.setLocationRef(baseRef + "/" + filePath); } resultSet.add(rep); } } } if (!resultSet.isEmpty()) { result = new ArrayList<Variant>(resultSet); } if (resultSet.isEmpty()) { if (isDirectoryTarget() && getDirectory().isListingAllowed()) { ReferenceFileList userList = new ReferenceFileList(this.getDirectoryContent().size()); // Set the list identifier userList.setIdentifier(baseRef); userList.setRegexp(directory.getRegexp()); SortedSet<Reference> sortedSet = new TreeSet<Reference>(getDirectory().getComparator()); sortedSet.addAll(this.getDirectoryContent()); for (Reference ref : sortedSet) { String filePart = ref.toString(false, false).substring(rootLength); StringBuilder filePath = new StringBuilder(); if ((!baseRef.endsWith("/")) && (!filePart.startsWith("/"))) { filePath.append('/'); } filePath.append(filePart); // SITOOLS2 - ReferenceFileList = reference and File String path = ref.getPath(); String repertoire = Reference.decode(path); File file = new File(repertoire); userList.addFileReference(baseRef + filePath, file); // SITOOLS2 instead of simple reference : userList.add(baseRef + filePath); } List<Variant> list = getDirectory().getIndexVariants(userList); for (Variant variant : list) { if (result == null) { result = new ArrayList<Variant>(); } result.add(getDirectory().getIndexRepresentation(variant, userList)); } } } } else if (isFileTarget() && (this.fileContent != null)) { // Sets the location of the target representation. if (getOriginalRef() != null) { this.fileContent.setLocationRef(getRequest().getOriginalRef()); } else { this.fileContent.setLocationRef(getReference()); } result = new ArrayList<Variant>(); result.add(this.fileContent); } this.variantsGet = result; } } return result; }
From source file:org.wso2.carbon.apimgt.impl.AbstractAPIManager.java
public Set<API> getSubscriberAPIs(Subscriber subscriber) throws APIManagementException { SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator()); Set<SubscribedAPI> subscribedAPIs = apiMgtDAO.getSubscribedAPIs(subscriber, null); boolean isTenantFlowStarted = false; try {//from ww w .ja va 2 s . c o m if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { isTenantFlowStarted = true; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } for (SubscribedAPI subscribedAPI : subscribedAPIs) { String apiPath = APIUtil.getAPIPath(subscribedAPI.getApiId()); Resource resource; try { resource = registry.get(apiPath); GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY); GenericArtifact artifact = artifactManager.getGenericArtifact(resource.getUUID()); API api = APIUtil.getAPI(artifact, registry); if (api != null) { apiSortedSet.add(api); } } catch (RegistryException e) { handleException("Failed to get APIs for subscriber: " + subscriber.getName(), e); } } } finally { if (isTenantFlowStarted) { PrivilegedCarbonContext.endTenantFlow(); } } return apiSortedSet; }
From source file:io.wcm.handler.media.format.impl.MediaFormatHandlerImpl.java
/** * Detect all matching media formats.// www .j a v a2s. co m * @param extension File extension * @param fileSize File size * @param width Image width (or 0 if not image) * @param height Image height (or 0 if not image) * @return Matching media formats sorted by their ranking or an empty list if no matching format was found */ @Override public SortedSet<MediaFormat> detectMediaFormats(String extension, long fileSize, long width, long height) { // sort media formats by ranking SortedSet<MediaFormat> matchingFormats = new TreeSet<>(new MediaFormatRankingComparator()); for (MediaFormat mediaFormat : getMediaFormats()) { // skip media formats with negative ranking if (mediaFormat.getRanking() < 0) { continue; } // check extension boolean extensionMatch = false; if (mediaFormat.getExtensions() != null) { for (String ext : mediaFormat.getExtensions()) { if (StringUtils.equalsIgnoreCase(ext, extension)) { extensionMatch = true; break; } } } else { extensionMatch = true; } // check file size boolean fileSizeMatch = false; if (mediaFormat.getFileSizeMax() > 0) { fileSizeMatch = (fileSize <= mediaFormat.getFileSizeMax()); } else { fileSizeMatch = true; } // width/height match boolean dimensionMatch = false; if (width > 0 && height > 0) { dimensionMatch = (mediaFormat.getEffectiveMinWidth() == 0 || width >= mediaFormat.getEffectiveMinWidth()) && (mediaFormat.getEffectiveMaxWidth() == 0 || width <= mediaFormat.getEffectiveMaxWidth()) && (mediaFormat.getEffectiveMinHeight() == 0 || height >= mediaFormat.getEffectiveMinHeight()) && (mediaFormat.getEffectiveMaxHeight() == 0 || height <= mediaFormat.getEffectiveMaxHeight()); } else { dimensionMatch = true; } boolean ratioMatch = false; if (mediaFormat.hasRatio() && width > 0 && height > 0) { double formatRatio = mediaFormat.getRatio(); double ratio = (double) width / height; ratioMatch = (ratio > formatRatio - RATIO_TOLERANCE) && (ratio < formatRatio + RATIO_TOLERANCE); } else { ratioMatch = true; } if (extensionMatch && fileSizeMatch && dimensionMatch && ratioMatch) { matchingFormats.add(mediaFormat); } } return matchingFormats; }
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
String toJsonZips(ParentChild data, String zip, Map<String, ParentChild> pcs) throws JSONException { String zip2 = zip.substring(3); SortedSet<String> keys = new TreeSet<String>(); boolean start = true; StringBuilder ret = new StringBuilder("{\"zip1\":\""); ret.append(data.getParents().getFirst()); ret.append("\",\"zip2\":\""); ret.append(zip2);//from www .jav a 2 s . c o m ret.append("\",\"zips\":["); for (String json : data.getChildren()) { JSONObject jo = new JSONObject(json); if (!jo.optString("zip2", "").equals(zip2)) { continue; } keys.add(jo.optString("key", "")); } for (String key : keys) { try { ParentChild zips = pcs.get(key); City city = City.fromJson(zips.getParents().getLast()); for (String json : zips.getChildren()) { JSONObject jo = new JSONObject(json); if (!jo.optString("code", "").equals(zip)) { continue; } if (start) { start = false; } else { ret.append(","); } jo.put("x0402", city.getCode()); jo.put("city", city.getName()); jo.remove("add1Yomi"); jo.remove("add2Yomi"); jo.remove("corpYomi"); ret.append(jo.toString()); } } catch (JDOObjectNotFoundException e) { } } return ret.append("]}").toString(); }
From source file:BayesianAnalyzer.java
/** * Returns a SortedSet of TokenProbabilityStrength built from the * Corpus and the tokens passed in the "tokens" Set. * The ordering is from the highest strength to the lowest strength. * * @param tokens//from w w w.j a va 2 s. c o m * @param workCorpus * @return SortedSet of TokenProbabilityStrength objects. */ private SortedSet getTokenProbabilityStrengths(Set tokens, Map workCorpus) { //Convert to a SortedSet of token probability strengths. SortedSet tokenProbabilityStrengths = new TreeSet(); Iterator i = tokens.iterator(); while (i.hasNext()) { TokenProbabilityStrength tps = new TokenProbabilityStrength(); tps.token = (String) i.next(); if (workCorpus.containsKey(tps.token)) { tps.strength = Math.abs(0.5 - ((Double) workCorpus.get(tps.token)).doubleValue()); } else { //This token has never been seen before, //we'll give it initially the default probability. Double corpusProbability = new Double(DEFAULT_TOKEN_PROBABILITY); tps.strength = Math.abs(0.5 - DEFAULT_TOKEN_PROBABILITY); boolean isTokenDegeneratedFound = false; Collection degeneratedTokens = buildDegenerated(tps.token); Iterator iDegenerated = degeneratedTokens.iterator(); String tokenDegenerated = null; double strengthDegenerated; while (iDegenerated.hasNext()) { tokenDegenerated = (String) iDegenerated.next(); if (workCorpus.containsKey(tokenDegenerated)) { Double probabilityTemp = (Double) workCorpus.get(tokenDegenerated); strengthDegenerated = Math.abs(0.5 - probabilityTemp.doubleValue()); if (strengthDegenerated > tps.strength) { isTokenDegeneratedFound = true; tps.strength = strengthDegenerated; corpusProbability = probabilityTemp; } } } // to reduce memory usage, put in the corpus only if the probability is different from (stronger than) the default if (isTokenDegeneratedFound) { synchronized (workCorpus) { workCorpus.put(tps.token, corpusProbability); } } } tokenProbabilityStrengths.add(tps); } return tokenProbabilityStrengths; }
From source file:com.android.mms.transaction.MessagingNotification.java
private static final void addSmsNotificationInfos(Context context, Set<Long> threads, SortedSet<NotificationInfo> notificationSet) { ContentResolver resolver = context.getContentResolver(); Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION, NEW_INCOMING_SM_CONSTRAINT, null, Sms.DATE + " desc"); if (cursor == null) { return;/* ww w. j av a 2s .co m*/ } try { while (cursor.moveToNext()) { String address = cursor.getString(COLUMN_SMS_ADDRESS); if (MessageUtils.isWapPushNumber(address)) { String[] mAddresses = address.split(":"); address = mAddresses[context.getResources().getInteger(R.integer.wap_push_address_index)]; } Contact contact = Contact.get(address, false); if (contact.getSendToVoicemail()) { // don't notify, skip this one continue; } String message = cursor.getString(COLUMN_SMS_BODY); long threadId = cursor.getLong(COLUMN_SMS_THREAD_ID); long timeMillis = cursor.getLong(COLUMN_SMS_DATE); int subId = cursor.getInt(COLUMN_SMS_SUB_ID); String msgId = cursor.getString(COLUMN_SMS_ID); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "addSmsNotificationInfos: count=" + cursor.getCount() + ", addr=" + address + ", thread_id=" + threadId); } NotificationInfo info = getNewMessageNotificationInfo(context, true /* isSms */, address, message, null /* subject */, threadId, subId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT); if (MessageUtils.isMailboxMode()) { info.mClickIntent.setData(Uri.withAppendedPath(Sms.CONTENT_URI, msgId)); } notificationSet.add(info); threads.add(threadId); threads.add(cursor.getLong(COLUMN_SMS_THREAD_ID)); } } finally { cursor.close(); } }