Java Code Examples for java.util.SortedSet

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 collections-generic, under directory /src/java/org/apache/commons/collections15/set/.

Source file: SynchronizedSortedSet.java

  19 
vote

public SortedSet<E> subSet(E fromElement,E toElement){
synchronized (lock) {
    SortedSet set=getSortedSet().subSet(fromElement,toElement);
    return new SynchronizedSortedSet<E>(set,lock);
  }
}
 

Example 2

From project dawn-isencia, under directory /com.isencia.passerelle.commons/src/main/java/com/isencia/util/swing/components/.

Source file: JListDataExchangePanel.java

  18 
vote

public static void main(String[] args){
  SortedSet so1=new TreeSet();
  so1.add("first");
  so1.add("second");
  so1.add("third");
  SortedSet so2=new TreeSet();
  SortedMutableListModel s1=new SortedMutableListModel(so1);
  SortedMutableListModel s2=new SortedMutableListModel(so2);
  JListDataExchangePanel dataEx=new JListDataExchangePanel(s1,s2,"source","dest");
  JFrame frame=new JFrame();
  frame.getContentPane().add(dataEx);
  frame.pack();
  frame.setVisible(true);
}
 

Example 3

From project eclipse.pde.build, under directory /org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/.

Source file: FilteringState.java

  18 
vote

public boolean addBundleDescription(BundleDescription toAdd){
  if (allPlugins == null) {
    return super.addBundleDescription(toAdd);
  }
  SortedSet includedMatches=allPlugins.subSet(new ReachablePlugin(toAdd.getSymbolicName(),ReachablePlugin.WIDEST_RANGE),new ReachablePlugin(toAdd.getSymbolicName(),ReachablePlugin.NARROWEST_RANGE));
  for (Iterator iterator=includedMatches.iterator(); iterator.hasNext(); ) {
    ReachablePlugin constraint=(ReachablePlugin)iterator.next();
    if (constraint.getRange().isIncluded(toAdd.getVersion()))     return super.addBundleDescription(toAdd);
  }
  return false;
}
 

Example 4

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

Source file: HttpParameters.java

  17 
vote

public SortedSet<String> put(String key,SortedSet<String> values,boolean percentEncode){
  if (percentEncode) {
    remove(key);
    for (    String v : values) {
      put(key,v,true);
    }
    return get(key);
  }
 else {
    return wrappedMap.put(key,values);
  }
}
 

Example 5

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

Source file: ConfigurationInspector.java

  16 
vote

public SortedSet<ConfigRecord<?>> inspect(ConfigurationFactory configurationFactory){
  ImmutableSortedSet.Builder<ConfigRecord<?>> builder=ImmutableSortedSet.naturalOrder();
  for (  ConfigurationProvider<?> configurationProvider : configurationFactory.getConfigurationProviders()) {
    builder.add(ConfigRecord.createConfigRecord(configurationProvider));
  }
  return builder.build();
}
 

Example 6

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

Source file: AbstractMetaAnalysis.java

  15 
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 7

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Egg/.

Source file: EggPermissionManager.java

  15 
vote

/** 
 * Get the list of every EggType that the player have access to.
 * @param player used to check the permissions
 * @return
 */
public SortedSet<String> getEggTypeNames(final Player player){
  final SortedSet<String> result=new TreeSet<String>();
  for (  final Entry<Class<? extends EggType<?>>,Permission> entry : permissions.entrySet()) {
    if (entry.getValue() == null) {
      result.add(entry.getKey().getSimpleName());
      continue;
    }
    if (!PermissionManager.hasPerm(player,entry.getValue(),false)) {
      continue;
    }
    result.add(entry.getKey().getSimpleName());
  }
  return result;
}
 

Example 8

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

Source file: SimpleLocalRepositoryManager.java

  15 
vote

String getRepositoryKey(RemoteRepository repository,String context){
  String key;
  if (repository.isRepositoryManager()) {
    StringBuilder buffer=new StringBuilder(128);
    buffer.append(repository.getId());
    buffer.append('-');
    SortedSet<String> subKeys=new TreeSet<String>();
    for (    RemoteRepository mirroredRepo : repository.getMirroredRepositories()) {
      subKeys.add(mirroredRepo.getId());
    }
    SimpleDigest digest=new SimpleDigest();
    digest.update(context);
    for (    String subKey : subKeys) {
      digest.update(subKey);
    }
    buffer.append(digest.digest());
    key=buffer.toString();
  }
 else {
    key=repository.getId();
  }
  return key;
}
 

Example 9

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

Source file: Authenticator.java

  15 
vote

/** 
 * Adds a general application privilege for a specific user
 * @throws CantDoThatException If privilege being assigned is MASTER but the user already has other privileges.
 */
protected synchronized void addUserPrivilege(AppUserInfo appUser,PrivilegeType privilegeType) throws CantDoThatException {
  if (privilegeType.equals(PrivilegeType.MASTER)) {
    SortedSet<AppRoleInfo> rolesForUser=this.getRolesForUser(appUser);
    if (rolesForUser.size() > 0) {
      throw new CantDoThatException("If adding a MASTER privilege, the user can't be a member of any roles. User '" + appUser + "' is a member of roles: "+ rolesForUser);
    }
    Set<UserGeneralPrivilegeInfo> userPrivileges=this.getPrivilegesForUser(appUser);
    if (userPrivileges.size() > 0) {
      throw new CantDoThatException("If adding a MASTER privilege, the user musn't have any other privileges. User '" + appUser + "' already has privileges: "+ userPrivileges);
    }
  }
  UserGeneralPrivilegeInfo userPrivilege=new UserGeneralPrivilege(appUser,privilegeType);
  HibernateUtil.currentSession().save(userPrivilege);
  this.getUserPrivilegesDirect().add(userPrivilege);
}
 

