Java Code Examples for java.util.TreeSet

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: GMMImpl.java

  32 
vote

public ID[] getMemberIDs(ID exclude){
  TreeSet newSet=null;
  if (exclude != null) {
    newSet=(TreeSet)mySet.clone();
    newSet.remove(new Member(exclude));
  }
 else {
    newSet=mySet;
  }
  final ID ids[]=new ID[newSet.size()];
  final Iterator iter=newSet.iterator();
  int j=0;
  while (iter.hasNext()) {
    ids[j++]=((Member)iter.next()).getID();
  }
  return ids;
}
 

Example 2

From project Application-Builder, under directory /src/main/java/org/silverpeas/version/.

Source file: JobBoxInfo.java

  31 
vote

private void setPackages(Map _packages){
  myPackages=new TreeSet();
  Iterator iPackage=_packages.values().iterator();
  PackageInfo info=null;
  while (iPackage.hasNext()) {
    info=(PackageInfo)iPackage.next();
    if (info.getBoxName().equals(getName())) {
      myPackages.add(info);
    }
  }
}
 

Example 3

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/monitor/statevariable/.

Source file: MonitorHandlerStateVar.java

  31 
vote

private void fireStatusChange(){
  Set union=new TreeSet(previousStateVarEnabled);
  union.addAll(listStateVarEnabled);
  Iterator it=union.iterator();
  String variableId;
  while (it.hasNext()) {
    variableId=(String)it.next();
    if ((previousStateVarEnabled.contains(variableId)) && (!listStateVarEnabled.contains(variableId)))     firerVariableStatus(variableId,false);
 else {
      if ((!previousStateVarEnabled.contains(variableId)) && (listStateVarEnabled.contains(variableId)))       firerVariableStatus(variableId,true);
    }
  }
}
 

Example 4

From project CIShell, under directory /testing/org.cishell.testing.convertertester.core.new/src/org/cishell/testing/convertertester/core/converter/graph/.

Source file: ConverterGraph.java

  31 
vote

public File asNWB(){
  Map nodes=assembleNodesSet();
  TreeSet edges=assembleEdges(nodes);
  File f=getTempFile();
  try {
    BufferedWriter writer=new BufferedWriter(new FileWriter(f));
    writeNodes(writer,nodes);
    writeEdges(writer,edges);
  }
 catch (  IOException e) {
    System.out.println("Blurt!");
    this.log.log(LogService.LOG_ERROR,"IOException while creating converter graph file",e);
  }
  return f;
}
 

Example 5

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/optimizer/.

Source file: Shrinker.java

  30 
vote

static void optimize(final File f,final File d,final NameMapping mapping) throws IOException {
  if (f.isDirectory()) {
    File[] files=f.listFiles();
    for (int i=0; i < files.length; ++i) {
      optimize(files[i],d,mapping);
    }
  }
 else   if (f.getName().endsWith(".class")) {
    ConstantPool cp=new ConstantPool();
    ClassReader cr=new ClassReader(new FileInputStream(f));
    ClassWriter cw=new ClassWriter(0);
    ClassConstantsCollector ccc=new ClassConstantsCollector(cw,cp);
    ClassOptimizer co=new ClassOptimizer(ccc,mapping);
    cr.accept(co,ClassReader.SKIP_DEBUG);
    Set constants=new TreeSet(new ConstantComparator());
    constants.addAll(cp.values());
    cr=new ClassReader(cw.toByteArray());
    cw=new ClassWriter(0);
    Iterator i=constants.iterator();
    while (i.hasNext()) {
      Constant c=(Constant)i.next();
      c.write(cw);
    }
    cr.accept(cw,ClassReader.SKIP_DEBUG);
    String n=mapping.map(co.getClassName());
    File g=new File(d,n + ".class");
    if (!g.exists() || g.lastModified() < f.lastModified()) {
      g.getParentFile().mkdirs();
      OutputStream os=new FileOutputStream(g);
      os.write(cw.toByteArray());
      os.close();
    }
  }
}
 

Example 6

From project CircDesigNA, under directory /src/circdesigna/abstractDesigner/.

Source file: InfiniteResourceTournament.java

  30 
vote

public void runBlockIteration_(CircDesigNA runner,double endThreshold){
  TreeSet<T> blockIterationLevel=new TreeSet();
  for (int k=0; k < populationSize; k++) {
    blockIterationLevel.add(population_mutable[k]);
  }
  blockItr:   for (int itrCount=0; ; itrCount++) {
    Iterator<T> qb=blockIterationLevel.iterator();
    while (qb.hasNext()) {
      T q=qb.next();
      boolean mutationSuccessful=SingleDesigner.mutateAndTestAndBackup(q);
      if (mutationSuccessful) {
        double newScore=SingleDesigner.getOverallScore(q);
        if (newScore <= endThreshold) {
          break blockItr;
        }
        qb.remove();
      }
 else {
      }
      if (runner != null && runner.abort) {
        break;
      }
    }
    setProgress((itrCount + 1),param_iterationShortcut);
    if (blockIterationLevel.size() < populationSize * .5) {
      break;
    }
    if (param_iterationShortcut >= 0) {
      if (itrCount > param_iterationShortcut && populationSize - blockIterationLevel.size() > 0) {
        System.err.println("Breaking iteration early.");
        break;
      }
    }
  }
  tournamentSelect(numElites);
}
 

Example 7

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: TableFilterCombo.java

  30 
vote

private DefaultComboBoxModel buildSortedModel(TableModel model){
  Set set=null;
  if (getComparator() != null) {
    set=new TreeSet(getComparator());
  }
 else {
    set=new TreeSet();
  }
  boolean modelContainsNullValue=false;
  for (int i=0; i < model.getRowCount(); i++) {
    Object obj=model.getValueAt(i,column);
    if (obj == null) {
      modelContainsNullValue=true;
    }
 else {
      set.add(obj);
    }
  }
  DefaultComboBoxModel comboModel=new DefaultComboBoxModel(set.toArray());
  if (modelContainsNullValue) {
    comboModel.insertElementAt(NULL_FILTER,0);
  }
  return comboModel;
}
 

Example 8

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/chartparser/.

Source file: FeatureMap.java

  29 
vote

public String toString(){
  String s="";
  Set<String> featureKeys=features.keySet();
  if (featureKeys.size() > 0)   s+="(";
  for (  String feature : new TreeSet<String>(features.keySet())) {
    StringRef sr=features.get(feature);
    s+=feature + ":";
    if (sr.getString() == null) {
      s+=sr.getID();
    }
 else {
      s+=sr.getString();
    }
    s+=",";
  }
  if (featureKeys.size() > 0) {
    s=s.substring(0,s.length() - 1) + ")";
  }
  return s;
}
 

Example 9

From project addis, under directory /application/src/main/java/org/drugis/addis/entities/analysis/.

Source file: AbstractMetaAnalysis.java

  29 
vote

private static List<TreatmentDefinition> calculateDefinitions(Map<Study,Map<TreatmentDefinition,Arm>> armMap){
  SortedSet<TreatmentDefinition> treatments=new TreeSet<TreatmentDefinition>();
  for (  Map<TreatmentDefinition,Arm> entry : armMap.values()) {
    treatments.addAll(entry.keySet());
  }
  return new ArrayList<TreatmentDefinition>(treatments);
}
 

Example 10

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Commands/Player/.

Source file: Search.java

  29 
vote

