Java Code Examples for java.util.SortedSet.add()

The following are Jave code examples for showing how to use add() of the java.util.SortedSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: scala-lang   File: AbsSorter.java   View Source Code Vote up 6 votes
private SortedSet<R> getMore$(D prev, int limit, boolean minFirst, boolean drop) {
    final SortedSet<R> result;
    if (minFirst) {
        result = new TreeSet<>(comparatorIncrement);
    } else {
        result = new TreeSet<>(comparatorDecrement);
    }
    R range = prev == null ? null : create(prev, prev);
    int count = 0;
    synchronized (this) { // 必须线程安全,否则rp参数可能无法被正确评估。
        while (count < limit) {
            range = getSerial$(range, limit - count, minFirst);
            if (range == null) break;
            else if (drop) drop(range);
            result.add(range);
            count += range.delta() + 1;
        }
    }
    return result;
}
 
Example 2
Project: Apriori   File: FrequentItemSetsTest.java   View Source Code Vote up 6 votes
/**
 * Tests, if all class members are set correctly by the constructor.
 */
@Test
public final void testConstructor() {
    SortedSet<ItemSet<NamedItem>> frequentItemSets = new FrequentItemSets<>(
            Comparator.reverseOrder());
    ItemSet<NamedItem> itemSet1 = new ItemSet<>();
    itemSet1.add(new NamedItem("a"));
    itemSet1.setSupport(0.5);
    ItemSet<NamedItem> itemSet2 = new ItemSet<>();
    itemSet2.add(new NamedItem("b"));
    itemSet2.setSupport(0.6);
    frequentItemSets.add(itemSet1);
    frequentItemSets.add(itemSet2);
    assertEquals(2, frequentItemSets.size());
    assertEquals(itemSet2, frequentItemSets.first());
    assertEquals(itemSet1, frequentItemSets.last());
}
 
Example 3
Project: syndesis   File: JsonHandlingITCase.java   View Source Code Vote up 6 votes
@Test
public void valuesGivenInJsonShouldBeTrimmedToNull() {
    final SortedSet<String> tags = new TreeSet<>();
    tags.add("");
    tags.add(" tag");
    tags.add("\tTaggy McTagface\t");

    final Integration integration = new Integration.Builder().id(id).name("  some-name\t").description("")
        .tags(tags).desiredStatus(Integration.Status.Draft).build();
    post("/api/v1/integrations", integration, Integration.class);

    final ResponseEntity<Integration> result = get("/api/v1/integrations/" + id, Integration.class);
    final Integration created = result.getBody();
    assertThat(created.getName()).isEqualTo("some-name");
    assertThat(created.getDescription()).isNotPresent();
    assertThat(created.getTags()).containsExactly("Taggy McTagface", "tag");

}
 
Example 4
Project: Equella   File: Version.java   View Source Code Vote up 6 votes
public SortedSet<WebVersion> getVersions()
{
	final SortedSet<WebVersion> versions = new TreeSet<WebVersion>(Utils.VERSION_COMPARATOR);

	final File upgradeFolder = config.getUpdatesDir();
	if( upgradeFolder.exists() )
	{
		for( String file : upgradeFolder.list() )
		{
			if( file != null && Utils.VERSION_EXTRACT.matcher(file).matches() )
			{
				versions.add(getWebVersionFromFile(file));
			}
		}
	}
	else
	{
		throw new RuntimeException("No upgrades folder found");
	}

	return versions;
}
 
Example 5
Project: logistimo-web-service   File: ReplenishmentReportService.java   View Source Code Vote up 6 votes
@Override
public List<ReportChartModel> buildReportsData(String data, ReportCompareField compareField,
                                               Map<String, String> filters)
    throws Exception {
  List<Report> reports = constructReportList(data);
  if (reports != null) {
    List<ReportChartModel> reportData = new ArrayList<>(reports.size());
    SortedSet<String> tSet = new TreeSet<>();
    for (Report report : reports) {
      ReportChartModel m = new ReportChartModel();
      m.label = getReportLabel(filters, report);
      tSet.add(m.label);
      m.value = getReportValues(report, compareField);
      reportData.add(m);
    }
    if (reportData.size() > 0) {
      return fillChartData(reportData, tSet, filters);
    } else {
      return reportData;
    }
  }
  return null;
}
 