Example 10

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

Source file: DefaultTypeAdapters.java

  15 
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 11

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

Source file: AbstractMultimap.java

  15 
vote

private Collection<V> unmodifiableCollectionSubclass(Collection<V> collection){
  if (collection instanceof SortedSet) {
    return Collections.unmodifiableSortedSet((SortedSet<V>)collection);
  }
 else   if (collection instanceof Set) {
    return Collections.unmodifiableSet((Set<V>)collection);
  }
 else   if (collection instanceof List) {
    return Collections.unmodifiableList((List<V>)collection);
  }
 else {
    return Collections.unmodifiableCollection(collection);
  }
}
 

Example 12

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

Source file: AreaCodeMap.java

  15 
vote

/** 
 * Returns the description of the geographical area the  {@code number} corresponds to.
 * @param number  the phone number to look up
 * @return  the description of the geographical area
 */
String lookup(PhoneNumber number){
  int numOfEntries=areaCodeMapStorage.getNumOfEntries();
  if (numOfEntries == 0) {
    return "";
  }
  long phonePrefix=Long.parseLong(number.getCountryCode() + phoneUtil.getNationalSignificantNumber(number));
  int currentIndex=numOfEntries - 1;
  SortedSet<Integer> currentSetOfLengths=areaCodeMapStorage.getPossibleLengths();
  while (currentSetOfLengths.size() > 0) {
    Integer possibleLength=currentSetOfLengths.last();
    String phonePrefixStr=String.valueOf(phonePrefix);
    if (phonePrefixStr.length() > possibleLength) {
      phonePrefix=Long.parseLong(phonePrefixStr.substring(0,possibleLength));
    }
    currentIndex=binarySearch(0,currentIndex,phonePrefix);
    if (currentIndex < 0) {
      return "";
    }
    int currentPrefix=areaCodeMapStorage.getPrefix(currentIndex);
    if (phonePrefix == currentPrefix) {
      return areaCodeMapStorage.getDescription(currentIndex);
    }
    currentSetOfLengths=currentSetOfLengths.headSet(possibleLength);
  }
  return "";
}
 

Example 13

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

Source file: Polyline.java

  15 
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 14

From project atlas, under directory /src/test/java/com/ning/atlas/.

Source file: TestJRubyTemplateParser.java

  15 
vote

@Test public void testExternalSystem() throws Exception {
  JRubyTemplateParser p=new JRubyTemplateParser();
  Template t=p.parseSystem(new File("src/test/ruby/ex1/system-template-with-external.rb")).get(0);
  Environment env=p.parseEnvironment(new File("src/test/ruby/ex1/env-with-listener.rb")).get(0);
  SystemMap map=t.normalize(env);
  SortedSet<Host> hosts=Sets.newTreeSet(new Comparator<Host>(){
    @Override public int compare(    Host host,    Host host1){
      return host.getId().toExternalForm().compareTo(host1.getId().toExternalForm());
    }
  }
);
  hosts.addAll(map.findLeaves());
  assertThat(hosts.size(),equalTo(3));
  Iterator<Host> itty=hosts.iterator();
  Host one=itty.next();
  System.out.println(one.getId());
  Host two=itty.next();
  System.out.println(two.getId());
  Host three=itty.next();
  System.out.println(three.getId());
}
 

Example 15

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

Source file: Histogram.java

  15 
vote

public TreeMapSegmenter(SortedSet<T> leftEndpoints){
  if (leftEndpoints.isEmpty()) {
    throw new IllegalArgumentException("Endpoints must not be empty: " + leftEndpoints);
  }
  int i=0;
  for (  T t : leftEndpoints) {
    index.put(t,i++);
  }
}
 

Example 16

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

Source file: CollectionRecipe.java

  15 
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 17

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

Source file: OSGiFrameworkContentProvider.java

  15 
vote

public void inputChanged(Viewer viewer,Object oldInput,Object newInput){
  frameworks.clear();
  Workspace workspace=(Workspace)newInput;
  IConfigurationElement[] configElements=Platform.getExtensionRegistry().getConfigurationElementsFor(Plugin.PLUGIN_ID,"osgiFrameworks");
  for (  IConfigurationElement element : configElements) {
    String frameworkName=element.getAttribute("name");
    String bsn=element.getAttribute("bsn");
    URL iconUrl=null;
    String iconPath=element.getAttribute("icon");
    if (iconPath != null) {
      Bundle contributorBundle=BundleUtils.findBundle(Plugin.getDefault().getBundleContext(),element.getContributor().getName(),null);
      if (contributorBundle != null)       iconUrl=contributorBundle.getEntry(iconPath);
    }
    List<RepositoryPlugin> repositories=(workspace != null) ? workspace.getRepositories() : Collections.<RepositoryPlugin>emptyList();
    for (    RepositoryPlugin repo : repositories) {
      try {
        SortedSet<Version> versions=repo.versions(bsn);
        if (versions != null)         for (        Version version : versions) {
          try {
            File framework=repo.get(bsn,version,null);
            if (framework != null)             frameworks.add(new OSGiFramework(frameworkName,bsn,version,iconUrl));
          }
 catch (          Exception e) {
            logger.logError(String.format("Error finding repository entry for OSGi framework %s, version %s.",bsn,version.toString()),e);
          }
        }
      }
 catch (      Exception e) {
        logger.logError(String.format("Error searching repository for OSGi framework %s.",bsn),e);
      }
    }
  }
}
 

Example 18

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

Source file: MoreLikeThisCategorizer.java

  15 
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 19