@Override public void execute(final CommandSender sender,final CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
  if (args.hasFlag('i')) {
    final String ip=args.getValueFlag('i');
    if (ip == null || ip.equals("") || ip.length() == 0) {
      return;
    }
    final Player[] onPlayers=ACPluginManager.getServer().getOnlinePlayers();
    final List<ACPlayer> exPlayers=PlayerManager.getInstance().getExistingPlayers();
    final TreeSet<String> players=new TreeSet<String>();
    final TreeSet<String> playersOld=new TreeSet<String>();
    final String on="[ON] ", off="[OFF] ";
    InetAddress ipAdress;
    for (    final Player p : onPlayers) {
      ipAdress=p.getAddress().getAddress();
      if (ipAdress != null && ipAdress.toString().substring(1).equals(ip)) {
        players.add(on + Utils.getPlayerName(p));
        playersOld.add(p.getName());
      }
    }
    String ip2;
    for (    final ACPlayer p : exPlayers) {
      ip2=p.getInformation("last-ip").getString();
      if (ip2 != null && ip2.contains(ip) && !playersOld.contains(p.getName())) {
        players.add(off + p.getName());
      }
    }
    final String found=Joiner.on(", ").join(players);
    sender.sendMessage(found);
    return;
  }
}
 

Example 11

From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/tasks/.

Source file: Layout.java

  29 
vote

public Layout(String layout) throws BuildException {
  Collection<String> valid=new HashSet<String>(Arrays.asList(GID,GID_DIRS,AID,VER,BVER,EXT,CLS));
  List<String> tokens=new ArrayList<String>();
  Matcher m=Pattern.compile("(\\{[^}]*\\})|([^{]+)").matcher(layout);
  while (m.find()) {
    if (m.group(1) != null && !valid.contains(m.group(1))) {
      throw new BuildException("Invalid variable '" + m.group() + "' in layout, supported variables are "+ new TreeSet<String>(valid));
    }
    tokens.add(m.group());
  }
  this.tokens=tokens.toArray(new String[tokens.size()]);
}
 

Example 12

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/internal/impl/.

Source file: DefaultUpdateCheckManager.java

  29 
vote

private String getDataKey(Artifact artifact,File artifactFile,RemoteRepository repository){
  Set<String> mirroredUrls=Collections.emptySet();
  if (repository.isRepositoryManager()) {
    mirroredUrls=new TreeSet<String>();
    for (    RemoteRepository mirroredRepository : repository.getMirroredRepositories()) {
      mirroredUrls.add(normalizeRepoUrl(mirroredRepository.getUrl()));
    }
  }
  StringBuilder buffer=new StringBuilder(1024);
  buffer.append(normalizeRepoUrl(repository.getUrl()));
  for (  String mirroredUrl : mirroredUrls) {
    buffer.append('+').append(mirroredUrl);
  }
  return buffer.toString();
}
 

Example 13

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/auth/.

Source file: Authenticator.java

  29 
vote

@Transient protected SortedSet<AppRoleInfo> getRolesForUser(AppUserInfo user){
  SortedSet<AppRoleInfo> rolesForUser=new TreeSet<AppRoleInfo>();
  for (  AppRoleInfo role : this.getRolesDirect()) {
    SortedSet<AppUserInfo> usersForRole=role.getUsers();
    if (usersForRole.contains(user)) {
      rolesForUser.add(role);
    }
  }
  return Collections.unmodifiableSortedSet(rolesForUser);
}
 

Example 14

From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/testing/.

Source file: ConfigAssertions.java

  29 
vote

public static <T>void assertDefaults(Map<String,Object> expectedAttributeValues,Class<T> configClass){
  ConfigurationMetadata<?> metadata=ConfigurationMetadata.getValidConfigurationMetadata(configClass);
  if (!metadata.getAttributes().keySet().containsAll(expectedAttributeValues.keySet())) {
    TreeSet<String> unsupportedAttributes=new TreeSet<String>(expectedAttributeValues.keySet());
    unsupportedAttributes.removeAll(metadata.getAttributes().keySet());
    Assert.fail("Unsupported attributes: " + unsupportedAttributes);
  }
  Set<String> nonDeprecatedAttributes=new TreeSet<String>();
  for (  AttributeMetadata attribute : metadata.getAttributes().values()) {
    if (attribute.getInjectionPoint().getProperty() != null) {
      nonDeprecatedAttributes.add(attribute.getName());
    }
  }
  if (!nonDeprecatedAttributes.containsAll(expectedAttributeValues.keySet())) {
    TreeSet<String> unsupportedAttributes=new TreeSet<String>(expectedAttributeValues.keySet());
    unsupportedAttributes.removeAll(nonDeprecatedAttributes);
    Assert.fail("Deprecated attributes: " + unsupportedAttributes);
  }
  if (!expectedAttributeValues.keySet().containsAll(nonDeprecatedAttributes)) {
    TreeSet<String> untestedAttributes=new TreeSet<String>(nonDeprecatedAttributes);
    untestedAttributes.removeAll(expectedAttributeValues.keySet());
    Assert.fail("Untested attributes: " + untestedAttributes);
  }
  T actual=newDefaultInstance(configClass);
  for (  AttributeMetadata attribute : metadata.getAttributes().values()) {
    Method getter=attribute.getGetter();
    if (getter == null) {
      continue;
    }
    Object actualAttributeValue=invoke(actual,getter);
    Object expectedAttributeValue=expectedAttributeValues.get(attribute.getName());
    Assert.assertEquals(expectedAttributeValue,actualAttributeValue,attribute.getName());
  }
}
 

Example 15

From project amplafi-sworddance, under directory /src/test/java/com/sworddance/util/.

Source file: TestUtilities.java

  29 
vote

@Test public void testGetFirst(){
  assertNull(getFirst(null));
  assertEquals(getFirst(new String[]{"a"}),"a");
  assertEquals(getFirst(new String[]{"a","b"}),"a");
  assertEquals(getFirst(Arrays.asList("a","b")),"a");
  assertEquals(getFirst("a"),"a");
  assertEquals(getFirst(new TreeSet<String>(Arrays.asList("a","b"))),"a");
}
 

Example 16

From project Android, under directory /app/src/main/java/com/github/mobile/core/issue/.

Source file: IssueFilter.java

  29 
vote

/** 
 * Add label to filter
 * @param label
 * @return this filter
 */
public IssueFilter addLabel(Label label){
  if (label == null)   return this;
  if (labels == null)   labels=new TreeSet<Label>(this);
  labels.add(label);
  return this;
}
 

Example 17

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/http/.

Source file: HttpParameters.java

  29 
vote

/** 
 * Convenience method to add a single value for the parameter specified by 'key'.
 * @param key the parameter name
 * @param value the parameter value
 * @param percentEncode whether key and value should be percent encoded before being inserted into the map
 * @return the value
 */
public String put(String key,String value,boolean percentEncode){
  SortedSet<String> values=wrappedMap.get(key);
  if (values == null) {
    values=new TreeSet<String>();
    wrappedMap.put(percentEncode ? OAuth.percentEncode(key) : key,values);
  }
  if (value != null) {
    value=percentEncode ? OAuth.percentEncode(value) : value;
    values.add(value);
  }
  return value;
}
 

Example 18

From project android-thaiime, under directory /common/src/com/android/common/.

Source file: OperationScheduler.java

  29 
vote

/** 
 * Return a string description of the scheduler state for debugging.
 */