Example 6
Project: mobile-store   File: IndexV1UpdaterTest.java   View Source Code Vote up 5 votes
private Set<String> getFields(Object instance) {
    SortedSet<String> output = new TreeSet<>();

    //determine fields declared in this class only (no fields of superclass)
    Field[] fields = instance.getClass().getDeclaredFields();

    //print field names paired with their values
    for (Field field : fields) {
        output.add(field.getName());
    }

    return output;
}
 
Example 7
Project: lams   File: EmailProgressAction.java   View Source Code Vote up 5 votes
/**
    * Gets learners or monitors of the lesson and organisation containing it.
    * 
    * @throws SchedulerException
    */
   public ActionForward getEmailProgressDates(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws IOException, JSONException, SchedulerException {
Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID);
if (!getSecurityService().isLessonMonitor(lessonId, getCurrentUser().getUserID(), "get class members", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson");
    return null;
}

HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);

JSONObject responseJSON = new JSONObject();
JSONArray datesJSON = new JSONArray();

// find all the current dates set up to send the emails
Scheduler scheduler = getScheduler();
String triggerPrefix = getTriggerPrefix(lessonId);
SortedSet<Date> currentDatesSet = new TreeSet<Date>();
Set<TriggerKey> triggerKeys = scheduler
	.getTriggerKeys(GroupMatcher.triggerGroupEquals(Scheduler.DEFAULT_GROUP));
for (TriggerKey triggerKey : triggerKeys) {
    String triggerName = triggerKey.getName();
    if (triggerName.startsWith(triggerPrefix)) {
	Trigger trigger = scheduler.getTrigger(triggerKey);
	JobDetail jobDetail = scheduler.getJobDetail(trigger.getJobKey());
	JobDataMap jobDataMap = jobDetail.getJobDataMap();

	// get only the trigger for the current lesson

	Object jobLessonId = jobDataMap.get(AttributeNames.PARAM_LESSON_ID);
	if (lessonId.equals(jobLessonId)) {

	    Date triggerDate = trigger.getNextFireTime();
	    currentDatesSet.add(triggerDate);
	}
    }
}

for (Date date : currentDatesSet) {
    datesJSON.put(createDateJSON(request.getLocale(), user, date, null));
}
responseJSON.put("dates", datesJSON);

response.setContentType("application/json;charset=utf-8");
response.getWriter().write(responseJSON.toString());
return null;
   }
 
Example 8
Project: monarch   File: PdxInstanceImpl.java   View Source Code Vote up 5 votes
/**
 * Any fields that are in otherFields but not in myFields are added to myFields as defaults. When
 * adding fields they are inserted in the natural sort order. Note: myFields may be modified by
 * this call.
 */
private static void addDefaultFields(SortedSet<PdxField> myFields,
    SortedSet<PdxField> otherFields) {
  for (PdxField f : otherFields) {
    if (!myFields.contains(f)) {
      myFields.add(new DefaultPdxField(f));
    }
  }
}
 
Example 9
Project: athena   File: Icmp6CodeCompleter.java   View Source Code Vote up 5 votes
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
    // Delegate string completer
    StringsCompleter delegate = new StringsCompleter();
    SortedSet<String> strings = delegate.getStrings();

    for (Icmp6Code code : Icmp6Code.values()) {
        strings.add(code.toString());
    }

    // Now let the completer do the work for figuring out what to offer.
    return delegate.complete(buffer, cursor, candidates);
}
 