From project Carolina-Digital-Repository, under directory /persistence/src/main/java/edu/unc/lib/dl/util/.

Source file: ContainerContentsHelper.java

  15 
vote

private static void replaceContent(Document result,SortedSet<String[]> records){
  Element parentDiv=result.getRootElement().getChild("div",JDOMNamespaceUtil.METS_NS);
  parentDiv.removeContent();
  int ord=1;
  for (  String[] record : records) {
    Element el=new Element("div",parentDiv.getNamespace()).setAttribute("ID",record[0]).setAttribute("ORDER",String.valueOf(ord));
    ord++;
    parentDiv.addContent(el);
  }
}
 

Example 20

From project ceylon-module-resolver, under directory /api/src/main/java/com/redhat/ceylon/cmr/api/.

Source file: ModuleSearchResult.java

  15 
vote

public ModuleDetails(String name,String doc,String license,SortedSet<String> authors,SortedSet<String> versions){
  this.name=name;
  this.doc=toNull(doc);
  this.license=toNull(license);
  this.authors.addAll(authors);
  this.versions.addAll(versions);
}
 

Example 21

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

Source file: BoardView.java

  15 
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 22

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/database/.

Source file: DatabaseTable.java

  15 
vote

private String formatDeleteEquals(Connection connection,String separator) throws SQLException {
  SortedSet<String> keys=Sets.newTreeSet();
  String[] primaryKeys=getPrimaryKeyColumns(connection);
  for (  String key : primaryKeys) {
    keys.add(key + " = ?");
  }
  return StringUtilities.implodeItems(Lists.newArrayList(keys),separator);
}
 

Example 23

From project closure-templates, under directory /java/src/com/google/template/soy/jssrc/internal/.

Source file: GenJsCodeVisitor.java

  15 
vote

/** 
 * Helper for visitSoyFileNode(SoyFileNode) to add code to define JS namespaces.
 * @param soyFile The node we're visiting.
 */
private void addCodeToDefineJsNamespaces(SoyFileNode soyFile){
  SortedSet<String> jsNamespaces=Sets.newTreeSet();
  for (  TemplateNode template : soyFile.getChildren()) {
    String templateName=template.getTemplateName();
    Matcher dotMatcher=DOT.matcher(templateName);
    while (dotMatcher.find()) {
      jsNamespaces.add(templateName.substring(0,dotMatcher.start()));
    }
  }
  for (  String jsNamespace : jsNamespaces) {
    boolean hasDot=jsNamespace.indexOf('.') >= 0;
    if (jsSrcOptions.shouldDeclareTopLevelNamespaces() || hasDot) {
      jsCodeBuilder.appendLine("if (typeof ",jsNamespace," == 'undefined') { ",(hasDot ? "" : "var "),jsNamespace," = {}; }");
    }
  }
}
 

Example 24

From project Cloud9, under directory /src/test/edu/umd/cloud9/util/fd/.

Source file: Int2IntFrequencyDistributionTest.java

  15 
vote

private void testIterableCommon(Int2IntFrequencyDistribution fd){
  fd.set(1,1);
  fd.set(4,3);
  fd.set(2,4);
  fd.set(5,7);
  fd.set(6,9);
  fd.set(3,2);
  assertEquals(6,fd.getNumberOfEvents());
  assertEquals(26,fd.getSumOfCounts());
  SortedSet<PairOfInts> list=new TreeSet<PairOfInts>();
  for (  PairOfInts pair : fd) {
    list.add(pair.clone());
  }
  assertEquals(6,list.size());
  Iterator<PairOfInts> iter=list.iterator();
  PairOfInts e=iter.next();
  assertEquals(1,e.getLeftElement());
  assertEquals(1,e.getRightElement());
  e=iter.next();
  assertEquals(2,e.getLeftElement());
  assertEquals(4,e.getRightElement());
  e=iter.next();
  assertEquals(3,e.getLeftElement());
  assertEquals(2,e.getRightElement());
  e=iter.next();
  assertEquals(4,e.getLeftElement());
  assertEquals(3,e.getRightElement());
  e=iter.next();
  assertEquals(5,e.getLeftElement());
  assertEquals(7,e.getRightElement());
  e=iter.next();
  assertEquals(6,e.getLeftElement());
  assertEquals(9,e.getRightElement());
}
 

Example 25

From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/ec2/.

Source file: CredentialsManager.java

  15 
vote

/** 
 * Returns a sorted set with all configured, persisted and runtime credentials. Note: When calling this method for the first time there may be a slight delay.
 * @return a newly created sorted set containing all currently known keypairs.
 */
public SortedSet<Credentials> getAllCredentials(){
  SortedSet<Credentials> sortedSet=Sets.newTreeSet();
  sortedSet.addAll(ImmutableSet.copyOf(configuredCredentials));
  sortedSet.addAll(ImmutableSet.copyOf(getNodeKeyPairs()));
  return sortedSet;
}
 

Example 26

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

Source file: Analyser.java

  15 
vote

private void determineFolderRange(SortedSet<DatasetMetadata> inFolder){
  if (inFolder.isEmpty()) {
    fStart=null;
    fEnd=null;
  }
 else {
    Iterator<DatasetMetadata> it=inFolder.iterator();
    DatasetMetadata ds=it.next();
    fStart=fEnd=ds.getLastFileTimestamp();
    while (it.hasNext()) {
      ds=it.next();
      Date ts=ds.getLastFileTimestamp();
      if (ts.getTime() < fStart.getTime()) {
        fStart=ts;
      }
 else       if (ts.getTime() > fEnd.getTime()) {
        fEnd=ts;
      }
    }
  }
}
 

Example 27

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