public String toString(){
  StringBuilder out=new StringBuilder("[OperationScheduler:");
  for (  String key : new TreeSet<String>(mStorage.getAll().keySet())) {
    if (key.startsWith(PREFIX)) {
      if (key.endsWith("TimeMillis")) {
        Time time=new Time();
        time.set(mStorage.getLong(key,0));
        out.append(" ").append(key.substring(PREFIX.length(),key.length() - 10));
        out.append("=").append(time.format("%Y-%m-%d/%H:%M:%S"));
      }
 else {
        out.append(" ").append(key.substring(PREFIX.length()));
        out.append("=").append(mStorage.getAll().get(key).toString());
      }
    }
  }
  return out.append("]").toString();
}
 

Example 19

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  29 
vote

@SuppressWarnings({"rawtypes"}) private static ParameterizedTypeHandlerMap<InstanceCreator<?>> createDefaultInstanceCreators(){
  ParameterizedTypeHandlerMap<InstanceCreator<?>> map=new ParameterizedTypeHandlerMap<InstanceCreator<?>>();
  DefaultConstructorAllocator allocator=new DefaultConstructorAllocator(50);
  map.registerForTypeHierarchy(Map.class,new DefaultConstructorCreator<Map>(LinkedHashMap.class,allocator));
  DefaultConstructorCreator<List> listCreator=new DefaultConstructorCreator<List>(ArrayList.class,allocator);
  DefaultConstructorCreator<Queue> queueCreator=new DefaultConstructorCreator<Queue>(LinkedList.class,allocator);
  DefaultConstructorCreator<Set> setCreator=new DefaultConstructorCreator<Set>(HashSet.class,allocator);
  DefaultConstructorCreator<SortedSet> sortedSetCreator=new DefaultConstructorCreator<SortedSet>(TreeSet.class,allocator);
  map.registerForTypeHierarchy(Collection.class,listCreator);
  map.registerForTypeHierarchy(Queue.class,queueCreator);
  map.registerForTypeHierarchy(Set.class,setCreator);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator);
  map.makeUnmodifiable();
  return map;
}
 

Example 20

From project android_build, under directory /tools/droiddoc/src/.

Source file: Hierarchy.java

  29 
vote

public static void makeHierarchy(HDF hdf,ClassInfo[] classes){
  HashMap<String,TreeSet<String>> nodes=new HashMap<String,TreeSet<String>>();
  for (  ClassInfo cl : classes) {
    String name=cl.qualifiedName();
    TreeSet<String> me=nodes.get(name);
    if (me == null) {
      me=new TreeSet<String>();
      nodes.put(name,me);
    }
    ClassInfo superclass=cl.superclass();
    String sname=superclass != null ? superclass.qualifiedName() : null;
    if (sname != null) {
      TreeSet<String> s=nodes.get(sname);
      if (s == null) {
        s=new TreeSet<String>();
        nodes.put(sname,s);
      }
      s.add(name);
    }
  }
  int depth=depth(nodes,"java.lang.Object");
  hdf.setValue("classes.0","");
  hdf.setValue("colspan","" + depth);
  recurse(nodes,"java.lang.Object",hdf.getObj("classes.0"),depth,depth);
  if (false) {
    Set<String> keys=nodes.keySet();
    if (keys.size() > 0) {
      System.err.println("The following classes are hidden but" + " are superclasses of not-hidden classes");
      for (      String n : keys) {
        System.err.println("  " + n);
      }
    }
  }
}
 

Example 21

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Sets.java

  29 
vote

/** 
 * Creates a <i>mutable</i>  {@code TreeSet} instance containing the givenelements sorted by their natural ordering. <p><b>Note:</b> if mutability is not required, use  {@link ImmutableSortedSet#copyOf(Iterable)} instead.<p><b>Note:</b> If  {@code elements} is a {@code SortedSet} with an explicitcomparator, this method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a  {@code TreeSet} withthat comparator.
 * @param elements the elements that the set should contain
 * @return a new {@code TreeSet} containing those elements (minus duplicates)
 */
@SuppressWarnings("unchecked") public static <E extends Comparable>TreeSet<E> newTreeSet(Iterable<? extends E> elements){
  TreeSet<E> set=newTreeSet();
  for (  E element : elements) {
    set.add(element);
  }
  return set;
}
 

Example 22

From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.

Source file: FlyweightMapStorage.java

  29 
vote

@Override public void readFromSortedMap(SortedMap<Integer,String> sortedAreaCodeMap){
  SortedSet<String> descriptionsSet=new TreeSet<String>();
  numOfEntries=sortedAreaCodeMap.size();
  prefixSizeInBytes=getOptimalNumberOfBytesForValue(sortedAreaCodeMap.lastKey());
  phoneNumberPrefixes=ByteBuffer.allocate(numOfEntries * prefixSizeInBytes);
  int index=0;
  for (  Entry<Integer,String> entry : sortedAreaCodeMap.entrySet()) {
    int prefix=entry.getKey();
    storeWordInBuffer(phoneNumberPrefixes,prefixSizeInBytes,index++,prefix);
    possibleLengths.add((int)Math.log10(prefix) + 1);
    descriptionsSet.add(entry.getValue());
  }
  descIndexSizeInBytes=getOptimalNumberOfBytesForValue(descriptionsSet.size() - 1);
  descriptionIndexes=ByteBuffer.allocate(numOfEntries * descIndexSizeInBytes);
  descriptionPool=new String[descriptionsSet.size()];
  descriptionsSet.toArray(descriptionPool);
  index=0;
  for (int i=0; i < numOfEntries; i++) {
    int prefix=readWordFromBuffer(phoneNumberPrefixes,prefixSizeInBytes,i);
    String description=sortedAreaCodeMap.get(prefix);
    int positionInDescriptionPool=Arrays.binarySearch(descriptionPool,description,new Comparator<String>(){
      public int compare(      String o1,      String o2){
        return o1.compareTo(o2);
      }
    }
);
    storeWordInBuffer(descriptionIndexes,descIndexSizeInBytes,index++,positionInDescriptionPool);
  }
}
 

Example 23

From project android_frameworks_ex, under directory /common/java/com/android/common/.

Source file: OperationScheduler.java

  29 
vote

/** 
 * Return a string description of the scheduler state for debugging.
 */
public String toString(){
  StringBuilder out=new StringBuilder("[OperationScheduler:");
  for (  String key : new TreeSet<String>(mStorage.getAll().keySet())) {
    if (key.startsWith(PREFIX)) {
      if (key.endsWith("TimeMillis")) {
        Time time=new Time();
        time.set(mStorage.getLong(key,0));
        out.append(" ").append(key.substring(PREFIX.length(),key.length() - 10));
        out.append("=").append(time.format("%Y-%m-%d/%H:%M:%S"));
      }
 else {
        out.append(" ").append(key.substring(PREFIX.length()));
        out.append("=").append(mStorage.getAll().get(key).toString());
      }
    }
  }
  return out.append("]").toString();
}
 

Example 24

From project android_packages_apps_cmparts, under directory /src/com/cyanogenmod/cmparts/activities/led/.

Source file: NotificationActivity.java

  29 
vote

private Set<String> getCategoryList(){
  Set<String> categories=new TreeSet<String>();
  for (  PackageSettings settings : mPackages.values()) {
    if (settings.category != null) {
      categories.add(settings.category);
    }
  }
  return categories;
}
 

Example 25

From project android_packages_inputmethods_LatinIME, under directory /tools/makedict/src/com/android/inputmethod/latin/.

Source file: XmlDictInputOutput.java

  29 
vote

/** 
 * Writes a dictionary to an XML file. The output format is the "second" format, which supports bigrams and shortcuts.
 * @param destination a destination stream to write to.
 * @param dict the dictionary to write.
 */