Example 10
Project: microbean-helm   File: TestRequirements.java   View Source Code Vote up 5 votes
private final void verifyRequirementsEnabled(final String tags, final String... expectedChartNames) {
  assertNotNull(tags);
  assertNotNull(expectedChartNames);
  final Config.Builder configBuilder = Config.newBuilder();
  assertNotNull(configBuilder);
  configBuilder.setRaw(tags);
  final SortedSet<String> expectations = new TreeSet<>();
  for (final String expectation : expectedChartNames) {
    assertNotNull(expectation);
    expectations.add(expectation);
  }
  verifyRequirementsEnabled(configBuilder, expectations);
}
 
Example 11
Project: lams   File: AuthoringAction.java   View Source Code Vote up 5 votes
/**
    * Ajax call, will add one more input line for new resource item instruction.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   private ActionForward initOverallFeedback(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {
String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
AssessmentForm assessmentForm = (AssessmentForm) sessionMap.get(AssessmentConstants.ATTR_ASSESSMENT_FORM);
Assessment assessment = assessmentForm.getAssessment();

// initial Overall feedbacks list
SortedSet<AssessmentOverallFeedback> overallFeedbackList = new TreeSet<AssessmentOverallFeedback>(
	new SequencableComparator());
if (!assessment.getOverallFeedbacks().isEmpty()) {
    overallFeedbackList.addAll(assessment.getOverallFeedbacks());
} else {
    for (int i = 1; i <= AssessmentConstants.INITIAL_OVERALL_FEEDBACK_NUMBER; i++) {
	AssessmentOverallFeedback overallFeedback = new AssessmentOverallFeedback();
	if (i == 1) {
	    overallFeedback.setGradeBoundary(100);
	}
	overallFeedback.setSequenceId(i);
	overallFeedbackList.add(overallFeedback);
    }
}

request.setAttribute(AssessmentConstants.ATTR_OVERALL_FEEDBACK_LIST, overallFeedbackList);
return mapping.findForward(AssessmentConstants.SUCCESS);
   }
 
Example 12
Project: scott-eu   File: ServiceProviderCatalogSingleton.java   View Source Code Vote up 5 votes
private static SortedSet<URI> getServiceProviderDomains(final ServiceProvider serviceProvider)
{
    final SortedSet<URI> domains = new TreeSet<URI>();

    if (serviceProvider!=null) {
        final Service [] services = serviceProvider.getServices();
        for (final Service service : services)
        {
            final URI domain = service.getDomain();

            domains.add(domain);
        }
    }
    return domains;
}
 
Example 13
Project: googles-monorepo-demo   File: SafeTreeSetTest.java   View Source Code Vote up 5 votes
@GwtIncompatible // SerializableTester
public void testSeveral_serialization() {
  SortedSet<String> set = new SafeTreeSet<String>();
  set.add("a");
  set.add("b");
  set.add("c");
  SortedSet<String> copy = SerializableTester.reserializeAndAssert(set);
  assertEquals(set.comparator(), copy.comparator());
}
 
Example 14
Project: lams   File: AuthoringConditionAction.java   View Source Code Vote up 5 votes
/**
    * Extract form content to ForumCondition.
    *
    * @param request
    * @param form
    * @throws Exception
    */
   private void extractFormToForumCondition(HttpServletRequest request, ForumConditionForm form) throws Exception {

SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(form.getSessionMapID());
// check whether it is "edit(old item)" or "add(new item)"
SortedSet<ForumCondition> conditionSet = getForumConditionSet(sessionMap);
int orderId = form.getOrderId();
ForumCondition condition = null;

if (orderId == -1) { // add
    String properConditionName = getForumService().createTextSearchConditionName(conditionSet);
    condition = form.extractCondition();
    condition.setName(properConditionName);
    int maxOrderId = 1;
    if (conditionSet != null && conditionSet.size() > 0) {
	ForumCondition last = conditionSet.last();
	maxOrderId = last.getOrderId() + 1;
    }
    condition.setOrderId(maxOrderId);
    conditionSet.add(condition);
} else { // edit
    List<ForumCondition> conditionList = new ArrayList<ForumCondition>(conditionSet);
    condition = conditionList.get(orderId - 1);
    form.extractCondition(condition);
}

Long[] selectedItems = form.getSelectedItems();
Set<Message> conditionTopics = new TreeSet<Message>(new ConditionTopicComparator());
Set<MessageDTO> messageDTOs = getMessageDTOList(sessionMap);

for (Long selectedItem : selectedItems) {
    for (MessageDTO messageDTO : messageDTOs) {
	Message topic = messageDTO.getMessage();
	if (selectedItem.equals(topic.getCreated().getTime())) {
	    conditionTopics.add(topic);
	}
    }
}
condition.setTopics(conditionTopics);
   }
 