Source file: AbstractDependencyTestCase.java

  15 
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 28

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

Source file: TreatmentLauncher.java

  15 
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 29

From project cogroo4, under directory /cogroo-eval/GramEval/src/main/java/cogroo/uima/eval/.

Source file: Stats.java

  15 
vote

public String toFP_TP_Table(){
  StringBuilder sb=new StringBuilder();
  SortedSet<String> set=new TreeSet<String>(new CompRule());
  set.addAll(Categories.getRules());
  sb.append(String.format(" %6s %3s %3s\n","Regra","TP","FP"));
  for (  String type : set) {
    sb.append(String.format(tpfp,type.replace("xml:",""),zeroOrValue(tpForOutcome.get(type)),zeroOrValue(fpForOutcome.get(type))));
  }
  return sb.toString();
}
 

Example 30

From project com.cedarsoft.serialization, under directory /serialization/src/main/java/com/cedarsoft/serialization/ui/.

Source file: VersionMappingsVisualizer.java

  15 
vote

public void visualize(@Nonnull Writer out) throws IOException {
  Collection<Column> columns=new ArrayList<Column>();
  SortedSet<Version> keyVersions=mappings.getMappedVersions();
  List<T> keys=new ArrayList<T>(mappings.getMappings().keySet());
  Collections.sort(keys,comparator);
  for (  T key : keys) {
    VersionMapping mapping=mappings.getMapping(key);
    List<Version> versions=new ArrayList<Version>();
    for (    Version keyVersion : keyVersions) {
      versions.add(mapping.resolveVersion(keyVersion));
    }
    columns.add(new Column(toString.convert(key),versions));
  }
  writeHeadline(columns,out);
  writeSeparator(columns.size(),out);
  writeContent(new ArrayList<Version>(keyVersions),columns,out);
  writeSeparator(columns.size(),out);
}
 

Example 31

From project common_1, under directory /src/main/java/org/powertac/common/.

Source file: Rate.java

  15 
vote

/** 
 * Allows initial publication of HourlyCharge instances within the notification interval.
 */
@StateChange public boolean addHourlyCharge(HourlyCharge newCharge,boolean publish){
  boolean result=false;
  if (isFixed) {
    log.error("Cannot change Rate " + this.toString());
  }
 else {
    Instant now=getCurrentTime();
    long warning=newCharge.getAtTime().getMillis() - now.getMillis();
    if (warning < noticeInterval && !publish) {
      log.warn("Too late (" + now.toString() + ") to change rate for "+ newCharge.getAtTime().toString());
    }
 else {
      if (probe == null) {
        probe=new ProbeCharge(new Instant(0l),0.0);
        System.out.println("add: probe was null");
      }
      probe.setAtTime(newCharge.getAtTime().plus(1000l));
      SortedSet<HourlyCharge> head=rateHistory.headSet(probe);
      if (head != null && head.size() > 0) {
        HourlyCharge item=head.last();
        if (item.getAtTime() == newCharge.getAtTime()) {
          log.debug("remove " + item.toString());
          rateHistory.remove(item);
        }
      }
      newCharge.setRateId(id);
      rateHistory.add(newCharge);
      log.info("Adding HourlyCharge " + newCharge.getId() + " at "+ newCharge.getAtTime()+ " to "+ this.toString());
      result=true;
    }
  }
  return result;
}
 

Example 32

From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/ui/.

Source file: RefspecAddRefsDialog.java

  15 
vote

/** 
 * A constructor
 * @param project  the project
 * @param root     the repository root
 * @param remote   the remote name or url of remote repository
 * @param tags     the set of tags (might be modified if update button is pressed)
 * @param branches the set of branches (might be modified if update button is pressed)
 */
protected RefspecAddRefsDialog(@NotNull Project project,@NotNull VirtualFile root,@NotNull String remote,@NotNull SortedSet<String> tags,@NotNull SortedSet<String> branches){
  super(project,true);
  setTitle(Bundle.getString("addrefspec.title"));
  setOKButtonText(Bundle.getString("addrefspec.button"));
  myProject=project;
  myRoot=root;
  myRemote=remote;
  myTags=tags;
  myBranches=branches;
  updateTree();
  setupGetReferences();
  init();
  setOKActionEnabled(false);
}
 

Example 33

From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/robotstxt/.

Source file: RuleSet.java

  15 
vote

@Override public boolean add(String str){
  SortedSet<String> sub=headSet(str);
  if (!sub.isEmpty() && str.startsWith(sub.last())) {
    return false;
  }
  boolean retVal=super.add(str);
  sub=tailSet(str + "\0");
  while (!sub.isEmpty() && sub.first().startsWith(str)) {
    sub.remove(sub.first());
  }
  return retVal;
}
 

Example 34

From project culvert, under directory /culvert-accumulo/src/main/java/com/bah/culvert/accumulo/database/.

Source file: AccumuloDatabaseAdapter.java

  15 
vote

@Override public void create(String tableName,byte[][] splitKeys,List<CColumn> columns){
  try {
    this.conn.tableOperations().create(tableName);
    SortedSet<Text> partitionKeys=new TreeSet<Text>();
    for (    byte[] split : splitKeys)     partitionKeys.add(new Text(split));
    this.conn.tableOperations().addSplits(tableName,partitionKeys);
  }
 catch (  Exception e) {
    throw Exceptions.asRuntime(e);
  }
}
 

Example 35

From project Diktofon, under directory /app/src/kaljurand_at_gmail_dot_com/diktofon/.

Source file: Recording.java

  15 
vote

public SortedSet<String> getTagsAsSortedSet(){
  if (mTags == null) {
    initTags();
  }
  return new TreeSet<String>(mTags);
}
 