public static void writeDictionaryXml(Writer destination,FusionDictionary dict) throws IOException {
  final TreeSet<Word> set=new TreeSet<Word>();
  for (  Word word : dict) {
    set.add(word);
  }
  destination.write("<wordlist format=\"2\">\n");
  for (  Word word : set) {
    destination.write("  <" + WORD_TAG + " "+ WORD_ATTR+ "=\""+ word.mWord+ "\" "+ FREQUENCY_ATTR+ "=\""+ word.mFrequency+ "\">");
    if (null != word.mBigrams) {
      destination.write("\n");
      for (      WeightedString bigram : word.mBigrams) {
        destination.write("    <" + BIGRAM_TAG + " "+ FREQUENCY_ATTR+ "=\""+ bigram.mFrequency+ "\">"+ bigram.mWord+ "</"+ BIGRAM_TAG+ ">\n");
      }
      destination.write("  ");
    }
    destination.write("</" + WORD_TAG + ">\n");
  }
  destination.write("</wordlist>\n");
  destination.close();
}
 

Example 26

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: CardEditor.java

  29 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  registerExternalStorageListener();
  setContentView(R.layout.card_editor);
  mFieldsLayoutContainer=(LinearLayout)findViewById(R.id.CardEditorEditFieldsLayout);
  mSave=(Button)findViewById(R.id.CardEditorSaveButton);
  mCancel=(Button)findViewById(R.id.CardEditorCancelButton);
  mEditorCard=Reviewer.getEditorCard();
  Fact cardFact=mEditorCard.getFact();
  TreeSet<Field> fields=cardFact.getFields();
  mEditFields=new LinkedList<FieldEditText>();
  Iterator<Field> iter=fields.iterator();
  while (iter.hasNext()) {
    FieldEditText newTextbox=new FieldEditText(this,iter.next());
    TextView label=newTextbox.getLabel();
    mEditFields.add(newTextbox);
    mFieldsLayoutContainer.addView(label);
    mFieldsLayoutContainer.addView(newTextbox);
  }
  mSave.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(    View v){
      Iterator<FieldEditText> iter=mEditFields.iterator();
      while (iter.hasNext()) {
        FieldEditText current=iter.next();
        current.updateField();
      }
      setResult(RESULT_OK);
      finish();
    }
  }
);
  mCancel.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(    View v){
      setResult(RESULT_CANCELED);
      finish();
    }
  }
);
}
 

Example 27

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/controlpanel/.

Source file: ControlPanel.java

  29 
vote

@Override public void run(){
  WebResource res=null;
synchronized (getApplication()) {
    res=Helper.getAnnisWebResource(getApplication());
  }
  if (res != null) {
    try {
      Set<String> corpusNames=new TreeSet<String>();
      for (      AnnisCorpus c : lastCorpusSelection.values()) {
        corpusNames.add(c.getName());
      }
      count=Integer.parseInt(res.path("search").path("count").queryParam("q",lastQuery).queryParam("corpora",StringUtils.join(corpusNames,",")).get(String.class));
    }
 catch (    UniformInterfaceException ex) {
synchronized (getApplication()) {
        if (ex.getResponse().getStatus() == 400) {
          window.showNotification(ex.getResponse().getEntity(String.class),"parsing error",Window.Notification.TYPE_ERROR_MESSAGE);
        }
 else {
          window.showNotification(ex.getResponse().getEntity(String.class),"unknown error " + ex.getResponse().getStatus(),Window.Notification.TYPE_ERROR_MESSAGE);
        }
      }
    }
  }
synchronized (getApplication()) {
    queryPanel.setStatus("" + count + " matches");
    searchWindow.updateQueryCount(count);
  }
  queryPanel.setCountIndicatorEnabled(false);
}
 

Example 28

From project apb, under directory /modules/apb-base/src/apb/.

Source file: DefinitionsIndex.java

  29 
vote

private Collection<ModuleInfo> buildModulesList(){
  Collection<ModuleInfo> result=new TreeSet<ModuleInfo>();
  for (  ModulesInfo modulesInfo : loadCache().values()) {
    if (projectPath.contains(modulesInfo.getPath())) {
      debug("Path %s. Modules: %s\n",modulesInfo.getPath(),modulesInfo.getModules());
      for (      ModuleInfo module : modulesInfo.getModules()) {
        result.add(module);
      }
    }
  }
  return result;
}
 

Example 29

From project Archimedes, under directory /br.org.archimedes.polyline/src/br/org/archimedes/polyline/.

Source file: Polyline.java

  29 
vote

public SortedSet<ComparablePoint> getSortedPointSet(Point referencePoint,Collection<Point> intersectionPoints){
  SortedSet<ComparablePoint> sortedPointSet=new TreeSet<ComparablePoint>();
  List<Line> lines=getLines();
  Point firstPoint=points.get(0);
  boolean invertOrder=!firstPoint.equals(referencePoint);
  for (  Point intersection : intersectionPoints) {
    try {
      int i=getIntersectionIndex(invertOrder,intersection);
      if (i < lines.size()) {
        ComparablePoint point=generateComparablePoint(intersection,invertOrder,i);
        sortedPointSet.add(point);
      }
    }
 catch (    NullArgumentException e) {
      e.printStackTrace();
    }
  }
  return sortedPointSet;
}
 

Example 30

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/util/iterator/.

Source file: TransformingPrefixStringFilter.java

  29 
vote

public static TreeSet<String> makeTreeSet(Collection<String> blocks,StringTransformer trans){
  TreeSet<String> tmp=new TreeSet<String>();
  for (  String filter : blocks) {
    if (trans != null) {
      filter=trans.transform(filter);
    }
    String possiblePrefix=tmp.floor(filter);
    if (possiblePrefix != null && filter.startsWith(possiblePrefix)) {
    }
 else {
      String possibleLonger=tmp.ceiling(filter);
      if (possibleLonger == null) {
      }
 else       if (possibleLonger.startsWith(filter)) {
        tmp.remove(possibleLonger);
      }
      tmp.add(filter);
    }
  }
  return tmp;
}
 

Example 31

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/io/.

Source file: LookupResponseHandler.java

  29 
vote

public LookupManager(Contact[] contacts,RouteTable routeTable,KUID lookupId){
  this.routeTable=routeTable;
  this.lookupId=lookupId;
  Contact localhost=routeTable.getIdentity();
  KUID contactId=localhost.getId();
  XorComparator comparator=new XorComparator(lookupId);
  this.responses=new TreeSet<Contact>(comparator);
  this.closest=new TreeSet<Contact>(comparator);
  this.query=new TreeSet<Contact>(comparator);
  history.put(contactId,0);
  addToResponses(localhost);
  for (  Contact contact : contacts) {
    addToQuery(contact,1);
  }
}
 

Example 32

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/config/jmx/.

Source file: JMXEnumerator.java

  29 
vote

public List<MBeanAttribute> enumerate() throws IOException, ReflectionException, InstanceNotFoundException, IntrospectionException {
  List<MBeanAttribute> list=new ArrayList<MBeanAttribute>();
  Set<ObjectName> instances=client.getMBeanServerConnection().queryNames(null,null);
  for (  ObjectName desc : new TreeSet<ObjectName>(instances)) {
    MBeanInfo info=client.getMBeanServerConnection().getMBeanInfo(desc);
    ObjectInstance obj=client.getMBeanServerConnection().getObjectInstance(desc);
    System.out.printf("%s, %s\n",desc,obj);
    String accessor=desc.toString();
    for (    MBeanAttributeInfo attr : info.getAttributes()) {
      if (attr.isReadable() && legalTypes.contains(attr.getType())) {
        list.add(new MBeanAttribute(attr.getName(),resolvePrettyName(accessor),accessor));
      }
    }
  }
  return list;
}
 