Example 15
Project: lams   File: AuthoringAction.java   View Source Code Vote up 4 votes
/**
    * Remove assessment question from HttpSession list and update page display. As authoring rule, all persist only
    * happen when user submit whole page. So this remove is just impact HttpSession values.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   private ActionForward addQuestionReference(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {
// get back sessionMAP
String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
updateQuestionReferencesGrades(request, sessionMap, false);

SortedSet<QuestionReference> references = getQuestionReferences(sessionMap);
int questionIdx = NumberUtils.toInt(request.getParameter(AssessmentConstants.PARAM_QUESTION_INDEX), -1);

// set SequenceId
QuestionReference reference = new QuestionReference();
int maxSeq = 1;
if ((references != null) && (references.size() > 0)) {
    QuestionReference last = references.last();
    maxSeq = last.getSequenceId() + 1;
}
reference.setSequenceId(maxSeq);

// set isRandomQuestion
boolean isRandomQuestion = (questionIdx == -1);
reference.setRandomQuestion(isRandomQuestion);

if (isRandomQuestion) {
    reference.setDefaultGrade(1);
} else {
    SortedSet<AssessmentQuestion> questionList = getQuestionList(sessionMap);
    AssessmentQuestion question = null;
    for (AssessmentQuestion questionFromList : questionList) {
	if (questionFromList.getSequenceId() == questionIdx) {
	    question = questionFromList;
	    break;
	}
    }
    reference.setQuestion(question);

    reference.setDefaultGrade(question.getDefaultGrade());
}
references.add(reference);

reinitializeAvailableQuestions(sessionMap);

request.setAttribute(AssessmentConstants.ATTR_SESSION_MAP_ID, sessionMapID);
return mapping.findForward(AssessmentConstants.SUCCESS);
   }
 
Example 16
Project: lams   File: AuthoringTaskListConditionAction.java   View Source Code Vote up 4 votes
/**
    * Extract form content to taskListContent.
    *
    * @param request
    * @param form
    * @throws TaskListException
    */
   private void extractFormToTaskListCondition(HttpServletRequest request, TaskListConditionForm form)
    throws Exception {
/*
 * BE CAREFUL: This method will copy necessary info from request form to a old or new TaskListItem instance. It
 * gets all info EXCEPT TaskListItem.createDate and TaskListItem.createBy, which need be set when persisting
 * this taskList item.
 */

SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(form.getSessionMapID());
// check whether it is "edit(old item)" or "add(new item)"
SortedSet<TaskListCondition> conditionList = getTaskListConditionList(sessionMap);
int sequenceId = NumberUtils.stringToInt(form.getSequenceId(), -1);
TaskListCondition condition = null;

if (sequenceId == -1) { // add
    condition = new TaskListCondition();
    int maxSeq = 1;
    if (conditionList != null && conditionList.size() > 0) {
	TaskListCondition last = conditionList.last();
	maxSeq = last.getSequenceId() + 1;
    }
    condition.setSequenceId(maxSeq);
    conditionList.add(condition);
} else { // edit
    List<TaskListCondition> rList = new ArrayList<TaskListCondition>(conditionList);
    condition = rList.get(sequenceId);
}

condition.setName(form.getName());

String[] selectedItems = form.getSelectedItems();
SortedSet<TaskListItem> itemList = getTaskListItemList(sessionMap);
SortedSet<TaskListItem> conditionItemList = new TreeSet<TaskListItem>(new TaskListItemComparator());

for (String selectedItem : selectedItems) {
    for (TaskListItem item : itemList) {
	if (selectedItem.equals((new Integer(item.getSequenceId())).toString())) {
	    conditionItemList.add(item);
	}
    }
}
condition.setTaskListItems(conditionItemList);

   }
 