Example 36

From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/ui/internal/search/.

Source file: TraceSearchQueryResults.java

  15 
vote

void updateSearch(IProgramSketch sketch,SortedSet<String> classes,SortedSet<MethodKey> methods,SortedSet<Long> activations,List<Match> matches){
  LinkedList<ITraceModelProxy> proxies=new LinkedList<ITraceModelProxy>();
  if (classes != null) {
    for (    String c : classes) {
      ITraceModelProxy proxy=TraceModelProxy.forClass(sketch.getTraceData(),c);
      proxies.add(proxy);
    }
    if (methods != null) {
      for (      MethodKey mk : methods) {
        proxies.add(TraceModelProxy.forMethod(sketch.getTraceData(),mk));
      }
      if (activations != null) {
        for (        Long a : activations) {
          proxies.add(TraceModelProxy.forActivation(sketch.getTraceData(),a.longValue()));
        }
      }
    }
  }
  this.results.put(sketch,new Result(proxies,matches));
  for (  Object o : listeners.getListeners()) {
    ISearchResultListener listener=(ISearchResultListener)o;
    listener.searchResultChanged(new TraceSearchResultEvent(this,sketch,proxies));
  }
}
 

Example 37

From project DoubleArrayTrie, under directory /src/main/org/digitalstain/datrie/.

Source file: DoubleArrayTrieImpl.java

  15 
vote

/** 
 * @see org.digitalstain.datrie.AbstractDoubleArrayTrie#nextAvailableMove(java.util.SortedSet)
 */
@Override protected int nextAvailableMove(SortedSet<Integer> values){
  if (values.size() == 1) {
    return nextAvailableHop(values.first());
  }
  int minValue=values.first();
  int maxValue=values.last();
  int neededPositions=maxValue - minValue + 1;
  int possible=findConsecutiveFree(neededPositions);
  if (possible - minValue >= 0) {
    return possible - minValue;
  }
  ensureReachableIndex(base.size() + neededPositions);
  return base.size() - neededPositions - minValue;
}
 

Example 38

From project dozer, under directory /core/src/main/java/org/dozer/util/.

Source file: CollectionUtils.java

  15 
vote

public static <T extends Set<?>>Set<?> createNewSet(Class<T> destType){
  Set<Object> result;
  if (SortedSet.class.isAssignableFrom(destType)) {
    result=new TreeSet<Object>();
  }
 else {
    result=new HashSet<Object>();
  }
  return result;
}
 

Example 39

From project EasySOA, under directory /easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/validation/.

Source file: ServiceValidatorComponent.java

  15 
vote

/** 
 * Validates the specified document - If a service, it is validated, but not saved - If another doctype, all services within the document are validated and saved
 */
@Override public ValidationResultList validateServices(CoreSession session,DocumentModel model) throws Exception {
  DocumentService docService=Framework.getService(DocumentService.class);
  boolean modelIsWorkspace=Workspace.DOCTYPE.equals(model.getType());
  DocumentModel workspace=(modelIsWorkspace) ? model : docService.getWorkspace(session,model);
  DocumentModel referenceEnv=docService.findEnvironment(session,(String)workspace.getProperty(Workspace.SCHEMA,Workspace.PROP_REFERENCEDENVIRONMENT));
  DocumentModelList services=null;
  ValidationResultList validationResultList=new ValidationResultList();
  if (referenceEnv != null) {
    DocumentModelList referenceServices=getAllServices(session,referenceEnv);
    if (Service.DOCTYPE.equals(model.getType())) {
      services=new DocumentModelListImpl();
      services.add(model);
    }
 else {
      services=getAllServices(session,model);
    }
    if (services != null) {
      for (      DocumentModel service : services) {
        DocumentModel matchingService=null;
        SortedSet<CorrelationMatch> matches=findCorrelatedServices(session,service,referenceServices);
        if (!matches.isEmpty()) {
          matchingService=matches.first().getDocumentModel();
        }
        ValidationResult validationResult=validateService(session,service,matchingService,model != service);
        validationResultList.add(validationResult);
      }
    }
  }
 else {
    throw new ClientException("No valid reference environment");
  }
  return validationResultList;
}
 

Example 40

From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/.

Source file: MoSyncProject.java

  15 
vote

/** 
 * Returns the ids of all build configurations that has a set of types
 * @param types The types to match against
 * @return The build configurations that have <b>all</b> the specifiedtypes, sorted in case-insensitive alphabetical order.
 */
public SortedSet<String> getBuildConfigurationsOfType(String... types){
  TreeSet<String> result=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  for (  IBuildConfiguration cfg : configurations.values()) {
    boolean doAdd=true;
    for (int i=0; i < types.length; i++) {
      doAdd&=cfg.getTypes().contains(types[i]);
    }
    if (doAdd) {
      result.add(cfg.getId());
    }
  }
  return result;
}
 

Example 41

From project ehour, under directory /eHour-service/src/main/java/net/rrm/ehour/report/service/.

Source file: AggregateReportServiceImpl.java

  15 
vote