Example 33

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/retriever/sample/.

Source file: AbstractSampleRetriever.java

  29 
vote

@Override public BufferedImage retrieve(String source,Properties localProperties) throws RetrieverException {
  Properties mergedProperties=mergeProperties(localProperties);
  if (allSources == null) {
synchronized (this) {
      allSources=new TreeSet<String>(getAllSources(mergedProperties));
      unretrievedSources=new TreeSet<String>(allSources);
    }
  }
  int retries=mergedProperties.getProperty("load-source-retries",1,Integer.class);
  if (!allSources.contains(source)) {
    throw new NoSuchSampleException("source '" + source + "' wasn't found when listing all of available samples");
  }
  for (int i=0; i < retries; i++) {
    try {
      return loadSource(source,mergedProperties);
    }
 catch (    Exception e) {
      continue;
    }
  }
  throw new RetrieverException("can't load the source '" + source + "'");
}
 

Example 34

From project ATHENA, under directory /core/web-resources/src/test/java/org/fracturedatlas/athena/web/resource/.

Source file: RecordResourceTest.java

  29 
vote

@Test public void testSearchRelationships(){
  when(mockUriInfo.getQueryParameters()).thenReturn(null);
  when(mockRecordManager.findSubResources("company","1","employee",null)).thenReturn(new TreeSet<PTicket>());
  resource.search("companies","1","employees",mockUriInfo);
  verify(mockRecordManager,times(1)).findSubResources("company","1","employee",null);
}
 

Example 35

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/trace/.

Source file: TraceCollection.java

  29 
vote

/** 
 * Returns the [count] longest traces in this collection.
 */
@SuppressWarnings("unchecked") public List<Trace> longestTraces(int count){
  TreeSet<Trace> cloned=(TreeSet<Trace>)this.traces.clone();
  LinkedList<Trace> out=new LinkedList<Trace>();
  for (int i=0; i < count; i++) {
    Trace toAdd=cloned.pollLast();
    if (toAdd == null) {
      break;
    }
    out.add(toAdd);
  }
  return out;
}
 

Example 36

From project backend-update-center2, under directory /src/test/java/.

Source file: ListExisting.java

  29 
vote

public static void main(String[] args) throws Exception {
  MavenRepositoryImpl r=DefaultMavenRepositoryBuilder.createStandardInstance();
  Set<String> groupIds=new TreeSet<String>();
  Collection<PluginHistory> all=r.listHudsonPlugins();
  for (  PluginHistory p : all) {
    HPI hpi=p.latest();
    groupIds.add(hpi.artifact.groupId);
  }
  for (  String groupId : groupIds) {
    System.out.println(groupId);
  }
}
 

Example 37

From project ballroom, under directory /widgets/src/main/java/org/jboss/ballroom/client/widgets/forms/.

Source file: ListBoxItem.java

  29 
vote

public void setChoices(Collection<String> choices,String defaultChoice){
  Set<String> sortedChoices=new TreeSet<String>(choices);
  int i=0;
  int idx=-1;
  listBox.clear();
  for (  String c : sortedChoices) {
    listBox.addItem(c);
    if (c.equals(defaultChoice))     idx=i;
    i++;
  }
  if (idx >= 0)   listBox.setSelectedIndex(idx);
 else   listBox.setSelectedIndex(-1);
}
 

Example 38

From project BetterShop_1, under directory /src/com/sk89q/wg_regions_52/managers/.

Source file: FlatRegionManager.java

  29 
vote

/** 
 * Get an object for a point for rules to be applied with.
 * @param pt
 * @return
 */
@Override public ApplicableRegionSet getApplicableRegions(Vector pt){
  final TreeSet<Region> appRegions=new TreeSet<Region>();
  for (  final Region region : regions.values()) {
    if (region.contains(pt)) {
      appRegions.add(region);
      Region parent=region.getParent();
      while (parent != null) {
        if (!appRegions.contains(parent)) {
          appRegions.add(region);
        }
        parent=parent.getParent();
      }
    }
  }
  return new ApplicableRegionSet(appRegions,regions.get("__global__"));
}
 

Example 39

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common.tests/src/de/bht/fpa/mail/common/model/.

Source file: MessageTest.java

  29 
vote

@Test public void shouldBeUseableInCollectionsWhichExpectComparables() throws Exception {
  Set<Message> messages=new TreeSet<Message>();
  messages.add(newMessageBuilder().id(4L).build());
  messages.add(newMessageBuilder().id(1L).build());
  messages.add(newMessageBuilder().id(2L).build());
  messages.add(newMessageBuilder().id(3L).build());
}
 

Example 40

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/activity/.

Source file: ReaderActivity.java

  29 
vote

public boolean onActionItemClicked(ActionMode mode,MenuItem item){
  TreeSet<Integer> selVerses=vWeb.getSelectedVerses();
  if (selVerses.size() == 0) {
    return true;
  }
switch (item.getItemId()) {
case R.id.action_bookmarks:
    Bookmarks.add(myLibrarian,selVerses.first());
  Toast.makeText(ReaderActivity.this,getString(R.string.added),Toast.LENGTH_LONG).show();
break;
case R.id.action_share:
myLibrarian.shareText(ReaderActivity.this,selVerses,Destination.ActionSend);
break;
case R.id.action_copy:
myLibrarian.shareText(ReaderActivity.this,selVerses,Destination.Clipboard);
Toast.makeText(ReaderActivity.this,getString(R.string.added),Toast.LENGTH_LONG).show();
break;
case R.id.action_references:
myLibrarian.setCurrentVerseNumber(selVerses.first());
Intent intParallels=new Intent(VIEW_REFERENCE);
intParallels.putExtra("linkOSIS",myLibrarian.getCurrentOSISLink().getPath());
startActivityForResult(intParallels,R.id.action_bar_parallels);
break;
default :
return false;
}
mode.finish();
return true;
}
 

Example 41

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/di/.

Source file: CollectionRecipe.java

  29 
vote

public static Class getCollection(Class type){
  if (ReflectionUtils.hasDefaultConstructor(type)) {
    return type;
  }
 else   if (SortedSet.class.isAssignableFrom(type)) {
    return TreeSet.class;
  }
 else   if (Set.class.isAssignableFrom(type)) {
    return LinkedHashSet.class;
  }
 else   if (List.class.isAssignableFrom(type)) {
    return ArrayList.class;
  }
 else   if (Queue.class.isAssignableFrom(type)) {
    return LinkedList.class;
  }
 else {
    return ArrayList.class;
  }
}
 

Example 42

From project BMach, under directory /src/jsyntaxpane/lexers/.

Source file: SimpleRegexLexer.java

  29 
vote

@Override public void parse(Segment segment,int ofst,List<Token> tokens){
  TreeSet<Token> allMatches=new TreeSet<Token>(TokenComparators.LONGEST_FIRST);
  for (  Map.Entry<TokenType,Pattern> e : patterns.entrySet()) {
    Matcher m=e.getValue().matcher(segment);
    while (m.find()) {
      Token t=new Token(e.getKey(),m.start() + ofst,m.end() - m.start());
      allMatches.add(t);
    }
  }
  int end=-1;
  for (  Token t : allMatches) {
    if (t.start > end) {
      tokens.add(t);
      end=t.end();
    }
  }
}
 