Example 17
Project: ZooKeeper   File: WriteLock.java   View Source Code Vote up 4 votes
/**
 * the command that is run and retried for actually 
 * obtaining the lock
 * @return if the command was successful or not
 */
public boolean execute() throws KeeperException, InterruptedException {
    do {
        if (id == null) {
            long sessionId = zookeeper.getSessionId();
            String prefix = "x-" + sessionId + "-";
            // lets try look up the current ID if we failed 
            // in the middle of creating the znode
            findPrefixInChildren(prefix, zookeeper, dir);
            idName = new ZNodeName(id);
        }
        if (id != null) {
            List<String> names = zookeeper.getChildren(dir, false);
            if (names.isEmpty()) {
                LOG.warn("No children in: " + dir + " when we've just " +
                "created one! Lets recreate it...");
                // lets force the recreation of the id
                id = null;
            } else {
                // lets sort them explicitly (though they do seem to come back in order ususally :)
                SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
                for (String name : names) {
                    sortedNames.add(new ZNodeName(dir + "/" + name));
                }
                ownerId = sortedNames.first().getName();
                SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
                if (!lessThanMe.isEmpty()) {
                    ZNodeName lastChildName = lessThanMe.last();
                    lastChildId = lastChildName.getName();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("watching less than me node: " + lastChildId);
                    }
                    Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
                    if (stat != null) {
                        return Boolean.FALSE;
                    } else {
                        LOG.warn("Could not find the" +
                        		" stats for less than me: " + lastChildName.getName());
                    }
                } else {
                    if (isOwner()) {
                        if (callback != null) {
                            callback.lockAcquired();
                        }
                        return Boolean.TRUE;
                    }
                }
            }
        }
    }
    while (id == null);
    return Boolean.FALSE;
}
 
Example 18
Project: lams   File: AuthoringAction.java   View Source Code Vote up 4 votes
/**
    * Extract web from content to commonCartridge item.
    *
    * @param request
    * @param itemForm
    * @throws CommonCartridgeApplicationException
    */
   private void extractFormToCommonCartridgeItem(HttpServletRequest request, CommonCartridgeItemForm itemForm)
    throws Exception {
/*
 * BE CAREFUL: This method will copy nessary info from request form to a old or new CommonCartridgeItem
 * instance. It gets all info EXCEPT CommonCartridgeItem.createDate and CommonCartridgeItem.createBy, which need
 * be set when persisting this commonCartridge item.
 */

SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(itemForm.getSessionMapID());
// check whether it is "edit(old item)" or "add(new item)"
SortedSet<CommonCartridgeItem> commonCartridgeList = getCommonCartridgeItemList(sessionMap);
int itemIdx = NumberUtils.stringToInt(itemForm.getItemIndex(), -1);
CommonCartridgeItem item = null;

if (itemIdx == -1) { // add
    item = new CommonCartridgeItem();
    item.setCreateDate(new Timestamp(new Date().getTime()));
    commonCartridgeList.add(item);
} else { // edit
    List<CommonCartridgeItem> rList = new ArrayList<CommonCartridgeItem>(commonCartridgeList);
    item = rList.get(itemIdx);
}
short type = itemForm.getItemType();
item.setType(itemForm.getItemType());

item.setTitle(itemForm.getTitle());
item.setCreateByAuthor(true);
item.setHide(false);

if (type == CommonCartridgeConstants.RESOURCE_TYPE_BASIC_LTI) {

    if (StringUtils.isBlank(item.getLaunchUrl()) && StringUtils.isNotBlank(item.getSecureLaunchUrl())) {
	item.setSecureLaunchUrl(itemForm.getUrl());
    } else {
	item.setLaunchUrl(itemForm.getUrl());
    }

    item.setKey(itemForm.getKey());
    item.setSecret(itemForm.getSecret());
    item.setButtonText(itemForm.getButtonText());
    item.setOpenUrlNewWindow(itemForm.isOpenUrlNewWindow());
    item.setFrameHeight(itemForm.getFrameHeight());
    item.setCustomStr(itemForm.getCustomStr());
}
// if(type == CommonCartridgeConstants.RESOURCE_TYPE_WEBSITE
// ||itemForm.getItemType() == CommonCartridgeConstants.RESOURCE_TYPE_LEARNING_OBJECT){
item.setDescription(itemForm.getDescription());
// }

   }
 