public ProjectManagerReport getProjectManagerDetailedReport(DateRange reportRange,Integer projectId){
  ProjectManagerReport report=new ProjectManagerReport();
  SortedSet<AssignmentAggregateReportElement> aggregates;
  List<MailLogAssignment> sentMail;
  Project project;
  List<Integer> assignmentIds=new ArrayList<Integer>();
  List<ProjectAssignment> allAssignments;
  AssignmentAggregateReportElement emptyAggregate;
  project=getProjectDAO().findById(projectId);
  report.setProject(project);
  reportRange=getReportRangeForProject(reportRange,project);
  report.setReportRange(reportRange);
  List<Project> projects=new ArrayList<Project>();
  projects.add(new Project(projectId));
  aggregates=new TreeSet<AssignmentAggregateReportElement>(reportAggregatedDAO.getCumulatedHoursPerAssignmentForProjects(projects,reportRange));
  for (  AssignmentAggregateReportElement aggregate : aggregates) {
    assignmentIds.add(aggregate.getProjectAssignment().getAssignmentId());
  }
  allAssignments=projectAssignmentService.getProjectAssignments(project,reportRange);
  for (  ProjectAssignment assignment : allAssignments) {
    if (!assignmentIds.contains(assignment.getAssignmentId())) {
      emptyAggregate=new AssignmentAggregateReportElement();
      emptyAggregate.setProjectAssignment(assignment);
      aggregates.add(emptyAggregate);
    }
  }
  report.setAggregates(aggregates);
  if (assignmentIds.size() > 0) {
    sentMail=mailService.getSentMailForAssignment(assignmentIds.toArray(new Integer[assignmentIds.size()]));
    report.setSentMail(new TreeSet<MailLogAssignment>(sentMail));
  }
  report.deriveTotals();
  return report;
}
 

Example 42

From project Empire, under directory /core/src/com/clarkparsia/empire/util/.

Source file: BeanReflectUtil.java

  15 
vote

/** 
 * Create an instance of the specifiec collection.  If the type cannot be instantiated directly, such as List, or Set, we'll try and figure out which type of collection is desired and return the standard implementation for that type, for example ArrayList or HashSet.
 * @param theValueType the type of collection to instantiate
 * @return the instantiated collection
 * @throws RuntimeException if there is no way to instantiate any matching collection
 */
public static Collection<Object> instantiateCollectionFromField(Class theValueType){
  try {
    return (Collection<Object>)theValueType.newInstance();
  }
 catch (  Throwable e) {
    if (List.class.isAssignableFrom(theValueType)) {
      return new ArrayList<Object>();
    }
 else     if (Set.class.isAssignableFrom(theValueType)) {
      if (SortedSet.class.isAssignableFrom(theValueType)) {
        return new TreeSet<Object>();
      }
 else {
        return new LinkedHashSet<Object>();
      }
    }
 else     if (Collection.class.equals(theValueType)) {
      return new LinkedHashSet<Object>();
    }
 else {
      throw new RuntimeException("Unknown or unsupported collection type for a field: " + theValueType);
    }
  }
}
 

Example 43

From project en, under directory /src/l1j/server/server/model/.

Source file: L1UltimateBattle.java

  15 
vote

private int nextUbTime(){
  SimpleDateFormat sdf=new SimpleDateFormat("HHmm");
  int nowTime=Integer.valueOf(sdf.format(getRealTime().getTime()));
  SortedSet<Integer> tailSet=_ubTimes.tailSet(nowTime);
  if (tailSet.isEmpty()) {
    tailSet=_ubTimes;
  }
  return tailSet.first();
}
 

Example 44

From project enterprise, under directory /ha/src/test/java/jmx/.

Source file: JmxDocsTest.java

  15 
vote

private void writeAttributesTable(String description,StringBuilder beanInfo,MBeanAttributeInfo[] attributes,boolean nonHtml){
  addNonHtmlCondition(beanInfo,nonHtml);
  beanInfo.append("[options=\"header\", cols=\"20m,36,20m,7,7\"]\n" + "|===\n" + "|Name|Description|Type|Read|Write\n"+ "5.1+^e|").append(description).append('\n');
  SortedSet<String> attributeInfo=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  for (  MBeanAttributeInfo attrInfo : attributes) {
    StringBuilder attributeRow=new StringBuilder(512);
    String type=getType(attrInfo.getType());
    Descriptor descriptor=attrInfo.getDescriptor();
    type=getCompositeType(type,descriptor,nonHtml);
    attributeRow.append('|').append(makeBreakable(attrInfo.getName(),nonHtml)).append('|').append(attrInfo.getDescription().replace('\n',' ')).append('|').append(type).append('|').append(attrInfo.isReadable() ? "yes" : "no").append('|').append(attrInfo.isWritable() ? "yes" : "no").append('\n');
    attributeInfo.add(attributeRow.toString());
  }
  for (  String row : attributeInfo) {
    beanInfo.append(row);
  }
  beanInfo.append("|===\n");
  beanInfo.append(ENDIF);
}
 

Example 45

From project erjang, under directory /src/main/java/erjang/m/ets/.

Source file: EPattern.java

  15 
vote

/** 
 * @param spec
 */
public EPattern(int keyidx,EObject spec){
  this.keyidx=keyidx;
  this.spec=spec;
  SortedSet<Integer> out=new TreeSet<Integer>();
  matcher=spec.compileMatch(out);
  this.out_vars=out.toArray(new Integer[out.size()]);
}
 

Example 46

From project figgo, under directory /src/main/java/br/octahedron/figgo/modules/user/data/.

Source file: UserDAO.java

  15 
vote

/** 
 * Retrieves a collection of  {@link User} that its name or email starts with a term.
 * @param term
 * @return
 */
public Collection<User> getUsersStartingWith(String term){
  Collection<User> searchResultName=this.getAllStartsWith(NAME_ATTRIBUTE,term.toLowerCase());
  Collection<User> searchResultEmail=this.getAllStartsWith(EMAIL_ATTRIBUTE,term.toLowerCase());
  SortedSet<User> result=new TreeSet<User>();
  result.addAll(searchResultEmail);
  result.addAll(searchResultName);
  return result;
}
 

Example 47

From project fitnesse, under directory /src/fitnesse/responders/testHistory/.

Source file: PageHistoryResponderTest.java

  15 