Example 43

From project bndtools, under directory /bndtools.core/src/bndtools/utils/.

Source file: DependencyUtils.java

  29 
vote

public static <T>void processDependencyMap(Collection<T> input,Map<T,Set<T>> dependencies,Processor<T> processor,IProgressMonitor monitor) throws CoreException, CircularDependencyException {
  SubMonitor progress=SubMonitor.convert(monitor,input.size());
  Set<T> processed=new TreeSet<T>();
  Stack<T> callStack=new Stack<T>();
  for (  T selected : input) {
    processDependencyMap(selected,callStack,dependencies,processed,processor,progress);
  }
}
 

Example 44

From project book, under directory /src/main/java/com/tamingtext/classifier/mlt/.

Source file: MoreLikeThisCategorizer.java

  29 
vote

public CategoryHits[] categorize(Reader reader) throws IOException {
  Query query=moreLikeThis.like(reader);
  HashMap<String,CategoryHits> categoryHash=new HashMap<String,CategoryHits>(25);
  for (  ScoreDoc sd : indexSearcher.search(query,maxResults).scoreDocs) {
    String cat=getDocClass(sd.doc);
    if (cat == null)     continue;
    CategoryHits ch=categoryHash.get(cat);
    if (ch == null) {
      ch=new CategoryHits();
      ch.setLabel(cat);
      categoryHash.put(cat,ch);
    }
    ch.incrementScore(sd.score);
  }
  SortedSet<CategoryHits> sortedCats=new TreeSet<CategoryHits>(CategoryHits.byScoreComparator());
  sortedCats.addAll(categoryHash.values());
  return sortedCats.toArray(new CategoryHits[0]);
}
 

Example 45

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/plugin/site/picker/reference/.

Source file: QueryParametersTab.java

  29 
vote

private Set<Entry> getEntries(){
  if (entries == null) {
    entries=new TreeSet<Entry>();
    for (    String s : getPageParameters().getNamedKeys()) {
      for (      StringValue v : getPageParameters().getValues(s)) {
        Entry e=new Entry();
        e.key=s;
        e.value=v.toString();
        entries.add(e);
      }
    }
  }
  return entries;
}
 

Example 46

From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.

Source file: ThreadHistoryMonitorHelper.java

  29 
vote

private void writeEvents(Formatter fw,String title,Collection<ThreadMonitorEvent> events){
  int count=0;
  TreeSet<String> threadNames=new TreeSet<String>();
  fw.format("+++ Begin %s Events, count=%d +++\n",title,events.size());
  for (  ThreadMonitorEvent event : events) {
    if (event.getRunnableClass() != null) {
      fw.format("#%d, %s(runnable=%s)\n%s\n",count++,event.getThreadName(),event.getRunnableClass(),event.getFullStack());
    }
 else {
      fw.format("#%d, %s\n%s\n",count++,event.getThreadName(),event.getFullStack());
    }
    threadNames.add(event.getThreadName());
  }
  fw.format("+++ End %s Events +++\n",title);
  fw.format("+++ Begin %s Thread Names +++\n",title);
  for (  String name : threadNames) {
    fw.format("%s\n",name);
  }
  fw.format("+++ End %s Thread Names +++\n",title);
}
 

Example 47

From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/util/.

Source file: Counter.java

  29 
vote

/** 
 * Returns a view of the items currently being counted in sorted order.  The returned view is read-write.
 */
public List<T> itemsSorted(boolean sortAscending){
  Comparator<? super Map.Entry<T,Integer>> comparator=new EntryComparator(sortAscending);
  Set<Map.Entry<T,Integer>> sortedItemSet=new TreeSet<Map.Entry<T,Integer>>(comparator);
  sortedItemSet.addAll(counts.entrySet());
  List<T> items=new ArrayList<T>(counts.size());
  for (  Map.Entry<T,Integer> item : sortedItemSet)   items.add(item.getKey());
  return items;
}
 

Example 48

From project CalendarPortlet, under directory /src/test/java/org/jasig/portlet/calendar/processor/.

Source file: ICalendarContentProcessorTest.java

  29 
vote

@Test public void test() throws IOException {
  Resource calendarFile=applicationContext.getResource("classpath:/sampleEvents.ics");
  DateMidnight start=new DateMidnight(2010,1,1,DateTimeZone.UTC);
  Interval interval=new Interval(start,start.plusYears(3));
  InputStream in=calendarFile.getInputStream();
  ByteArrayOutputStream buffer=new ByteArrayOutputStream();
  IOUtils.copyLarge(in,buffer);
  TreeSet<VEvent> events=new TreeSet<VEvent>(new VEventStartComparator());
  net.fortuna.ical4j.model.Calendar c=processor.getIntermediateCalendar(interval,new ByteArrayInputStream(buffer.toByteArray()));
  events.addAll(processor.getEvents(interval,c));
  assertEquals(5,events.size());
  Iterator<VEvent> iterator=events.iterator();
  VEvent event=iterator.next();
  assertEquals("Independence Day",event.getSummary().getValue());
  assertNull(event.getStartDate().getTimeZone());
  event=iterator.next();
  assertEquals("Vikings @ Saints  [NBC]",event.getSummary().getValue());
  DateTime eventStart=new DateTime(event.getStartDate().getDate(),DateTimeZone.UTC);
  assertEquals(0,eventStart.getHourOfDay());
  assertEquals(30,eventStart.getMinuteOfHour());
  event=iterator.next();
  assertEquals("Independence Day",event.getSummary().getValue());
  assertNull(event.getStartDate().getTimeZone());
}
 

Example 49

From project candlepin, under directory /src/main/java/org/candlepin/model/.

Source file: PoolCurator.java

  29 
vote

/** 
 * Method to compile service/support level lists. One is the available levels for consumers for this owner. The second is the level names that are exempt. Exempt means that a product pool with this level can be used with a consumer of any service level.
 * @param owner The owner that has the list of available service levels forits consumers
 * @param exempt boolean to show if the desired list is the levels that areexplicitly marked with the support_level_exempt attribute.
 * @return Set of levels based on exempt flag.
 */
public Set<String> retrieveServiceLevelsForOwner(Owner owner,boolean exempt){
  String stmt="select distinct name, value, productId " + "from ProductPoolAttribute a where " + "(name='support_level' or name='support_level_exempt') "+ "and productId in (select distinct p.productId from Pool p where "+ "owner_id=:owner_id) order by name DESC";
  Query q=currentSession().createQuery(stmt);
  q.setParameter("owner_id",owner.getId());
  List<Object[]> results=q.list();
  Set<String> slaSet=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  Set<String> exemptSlaSet=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  Set<String> exemptProductIds=new HashSet<String>();
  for (  Object[] result : results) {
    String name=(String)result[0];
    String value=(String)result[1];
    String productId=(String)result[2];
    if ("support_level_exempt".equals(name) && "true".equalsIgnoreCase(value)) {
      exemptProductIds.add(productId);
    }
 else     if ("support_level".equalsIgnoreCase(name) && (value != null && !value.trim().equals(""))) {
      if (exemptProductIds.contains(productId)) {
        exemptSlaSet.add(value);
      }
    }
  }
  for (  Object[] result : results) {
    String name=(String)result[0];
    String value=(String)result[1];
    if (!"support_level_exempt".equals(name)) {
      if (!exemptSlaSet.contains(value)) {
        slaSet.add(value);
      }
    }
  }
  if (exempt) {
    return exemptSlaSet;
  }
  return slaSet;
}
 