Example 19
Project: n4js   File: N4JSResourceDescription.java   View Source Code Vote up 4 votes
@Override
public Iterable<QualifiedName> getImportedNames() {
	if (null == lazyImportedNames) {
		synchronized (this) {
			if (null == lazyImportedNames) {
				// get imported names collected during global scoping
				// the scope provider registers every request in scoping so that by this
				// also all names are collected that cannot be resolved
				Iterable<QualifiedName> superImportedNames = super.getImportedNames();
				// use sorted set to ensure order of items
				final SortedSet<QualifiedName> importedNames;
				if (superImportedNames != null) {
					importedNames = Sets.newTreeSet(superImportedNames);
				} else {
					importedNames = Sets.<QualifiedName> newTreeSet();
				}
				// import our own module name to get a proper change notification
				Resource resource = getResource();
				List<EObject> contents = resource.getContents();
				if (contents.size() > 1) {
					TModule module = (TModule) contents.get(1);
					importedNames.add(qualifiedNameProvider.getFullyQualifiedName(module));
				}
				final Set<EObject> crossRefTypes = Sets.newHashSet();
				IAcceptor<EObject> acceptor = getCrossRefTypeAcceptor(crossRefTypes);
				crossReferenceComputer.computeCrossRefs(resource, acceptor);
				for (EObject type : crossRefTypes) {
					if (type instanceof Type) {
						handleType(importedNames, type);
					} else if (type instanceof TVariable) {
						handleTVariable(importedNames, (TVariable) type);
					} else if (type instanceof TEnumLiteral) {
						handleTEnumLiteral(importedNames, (TEnumLiteral) type);
					}
				}
				this.lazyImportedNames = importedNames;
			}
		}
	}

	return lazyImportedNames;
}
 
Example 20
Project: jmt   File: BlockingStationPanel.java   View Source Code Vote up 3 votes
/**
 * Returns an appropriate editor for the cell specified by
 * <code>row</code> and <code>column</code>. If the
 * <code>TableColumn</code> for this column has a non-null editor,
 * returns that.  If not, finds the class of the data in this
 * column (using <code>getColumnClass</code>)
 * and returns the default editor for this type of data.
 * <p/>
 * <b>Note:</b>
 * Throughout the table package, the internal implementations always
 * use this method to provide editors so that this default behavior
 * can be safely overridden by a subclass.
 *
 * @param row    the row of the cell to edit, where 0 is the first row
 * @param column the column of the cell to edit,
 *               where 0 is the first column
 * @return the editor for this cell;
 *         if <code>null</code> return the default editor for
 *         this type of cell
 * @see javax.swing.DefaultCellEditor
 */
@Override
public TableCellEditor getCellEditor(int row, int column) {
	if (column == 1) {
		return new ButtonCellEditor(delete);
	} else {
		// Builds an ordered array with station keys that can be added and current one
		SortedSet<Object> tmp = new TreeSet<Object>(bd.getBlockableStationKeys());
		tmp.add(stations.get(row));
		return comboFactory.getEditor(tmp.toArray());
	}
}