vote

@Test public void pageHistoryShouldHaveStatsForOneTestIfOnePageHistoryFileIsPresent() throws Exception {
  File pageDirectory=addPageDirectory("TestPage");
  addTestResult(pageDirectory,"20090418123103_1_2_3_4");
  history.readHistoryDirectory(resultsDirectory);
  PageHistory pageHistory=history.getPageHistory("TestPage");
  assertEquals(1,pageHistory.size());
  assertEquals(7,pageHistory.maxAssertions());
  SortedSet<Date> dates=pageHistory.datesInChronologicalOrder();
  assertEquals(1,dates.size());
  Date date=dateFormat.parse("20090418123103");
  assertEquals(date,dates.first());
  PageHistory.PassFailBar passFailBar=pageHistory.getPassFailBar(date,50);
  assertEquals(1,passFailBar.getPass());
  assertEquals(6,passFailBar.getFail());
  assertEquals(7,passFailBar.getPassUnits());
  assertEquals(43,passFailBar.getFailUnits());
}
 

Example 48

From project flexymind-alpha, under directory /src/com/flexymind/alpha/parsers/.

Source file: MIDIParser.java

  15 
vote

private static LinkedList<MidiNote> parseFile(MidiFile mFile){
  LinkedList<MidiNote> tempList=new LinkedList<MidiNote>();
  SortedSet<MidiEvent> eventTreeSet=mFile.getTracks().get(1).getEvents();
  for (  MidiEvent event : eventTreeSet) {
    if (isCorrectMidiNote(event)) {
      MidiNote note=new MidiNote(Note.getToneByMidiFileId(((NoteOn)event).getNoteValue()));
      tempList.add(note);
    }
  }
  return tempList;
}
 

Example 49

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/client/.

Source file: OAuth.java

  15 
vote

public UserInfo GetAccessToken(String url){
  UserInfo user=null;
  String verifier=url.substring(url.indexOf("oauth_verifier") + "oauth_verifier=".length());
  httpOauthprovider.setOAuth10a(true);
  try {
    httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
  }
 catch (  Exception e) {
    e.printStackTrace();
    try {
      httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
    }
 catch (    Exception e1) {
      e.printStackTrace();
      try {
        httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
      }
 catch (      Exception e2) {
        e.printStackTrace();
      }
    }
  }
  SortedSet<String> user_id=httpOauthprovider.getResponseParameters().get("user_id");
  if (user_id == null) {
    return null;
  }
  String userId=user_id.first();
  String userKey=httpOauthConsumer.getToken();
  String userSecret=httpOauthConsumer.getTokenSecret();
  user=new UserInfo();
  user.setUserId(userId);
  user.setToken(userKey);
  user.setTokenSecret(userSecret);
  return user;
}
 

Example 50

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/.

Source file: FlumeEventQueue.java

  15 
vote

/** 
 * @return a copy of the set of fileIDs which are currently on the queuewill be normally be used when deciding which data files can be deleted
 */
synchronized SortedSet<Integer> getFileIDs(){
  SortedSet<Integer> fileIDs=new TreeSet<Integer>(backingStore.getReferenceCounts());
  fileIDs.addAll(inflightPuts.getFileIDs());
  fileIDs.addAll(inflightTakes.getFileIDs());
  return fileIDs;
}
 

Example 51

From project Flume-Hive, under directory /src/java/com/cloudera/flume/reporter/charts/google/.

Source file: GoogleHistogramChartGen.java

  15 
vote

private String histoSortFreqs(Histogram<T> h){
  if (h.size() == 0)   return "";
  SortedSet<Pair<T,Integer>> s=h.sorted();
  StringBuilder data=null;
  for (  Pair<T,Integer> p : s) {
    if (data == null) {
      data=new StringBuilder();
      data.append(p.getRight());
    }
 else {
      data.append("," + p.getRight());
    }
  }
  return data.toString();
}
 

Example 52

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/reporter/charts/google/.

Source file: GoogleHistogramChartGen.java

  15 
vote

private String histoSortFreqs(Histogram<T> h){
  if (h.size() == 0)   return "";
  SortedSet<Pair<T,Integer>> s=h.sorted();
  StringBuilder data=null;
  for (  Pair<T,Integer> p : s) {
    if (data == null) {
      data=new StringBuilder();
      data.append(p.getRight());
    }
 else {
      data.append("," + p.getRight());
    }
  }
  return data.toString();
}
 

Example 53

From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.

Source file: ClusterMonitor.java

  15 
vote

private List<SortedMap<String,String>> toMapList(Collection<NodeInfo> nis){
  SortedSet<NodeInfo> nis1=new TreeSet<NodeInfo>(new Comparator<NodeInfo>(){
    @Override public int compare(    NodeInfo o1,    NodeInfo o2){
      return o1.getNodeId() - o2.getNodeId();
    }
  }
);
  nis1.addAll(nis);
  List<SortedMap<String,String>> list=new ArrayList<SortedMap<String,String>>(nis.size());
  for (  NodeInfo ni : nis1)   list.add(toMap(ni));
  return list;
}
 

Example 54

From project gatein-common, under directory /common/src/main/java/org/gatein/common/util/.

Source file: SetMap.java

  15 
vote

protected Collection<V> newCollection(Collection<V> other){
  if (comparator == null) {
    return new HashSet<V>(other);
  }
 else {
    SortedSet<V> set=new TreeSet<V>(comparator);
    set.addAll(other);
    return set;
  }
}
 

Example 55

From project gatein-mop, under directory /core/src/test/java/org/gatein/mop/core/api/content/.

Source file: CustomizationContextComparatorTestCase.java

  15 
vote