Example 50

From project capedwarf-blue, under directory /prospectivesearch/src/main/java/org/jboss/capedwarf/prospectivesearch/.

Source file: TopicsReducer.java

  29 
vote

public Set<String> reduce(String reducedKey,Iterator<Set<String>> iter){
  Set<String> allTopics=new TreeSet<String>();
  while (iter.hasNext()) {
    Set<String> topics=iter.next();
    allTopics.addAll(topics);
  }
  return allTopics;
}
 

Example 51

From project cascading, under directory /src/core/cascading/flow/stream/.

Source file: StepStreamGraph.java

  29 
vote

protected void setTraps(){
  Collection<Duct> ducts=getAllDucts();
  for (  Duct duct : ducts) {
    if (!(duct instanceof ElementDuct))     continue;
    ElementDuct elementDuct=(ElementDuct)duct;
    FlowElement flowElement=elementDuct.getFlowElement();
    Set<String> branchNames=new TreeSet<String>();
    if (flowElement instanceof Pipe)     branchNames.add(((Pipe)flowElement).getName());
 else     if (flowElement instanceof Tap)     branchNames.addAll(getTapBranchNamesFor(duct));
 else     throw new IllegalStateException("unexpected duct type" + duct.getClass().getCanonicalName());
    elementDuct.setBranchNames(branchNames);
    for (    String branchName : branchNames) {
      Tap trap=step.getTrap(branchName);
      if (trap != null) {
        elementDuct.setTrapHandler(new TrapHandler(flowProcess,trap,branchName));
        break;
      }
    }
    if (!elementDuct.hasTrapHandler())     elementDuct.setTrapHandler(new TrapHandler(flowProcess));
  }
}
 

Example 52

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/templatecompiler/statements/.

Source file: AttributesStatement.java

  29 
vote

/** 
 * <p class="changed_added_4_0"> </p>
 * @param attributes
 * @param componentAttributes
 */
public void processAttributes(AnyElement element,Collection<PropertyBase> componentAttributes){
  this.componentAttributes=componentAttributes;
  Set<String> processedAttributes=Sets.newHashSet();
  TreeSet<PassThrough> passThroughAttributes=Sets.newTreeSet();
  this.elementName=element.getName();
  processRegularAttributes(element,processedAttributes,passThroughAttributes);
  String passThrough=element.getPassThrough();
  processPassThrough(processedAttributes,passThroughAttributes,passThrough);
  String passThroughWithExclusions=element.getPassThroughWithExclusions();
  processPassThroughWithExclusions(processedAttributes,passThroughAttributes,passThroughWithExclusions);
  if (!passThroughAttributes.isEmpty()) {
    WriteAttributesSetStatement writeAttributesSetStatement=passThroughStatementProvider.get();
    addStatement(writeAttributesSetStatement);
    writeAttributesSetStatement.setAttributes(passThroughAttributes);
  }
}
 

Example 53

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/.

Source file: VirtualDir.java

  29 
vote

@Override public String[] list(String path) throws IOException {
  if (path.equals(".") || path.isEmpty()) {
    path="";
  }
 else   if (!path.endsWith("/")) {
    path+="/";
  }
  boolean dirSeen=false;
  TreeSet<String> nameSet=new TreeSet<String>();
  Enumeration<? extends ZipEntry> enumeration=zipFile.entries();
  while (enumeration.hasMoreElements()) {
    ZipEntry zipEntry=enumeration.nextElement();
    String name=zipEntry.getName();
    if (name.startsWith(path)) {
      int i1=path.length();
      int i2=name.indexOf("/",i1);
      String entryName;
      if (i2 == -1) {
        entryName=name.substring(i1);
      }
 else {
        entryName=name.substring(i1,i2);
      }
      if (!entryName.isEmpty() && !nameSet.contains(entryName)) {
        nameSet.add(entryName);
      }
      dirSeen=true;
    }
  }
  if (!dirSeen) {
    throw new FileNotFoundException(getBasePath() + "!" + path);
  }
  return nameSet.toArray(new String[nameSet.size()]);
}
 

Example 54

From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/loader/.

Source file: JDTModule.java

  29 
vote

private void loadAllPackages(){
  Set<String> packageList=new TreeSet<String>();
  if (isJava()) {
    for (    IPackageFragmentRoot fragmentRoot : packageFragmentRoots) {
      if (!fragmentRoot.exists())       continue;
      IParent parent=fragmentRoot;
      listPackages(packageList,parent);
    }
    for (    String packageName : packageList) {
      getPackage(packageName);
    }
  }
}
 

Example 55

From project ceylon-module-resolver, under directory /testsuite/src/test/java/com/redhat/ceylon/test/smoke/test/.

Source file: AbstractTest.java

  29 
vote

protected SortedSet<String> set(String... values){
  SortedSet<String> ret=new TreeSet<String>();
  for (  String v : values) {
    ret.add(v);
  }
  return ret;
}
 

Example 56

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/chess/.

Source file: BoardView.java

  29 
vote

public static List<BoardView> listBoardViews(boolean isSorted){
  if (isSorted) {
    SortedSet<String> sorted=new TreeSet<String>(chessBoards.keySet());
    List<BoardView> res=new ArrayList<BoardView>();
    for (    String name : sorted) {
      res.add(chessBoards.get(name));
    }
    return res;
  }
 else {
    return new ArrayList<BoardView>(chessBoards.values());
  }
}
 

Example 57

From project Chess_1, under directory /src/chess/gui/.

Source file: GUIController.java

  29 
vote

/** 
 * Creates a new controller tied to the specified display and gui frame.
 * @param parent the frame for the world window
 * @param disp the panel that displays the grid
 * @param displayMap the map for occupant displays
 * @param res the resource bundle for message display
 */
public GUIController(WorldFrame<T> parent,GridPanel disp,DisplayMap displayMap,ResourceBundle res){
  resources=res;
  display=disp;
  parentFrame=parent;
  this.displayMap=displayMap;
  makeControls();
  occupantClasses=new TreeSet<Class>(new Comparator<Class>(){
    public int compare(    Class a,    Class b){
      return a.getName().compareTo(b.getName());
    }
  }
);
  World<T> world=parentFrame.getWorld();
  Grid<T> gr=world.getGrid();
  for (  Location loc : gr.getOccupiedLocations())   addOccupant(gr.get(loc));
  for (  String name : world.getOccupantClasses())   try {
    occupantClasses.add(Class.forName(name));
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  timer=new Timer(INITIAL_DELAY,new ActionListener(){
    public void actionPerformed(    ActionEvent evt){
      step();
    }
  }
);
  display.addMouseListener(new MouseAdapter(){
    public void mousePressed(    MouseEvent evt){
      Grid<T> gr=parentFrame.getWorld().getGrid();
      Location loc=display.locationForPoint(evt.getPoint());
      if (loc != null && gr.isValid(loc) && !isRunning()) {
        display.setCurrentLocation(loc);
        locationClicked();
      }
    }
  }
);
  stop();
}
 

Example 58

From project chromattic, under directory /core/src/test/java/org/chromattic/test/jcr/.

Source file: AbstractJCRTestCase.java

  29 
vote

protected final void assertEquals(Set<Node> expected,Set<Node> actual){
  TreeSet<Node> expectedSet=new TreeSet<Node>(comparator);
  expectedSet.addAll(expected);
  TreeSet<Node> actualSet=new TreeSet<Node>(comparator);
  actualSet.addAll(actual);
  assertTrue("Was expected to have " + actual + " equals to "+ expected,expectedSet.equals(actualSet));
}
 

Example 59

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  29 
vote

public static Set<String> loadSet(final File file,final int chunksize,final boolean tree) throws IOException {
  final Set<String> set=(tree) ? (Set<String>)new TreeSet<String>() : (Set<String>)new HashSet<String>();
  final byte[] b=read(file);
  for (int i=0; (i + chunksize) <= b.length; i++) {
    set.add(new String(b,i,chunksize,"UTF-8"));
  }
  return set;
}
 

Example 60

From project ciel-java, under directory /examples/skyhout/src/java/skywriting/examples/skyhout/pagerank/.

Source file: PageRankSortReduceTask.java

  29 
vote

@Override public Set<Integer> combineInit(IntArrayWritable initVal){
  Set<Integer> ret=new TreeSet<Integer>();
  for (  int x : initVal.get()) {
    ret.add(x);
  }
  return ret;
}
 

Example 61

From project Citizens, under directory /src/guard/net/citizensnpcs/guards/flags/.

Source file: FlagSorter.java

  29 
vote

private TreeSet<FlagInfo> getSortedFlags(FlagType type,Collection<String> toProcess){
  Map<String,FlagInfo> source=list.getFlags(type);
  List<FlagInfo> processed=new ArrayList<FlagInfo>();
  for (  String string : toProcess) {
    if (source.get(string) == null) {
      throw new IllegalArgumentException("source didn't contain a corresponding flag");
    }
    processed.add(source.get(string));
  }
  TreeSet<FlagInfo> sorted=Sets.newTreeSet(priorityComparer);
  sorted.addAll(processed);
  return sorted;
}
 

Example 62

From project Cloud9, under directory /src/dist/edu/umd/cloud9/example/ir/.

Source file: BooleanRetrieval.java

  29 
vote

public void performAND(){
  Set<Integer> s1=stack.pop();
  Set<Integer> s2=stack.pop();
  Set<Integer> sn=new TreeSet<Integer>();
  for (  int n : s1) {
    if (s2.contains(n)) {
      sn.add(n);
    }
  }
  stack.push(sn);
}
 

Example 63

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/grabber/.

Source file: Analyser.java

  29 
vote

private SortedSet<DatasetMetadata> buildInDatabaseMetadata(){
  TreeSet<DatasetMetadata> inDatabase=new TreeSet<DatasetMetadata>(ORDER_BY_BASE_PATH_AND_TIME_AND_ID);
  EntityManager em=emf.createEntityManager();
  try {
    TypedQuery<DatasetMetadata> query=em.createQuery("from DatasetMetadata m where m.facilityName = :name",DatasetMetadata.class);
    query.setParameter("name",getFacility().getFacilityName());
    inDatabase.addAll(query.getResultList());
  }
  finally {
    em.close();
  }
  return inDatabase;
}
 

Example 64

From project cmsandroid, under directory /src/com/zia/freshdocs/preference/.

Source file: CMISPreferencesManager.java

  29 
vote

public Collection<CMISHost> getAllPreferences(Context ctx){
  Collection<CMISHost> results=new TreeSet<CMISHost>();
  Map<String,CMISHost> prefs=readPreferences(ctx);
  if (prefs.size() == 0) {
    initDefaultPrefs(ctx);
    prefs=readPreferences(ctx);
  }
  if (prefs != null) {
    results.addAll(prefs.values());
    results.add(createAddServer(ctx));
  }
  return results;
}
 

Example 65

From project codjo-broadcast, under directory /codjo-broadcast-common/src/test/java/net/codjo/broadcast/common/util/.

Source file: AbstractDependencyTestCase.java

  29 
vote

/** 
 * Verifie que le package <code>currentPackage</code> n'a comme d?endance directe seulement les package se trouvant dans <code>dependsUpon</code>.
 * @param currentPackage Le package a verifier (ex : "net.codjo.orbis")
 * @param dependsUpon    Tableau de package.
 * @throws IllegalArgumentException TODO
 */
protected void assertDependency(String currentPackage,String[] dependsUpon){
  jdepend.analyze();
  JavaPackage testedPack=jdepend.getPackage(currentPackage);
  if (testedPack == null) {
    throw new IllegalArgumentException("Package " + currentPackage + " est inconnu");
  }
  SortedSet<String> trueDependency=new TreeSet<String>();
  for (  Object object : testedPack.getEfferents()) {
    JavaPackage obj=(JavaPackage)object;
    if (!obj.getName().startsWith("java")) {
      trueDependency.add(obj.getName());
    }
  }
  List wantedDepency=Arrays.asList(dependsUpon);
  if (!trueDependency.containsAll(wantedDepency) || !wantedDepency.containsAll(trueDependency)) {
    StringWriter strWriter=new StringWriter();
    doTrace(currentPackage,dependsUpon,new PrintWriter(strWriter));
    fail("Contraintes de Dependance non respect? : \n" + strWriter.toString());
  }
}
 

Example 66

From project codjo-control, under directory /codjo-control-common/src/main/java/net/codjo/control/common/.

Source file: Plan.java

  29 
vote

public void addStep(Step step){
  if (steps == null) {
    steps=new TreeSet<Step>(new ByAscendigPriority());
  }
  steps.add(step);
}
 

Example 67

From project codjo-data-process, under directory /codjo-data-process-server/src/main/java/net/codjo/dataprocess/server/kernel/.

Source file: TreatmentLauncher.java

  29 
vote

public static String getNotResolvableArguments(Connection con,int repositoryId,ExecutionListModel executionListModel,DataProcessContext context){
  SortedSet<String> parametersList=new TreeSet<String>();
  List<UserTreatment> userTreatmentList=UserTreatment.orderList(UserTreatment.buildUserTrtListWithPriority(executionListModel.getPriorityMap()));
  try {
    for (    UserTreatment userTrt : userTreatmentList) {
      TreatmentModel trtModel=Repository.getTreatmentById(con,repositoryId,userTrt.getId());
      AbstractTreatment currentTrt=null;
      try {
        currentTrt=TreatmentFactory.buildTreatment(con,trtModel,repositoryId,executionListModel);
      }
 catch (      TreatmentException ex) {
        parametersList.add(ex.getLocalizedMessage());
      }
      if (currentTrt != null) {
        parametersList.addAll(currentTrt.getNotResolvableArguments(context));
      }
    }
  }
 catch (  TreatmentException ex) {
    parametersList.add(ex.getLocalizedMessage());
  }
  List<String> list=new ArrayList<String>();
  list.addAll(parametersList);
  return new ListCodec().encode(list);
}
 

Example 68

From project codjo-segmentation, under directory /codjo-segmentation-server/src/test/java/net/codjo/segmentation/server/blackboard/.

Source file: JdbcBlackboardParticipantTestCase.java

  29 
vote

public void test_blackboardDescription() throws Exception {
  T participant=createParticipant();
  DFService.AgentDescription description=((ParticipantWrapperBehaviour)participant.toBehaviour()).getBlackBoardDescription();
  Set<String> result=new TreeSet<String>();
  Iterator iterator=description.getAllServices();
  while (iterator.hasNext()) {
    DFService.ServiceDescription serviceDescription=(DFService.ServiceDescription)iterator.next();
    result.add(serviceDescription.getType());
  }
  Set<String> expected=new TreeSet<String>();
  expected.addAll(Arrays.asList(getListenedBlackboardDescriptionTypes()));
  assertEquals(expected.toString(),result.toString());
}