public void testRemoveDuplicates(){
  CustomizationContextComparator comparator=new CustomizationContextComparator("foo");
  SortedSet<SimpleCustomizationContext> contexts=new TreeSet<SimpleCustomizationContext>(comparator);
  contexts.add(s2);
  contexts.add(s2);
  assertEquals(1,contexts.size());
}
 

Example 56

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/blueprint/container/support/.

Source file: BlueprintEditorRegistrar.java

  15 
vote

@SuppressWarnings("unchecked") @Override protected Collection createCollection(Class collectionType,int initialCapacity){
  if (!collectionType.isInterface()) {
    try {
      return (Collection)collectionType.newInstance();
    }
 catch (    Exception ex) {
      throw new IllegalArgumentException("Could not instantiate collection class [" + collectionType.getName() + "]: "+ ex.getMessage());
    }
  }
 else   if (List.class.equals(collectionType)) {
    return new ArrayList(initialCapacity);
  }
 else   if (Set.class.equals(collectionType)) {
    return new LinkedHashSet(initialCapacity);
  }
 else   if (SortedSet.class.equals(collectionType)) {
    return new TreeSet();
  }
 else {
    return new ArrayList(initialCapacity);
  }
}
 

Example 57

From project geronimo-xbean, under directory /xbean-classloader/src/test/java/org/apache/xbean/classloader/.

Source file: MultiParentClassLoaderTest.java

  15 
vote

/** 
 * Verify that the test jars are valid.
 * @throws Exception if a problem occurs
 */
public void testTestJars() throws Exception {
  for (int i=0; i < files.length; i++) {
    File file=files[i];
    JarFile jarFile=new JarFile(files[i]);
    String urlString="jar:" + file.toURL() + "!/"+ ENTRY_NAME;
    URL url=new URL(files[i].toURL(),urlString);
    assertStreamContains(ENTRY_VALUE + i,url.openStream());
    jarFile.close();
    URLClassLoader urlClassLoader=new URLClassLoader(new URL[]{file.toURL()});
    Class clazz=urlClassLoader.loadClass(CLASS_NAME);
    assertNotNull(clazz);
    assertTrue(SortedSet.class.isAssignableFrom(clazz));
    clazz=urlClassLoader.loadClass(CLASS_NAME + i);
    assertNotNull(clazz);
    assertTrue(SortedSet.class.isAssignableFrom(clazz));
    InputStream in=urlClassLoader.getResourceAsStream(ENTRY_NAME);
    assertStreamContains("Should have found value from parent " + i,ENTRY_VALUE + i,in);
    in=urlClassLoader.getResourceAsStream(ENTRY_NAME + i);
    assertStreamContains("Should have found value from parent " + i,ENTRY_VALUE + i + ENTRY_VALUE,in);
  }
}
 

Example 58

From project gibson, under directory /gibson-core/src/main/java/org/ardverk/gibson/.

Source file: EventUtils.java

  15 
vote

public static Set<String> keywords(Event event){
  if (event == null) {
    throw new NullPointerException("event");
  }
  SortedSet<String> keywords=new TreeSet<>();
  String message=event.getMessage();
  if (message != null) {
    keywords(message,keywords);
  }
  Condition condition=event.getCondition();
  if (condition != null) {
    keywords(condition,keywords);
  }
  String marker=event.getMarker();
  if (marker != null) {
    keywords(marker,keywords);
  }
  if (keywords.isEmpty()) {
    return null;
  }
  return keywords;
}
 

Example 59

From project google-gson, under directory /src/main/java/com/google/gson/.

Source file: DefaultTypeAdapters.java

  15 
vote

@SuppressWarnings("unchecked") 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),true);
  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,true);
  map.registerForTypeHierarchy(Queue.class,queueCreator,true);
  map.registerForTypeHierarchy(Set.class,setCreator,true);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator,true);
  map.makeUnmodifiable();
  return map;
}
 

Example 60

From project gradle-msbuild-plugin, under directory /src/main/groovy/org/gradle/api/reporting/internal/.

Source file: TaskReportContainer.java

  15 
vote

@Input public SortedSet<String> getEnabledReportNames(){
  return CollectionUtils.collect(getEnabled(),new TreeSet<String>(),new Transformer<String,Report>(){
    public String transform(    Report report){
      return report.getName();
    }
  }
);
}
 

Example 61

From project graph2tab, under directory /src/main/java/org/isatools/tablib/export/graph2tab/.

Source file: LayersBuilder.java

  15 
vote

/** 
 * Set the layer for a node, which means all the two internal structures used for that are updated.
 */
private void setLayer(Node node,int layer){
  Integer oldLayer=node2Layer.get(node);
  if (oldLayer != null) {
    SortedSet<Node> oldLayerNodes=layer2Nodes.get(oldLayer);
    if (oldLayerNodes.remove(node) && oldLayerNodes.isEmpty() && oldLayer == maxLayer)     maxLayer--;
  }
  SortedSet<Node> lnodes=layer2Nodes.get(layer);
  if (lnodes == null) {
    lnodes=new TreeSet<Node>();
    layer2Nodes.put(layer,lnodes);
  }
  lnodes.add(node);
  node2Layer.put(node,layer);
  if (layer > maxLayer)   maxLayer=layer;
}
 

Example 62

From project gson, under directory /gson/src/main/java/com/google/gson/.

Source file: DefaultTypeAdapters.java

  15 
vote

@SuppressWarnings("unchecked") 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),true);
  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,true);
  map.registerForTypeHierarchy(Queue.class,queueCreator,true);
  map.registerForTypeHierarchy(Set.class,setCreator,true);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator,true);
  map.makeUnmodifiable();
  return map;
}