java.util.TreeSet Java Examples

The following examples show how to use java.util.TreeSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShoulderPeaksFilter.java    From mzmine2 with GNU General Public License v2.0 7 votes vote down vote up
/**
 * This function remove peaks encountered in the lateral of a main peak (currentCandidate) that
 * are considered as garbage, for example FTMS shoulder peaks.
 * 
 * First calculates a peak model (Gauss, Lorenzian, etc) defined by peakModelName parameter, with
 * the same position (m/z) and height (intensity) of the currentCandidate, and the defined
 * resolution (resolution parameter). Second search and remove all the lateral peaks that are
 * under the curve of the modeled peak.
 * 
 */
private static void removeLateralPeaks(DataPoint currentCandidate, TreeSet<DataPoint> candidates,
    PeakModel peakModel, double resolution) {

  // We set our peak model with same position(m/z), height(intensity) and
  // resolution of the current peak
  peakModel.setParameters(currentCandidate.getMZ(), currentCandidate.getIntensity(), resolution);

  // We search over all peak candidates and remove all of them that are
  // under the curve defined by our peak model
  Iterator<DataPoint> candidatesIterator = candidates.iterator();
  while (candidatesIterator.hasNext()) {

    DataPoint lateralCandidate = candidatesIterator.next();

    // Condition in x domain (m/z)
    if ((lateralCandidate.getIntensity() < peakModel.getIntensity(lateralCandidate.getMZ()))) {
      candidatesIterator.remove();
    }
  }

}
 
Example #2
Source File: FloatDataset.java    From january with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public FloatDataset getUniqueItems() {
	Set<Float> set = new TreeSet<Float>(); // CLASS_TYPE
	IndexIterator it = getIterator();
	while (it.hasNext()) {
		set.add(data[it.index]);
	}

	FloatDataset u = new FloatDataset(set.size()); // CLASS_TYPE
	int i = 0;
	float[] udata = u.getData(); // PRIM_TYPE
	for (Float v : set) { // CLASS_TYPE
		udata[i++] = v;
	}
	return u;
}
 
Example #3
Source File: IndependenceScorer.java    From blip with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void prepare() {
    super.prepare();

    // Initialize everything
    closed = new TCustomHashSet<int[]>(new ArrayHashingStrategy()); // Parent set already seen
    open = new TreeSet<OpenParentSet>(); // Parent set to evaluate

    if (max_pset_size <= 1) {
        return;
    }

    // Consider all two-parent set for evaluation
    for (int i = 0; i < parents.length; i++) {
        for (int j = i + 1; j < parents.length; j++) {

            addParentSetToEvaluate(new int[] { parents[i]}, parents[j],
                    null);
        }
    }

}
 
Example #4
Source File: GroupNodeTest.java    From GDH with MIT License 6 votes vote down vote up
@Test
public void testDifferentGroup() {
    Node n1 = new Node(ip1, port1);
    Node n2 = new Node(ip1, port2);

    Node n3 = new Node(ip1, port1);
    Node n4 = new Node(ip1, "3002");

    TreeSet<Node> set = new TreeSet<>();
    TreeSet<Node> set2 = new TreeSet<>();
    set.add(n1);
    set.add(n2);
    set2.add(n3);
    set2.add(n4);
    Group g1 = new Group(new Configuration(), n1, n2);
    Group g2 = new Group(new Configuration(), n3, n4);
    Assert.assertTrue(n1.equals(n3));
    Assert.assertTrue(g1.hashCode() != g2.hashCode());
    Assert.assertTrue(!g1.equals(g2));
}
 
Example #5
Source File: CommonProxyFactory.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
private static SortedSet<MethodDescriptor> getSortedMethods(final Class<?> type) {
  SortedSet<MethodDescriptor> methods = new TreeSet<MethodDescriptor>(METHOD_COMPARATOR);

  if (type == null) {
    return methods;
  }

  final Method[] declaredMethods = type.getDeclaredMethods();

  if (declaredMethods.length > 256) {
    throw new IllegalArgumentException("Can't proxy that many methods on a single instance!");
  }

  for (Method declaredMethod : declaredMethods) {
    methods.add(MethodDescriptor.of(declaredMethod));
  }

  if (methods.size() != declaredMethods.length) {
    throw new AssertionError("Ouch... looks like that didn't work!");
  }
  return methods;
}
 
Example #6
Source File: LauncherLaunchInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private Set<String> extractLibJarNamesFromURLs(URL[] urls) {
    if (urls == null) {
        return Collections.emptySet();
    }
    Set<String> libJarNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    for (URL url : urls) {
        try {
            String libJarName = extractLibJarName(url);
            if (libJarName.length() > 0) {
                libJarNames.add(libJarName);
            }
        } catch (Exception e) {
            // safety net
            logger.warn("Error extracting library name", e);
        }
    }
    return libJarNames;
}
 
Example #7
Source File: MapperFactory.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Mapper getMapper(String... mappingFiles) {
   Set<String> mappingSet = new TreeSet();
   mappingSet.addAll(Arrays.asList(mappingFiles));
   MessageDigest complete = DigestUtils.getMd5Digest();
   Iterator i$ = mappingSet.iterator();

   while(i$.hasNext()) {
      String mapping = (String)i$.next();
      complete.update(mapping.getBytes());
   }

   String key = new String(Base64.encode(complete.digest()));
   if (!cache.containsKey(key)) {
      Map<String, Object> options = new HashMap();
      options.put("be.ehealth.technicalconnector.mapper.configfiles", mappingFiles);

      try {
         cache.put(key, helper.getImplementation(options));
      } catch (TechnicalConnectorException var6) {
         throw new IllegalArgumentException(var6);
      }
   }

   return (Mapper)cache.get(key);
}
 
Example #8
Source File: HttpManagementUtil.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public static String getRequestPrincipals(HttpServletRequest httpRequest)
{
    HttpSession session = httpRequest.getSession(false);
    if (session != null)
    {
        Subject subject = HttpManagementUtil.getAuthorisedSubject(httpRequest);
        if (subject != null)
        {

            Set<Principal> principalSet = subject.getPrincipals();
            if (!principalSet.isEmpty())
            {
                TreeSet<String> principalNames = new TreeSet<>();
                for (Principal principal : principalSet)
                {
                    principalNames.add(principal.getName());
                }
                return principalNames.toString();
            }
        }
    }
    return null;
}
 
Example #9
Source File: ForwardRegisterTrackingTransformationProviderTest.java    From binnavi with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransformSubIdenticalInput() {
  final RegisterTrackingTransformationProvider transformationProvider =
      new RegisterTrackingTransformationProvider(new RegisterTrackingOptions(false,
          new TreeSet<String>(), false, AnalysisDirection.DOWN));
  final ReilInstruction instruction =
      ReilHelpers.createSub(0, OperandSize.DWORD, "ecx", OperandSize.DWORD, "ecx",
          OperandSize.DWORD, "eax");
  final Pair<RegisterSetLatticeElement, RegisterSetLatticeElement> transformationResult =
      transformationProvider.transformSub(instruction, createTaintedState("ecx", "eax"));

  Assert.assertNull(transformationResult.second());

  transformationResult.first().onInstructionExit();

  Assert.assertTrue(transformationResult.first().getNewlyTaintedRegisters().isEmpty());
  Assert.assertTrue(transformationResult.first().getReadRegisters().isEmpty());
  Assert.assertFalse(transformationResult.first().getTaintedRegisters().contains("eax"));
  Assert.assertTrue(transformationResult.first().getTaintedRegisters().contains("ecx"));
  Assert.assertTrue(transformationResult.first().getUntaintedRegisters().contains("eax"));
  Assert.assertTrue(transformationResult.first().getUpdatedRegisters().isEmpty());
}
 
Example #10
Source File: UserDictionaryList.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the entries that allow the user to go into the user dictionary for each locale.
 * @param userDictGroup The group to put the settings in.
 */
protected void createUserDictSettings(final PreferenceGroup userDictGroup) {
    final Activity activity = getActivity();
    userDictGroup.removeAll();
    final TreeSet<String> localeSet =
            UserDictionaryList.getUserDictionaryLocalesSet(activity);

    if (localeSet.size() > 1) {
        // Have an "All languages" entry in the languages list if there are two or more active
        // languages
        localeSet.add("");
    }

    if (localeSet.isEmpty()) {
        userDictGroup.addPreference(createUserDictionaryPreference(null));
    } else {
        for (String locale : localeSet) {
            userDictGroup.addPreference(createUserDictionaryPreference(locale));
        }
    }
}
 
Example #11
Source File: DependencyNode.java    From depgraph-maven-plugin with Apache License 2.0 6 votes vote down vote up
private DependencyNode(Artifact artifact, NodeResolution resolution, String effectiveVersion) {
  if (artifact == null) {
    throw new NullPointerException("Artifact must not be null");
  }

  this.effectiveVersion = effectiveVersion;
  this.scopes = new TreeSet<>();
  this.classifiers = new TreeSet<>();
  this.types = new TreeSet<>();
  this.artifact = artifact;
  this.resolution = resolution;
  if (artifact.getScope() != null) {
    this.scopes.add(artifact.getScope());
  }
  this.types.add(artifact.getType());

  if (!isNullOrEmpty(artifact.getClassifier())) {
    this.classifiers.add(artifact.getClassifier());
  }
}
 
Example #12
Source File: PostgreSqlRule.java    From booties with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all the resource names contained in this file system folder.
 *
 * @param scanRootLocation
 *            The root location of the scan on disk.
 * @param folder
 *            The folder to look for resources under on disk.
 * @return The resource names;
 * @throws IOException
 *             when the folder could not be read.
 */
private Set<String> findResourceNamesFromFileSystem(String scanRootLocation, File folder) throws IOException {
    LOG.debug("Scanning for resources in path: " + folder.getPath() + " (" + scanRootLocation + ")");

    Set<String> resourceNames = new TreeSet<String>();

    File[] files = folder.listFiles();
    for (File file : files) {
        if (file.canRead()) {
            if (file.isDirectory()) {
                resourceNames.addAll(findResourceNamesFromFileSystem(scanRootLocation, file));
            } else {
                resourceNames.add(file.getPath());
            }
        }
    }

    return resourceNames;
}
 
Example #13
Source File: GetServicePort.java    From openshift-ping with Apache License 2.0 6 votes vote down vote up
private Set<DnsRecord> getDnsRecords(String serviceName) throws Exception {
    Set<DnsRecord> dnsRecords = new TreeSet<DnsRecord>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    env.put(Context.PROVIDER_URL, "dns:");
    env.put("com.sun.jndi.dns.recursion", "false");
    // default is one second, but os skydns can be slow
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    // retries handled by DnsPing
    //env.put("com.sun.jndi.dns.timeout.retries", "4");
    DirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes("_tcp." + serviceName, new String[]{"SRV"});
    if (attrs == null) {
        return dnsRecords;
    }
    NamingEnumeration<?> servers = attrs.get("SRV").getAll();
    while (servers.hasMore()) {
        DnsRecord record = DnsRecord.fromString((String)servers.next());
        dnsRecords.add(record);
    }
    return dnsRecords;
}
 
Example #14
Source File: DateFolderFlagDistributor.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public boolean addInputFile(InputFile inputFile) throws UnusableFileException {
    String path = inputFile.getDirectory();
    long slice = util.getBucket(grouping, path);
    // we should never use default...
    String folder = "default";
    for (String string : folders) {
        if (path.contains(string)) {
            folder = string;
            break;
        }
    }
    DFKey bucket = new DFKey(slice, folder);
    Set<InputFile> bucketList = buckets.get(bucket);
    if (bucketList == null) {
        bucketList = new TreeSet<>(fc.isLifo() ? InputFile.LIFO : InputFile.FIFO);
        buckets.put(bucket, bucketList);
    }
    return bucketList.add(inputFile);
}
 
Example #15
Source File: NumberFormatDialog.java    From tracker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets an array of unit dimensions for all currently selected variables.
 *
 * @return array of unit dimensions
 */
private String[] getCurrentDimensions() {
  TTrack track = TTrack.getTrack(trackID);
  if (track==null) return new String[0];
  Class<? extends TTrack> trackType = getTrackType(track);
	TreeSet<String> dimensions = new TreeSet<String>(); 
int[] indices = variableList.getSelectedIndices();
Object[] selected = new Object[indices.length];
for (int j=0; j<indices.length; j++) {
	selected[j] = displayedNames[indices[j]];
}
for (Object displayedName : selected) {
	String name = realNames.get(displayedName.toString());
		String dim = getVariableDimensions(trackType, name);
		if (dim!=null) {
			dimensions.add(dim);
		}
}
return dimensions.toArray(new String[dimensions.size()]);
}
 
Example #16
Source File: Anaphora.java    From fnlp with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void init(String[][][]stringTag,String str) throws Exception{
	ts = new TreeSet<Entity>();
	llis = new LinkedList<Instance>();
	fc = new FormChanger();
	test = new InstanceSet(cl.getPipe());
	test.loadThruPipes(new AR_Reader(stringTag,str));
	for(int i=0;i<test.size();i++){
		String ss = cl.getStringLabel(test.getInstance(i));
		if(ss.equals("1")){
			llis.add(test.getInstance(i));
		}	
	}
	fc.groupToList(llis);
	fc.getLlsb();
	ts = fc.getTs();
}
 
Example #17
Source File: MainActivity.java    From AnimatedGridView with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_remove) {
        if (agv.getCount() >= 6) {
            TreeSet<Integer> row = new TreeSet<Integer>();
            row.add(0);
            agv.animateDeleteRow(row, 200);
        }

        return true;
    } else if (id == R.id.action_add) {
        LinkedList<Object> items = new LinkedList<Object>();
        items.add(1);
        items.add(2);
        items.add(3);
        items.add(4);
        items.add(5);
        items.add(6);
        agv.animateAddCells(items, 200);
    }
    return super.onOptionsItemSelected(item);
}
 
Example #18
Source File: Percentiles.java    From vanillacore with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance that keeps only the percentiles with values
 * falling within the specified range. All new percentiles are adjusted such
 * that the last value has the 100% percentage.
 * 
 * @param range
 *            the range within which the percentiles will be preserved
 * @return a new instance that keeps only the percentiles falling within the
 *         specified range; or <code>null</code> if no such a percentile
 */
public Percentiles percentiles(ConstantRange range) {
	SortedSet<Constant> sorted = values();
	SortedSet<Constant> contained = new TreeSet<Constant>();
	Constant prev = null;
	for (Constant pct : sorted) {
		if (range.contains(pct)) {
			contained.add(pct);
		} else if (contained.isEmpty())
			prev = pct;
	}
	if (contained.isEmpty())
		return null;
	double prevPercent = prev == null ? 0.0 : pcts.get(prev);
	double totalPercent = pcts.get(contained.last()) - prevPercent;
	Map<Constant, Double> newPcts = new HashMap<Constant, Double>();
	for (Constant p : contained)
		newPcts.put(p, (pcts.get(p) - prevPercent) / totalPercent);
	return new Percentiles(newPcts);
}
 
Example #19
Source File: Class_.java    From unitime with Apache License 2.0 6 votes vote down vote up
public String instructorText(String instructorNameFormat, String separator){
	if (getClassInstructors() == null) return "";
	
	TreeSet sortedInstructors = new TreeSet(new InstructorComparator());
	sortedInstructors.addAll(this.getClassInstructors());

	StringBuffer sb = new StringBuffer();
	
	for (Iterator it = sortedInstructors.iterator(); it.hasNext();) {
		ClassInstructor ci = (ClassInstructor) it.next();
		sb.append(ci.getInstructor().getName(instructorNameFormat));
		if (it.hasNext()) sb.append(separator);
	}
	
	return sb.toString();
}
 
Example #20
Source File: JAXBContextImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder buf = new StringBuilder(Which.which(getClass()) + " Build-Id: " + getBuildId());
    buf.append("\nClasses known to this context:\n");

    Set<String> names = new TreeSet<String>();  // sort them so that it's easy to read

    for (Class key : beanInfoMap.keySet())
        names.add(key.getName());

    for(String name: names)
        buf.append("  ").append(name).append('\n');

    return buf.toString();
}
 
Example #21
Source File: AlertsEngineImpl.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
private TreeSet<Event> processEventsExtensions(TreeSet<Event> events) {
    Set<EventExtension> extensions = extensionsService.getEventExtensions();
    if (!extensions.isEmpty()) {
        for (EventExtension extension : extensions) {
            events = extension.processEvents(events);
        }
    }
    return events;
}
 
Example #22
Source File: ResourceModelImpl.java    From RADL with Apache License 2.0 5 votes vote down vote up
private Collection<String> getResourcesWithSameLocationAndDifferentMethods(Collection<String> resourcesToProcess,
    String resource, String uri, Collection<Method> methods) {
  Collection<String> result = new TreeSet<>();
  result.add(resource);
  for (String otherResource : resourcesToProcess) {
    if (isResourceWithSameLocationAndDifferentMethods(resource, uri, methods, otherResource)) {
      result.add(otherResource);
    }
  }
  return result;
}
 
Example #23
Source File: NetUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve {@link Set} of IPv4 addresses of this host.
 * <p/>
 * @return {@link Set} of IPv4 addresses of this host.
 */
public static Set<Inet4Address> getHostIP4s() {
    Set<Inet4Address> addrs = new TreeSet<>(INET_ADDRESS_COMPARATOR);
    for (InetAddress a : getHostIPs()) {
        if (a instanceof Inet4Address) {
            addrs.add((Inet4Address) a);
        }
    }
    return addrs;
}
 
Example #24
Source File: BenchmarkResultsPrinter.java    From presto with Apache License 2.0 5 votes vote down vote up
private static List<String> getSelectedQueryTagNames(Iterable<Suite> suites, Iterable<BenchmarkQuery> queries)
{
    SortedSet<String> tags = new TreeSet<>();
    for (Suite suite : suites) {
        for (BenchmarkQuery query : suite.selectQueries(queries)) {
            tags.addAll(query.getTags().keySet());
        }

        for (RegexTemplate regexTemplate : suite.getSchemaNameTemplates()) {
            tags.addAll(regexTemplate.getFieldNames());
        }
    }
    return ImmutableList.copyOf(tags);
}
 
Example #25
Source File: TestExplicitColumnTracker.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for HBASE-2545
 */
@Test
public void testInfiniteLoop() throws IOException {
  TreeSet<byte[]> columns = new TreeSet<>(Bytes.BYTES_COMPARATOR);
  columns.addAll(Arrays.asList(new byte[][] { col2, col3, col5 }));
  List<byte[]> scanner = Arrays.<byte[]> asList(new byte[][] { col1, col4 });
  List<ScanQueryMatcher.MatchCode> expected = Arrays.<ScanQueryMatcher.MatchCode> asList(
    new ScanQueryMatcher.MatchCode[] { ScanQueryMatcher.MatchCode.SEEK_NEXT_COL,
        ScanQueryMatcher.MatchCode.SEEK_NEXT_COL });
  runTest(1, columns, scanner, expected);
}
 
Example #26
Source File: ExecutionCourse.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SortedSet<WrittenEvaluation> getWrittenEvaluations() {
    final SortedSet<WrittenEvaluation> writtenEvaluations = new TreeSet<>(WrittenEvaluation.COMPARATOR_BY_BEGIN_DATE);
    for (final Evaluation evaluation : getAssociatedEvaluationsSet()) {
        if (evaluation instanceof WrittenEvaluation) {
            writtenEvaluations.add((WrittenEvaluation) evaluation);
        }
    }
    return writtenEvaluations;
}
 
Example #27
Source File: Context.java    From vasco with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new context for phantom method
 * 
 * @param method
 */
public Context(M method) {
	count++;
	this.id = count;
	this.method = method;
	this.inValues = new HashMap<N, A>();
	this.outValues = new HashMap<N, A>();
	this.analysed = false;
	this.workList = new TreeSet<N>();
	this.workListOfEdges = new LinkedList<Pair<N, N>>();
}
 
Example #28
Source File: ReplicatedServer.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected void remove(XOffering offering, boolean removeExpectations) {
	Lock lock = writeLock();
	try {
		for (XCourse course: offering.getCourses()) {
			iCourseForId.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).remove(course.getCourseId());
			TreeSet<XCourseId> courses = iCourseForName.get(course.getCourseNameInLowerCase());
			if (courses != null) {
				courses.remove(course);
				if (courses.size() == 1) 
					for (XCourseId x: courses) x.setHasUniqueName(true);
				if (courses.isEmpty())
					iCourseForName.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).remove(course.getCourseNameInLowerCase());
				else
					iCourseForName.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(course.getCourseNameInLowerCase(), courses);
			}
		}
		iOfferingTable.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).remove(offering.getOfferingId());
		if (removeExpectations)
			iExpectations.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).remove(offering.getOfferingId());
		for (String externalId: offering.getInstructorExternalIds()) {
			Set<Long> offeringIds = iInstructedOfferings.get(externalId);
			if (offeringIds != null) {
				if (offeringIds.remove(offering.getOfferingId()))
					iInstructedOfferings.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put(externalId, offeringIds);
			}
		}
	} finally {
		lock.release();
	}
}
 
Example #29
Source File: MeanShift.java    From clust4j with Apache License 2.0 5 votes vote down vote up
SerialCenterIntensity(RadiusNeighbors nbrs) {
	
	LogTimer timer;
	
	// Now get single seed members
	MeanShiftSeed sd;
	this.computedSeeds = new TreeSet<>();
	final double[][] X = data.getData();
	
	int idx = 0;
	for(double[] seed: seeds) {
		idx++;
		timer = new LogTimer();
		sd = singleSeed(seed, nbrs, X, maxIter);
		
		if(null == sd)
			continue;
		
		computedSeeds.add(sd);
		itrz = FastMath.max(itrz, sd.iterations);
		
		// If it actually converged, add the summary
		summaries.add(new SummaryLite(
			"Kernel "+(idx - 1), sd.iterations, 
			timer.formatTime(), timer.wallTime()
		));
	}
}
 
Example #30
Source File: ImportStatements.java    From Refaster with Apache License 2.0 5 votes vote down vote up
public ImportStatements(JCExpression packageTree, List<JCImport> importTrees,
    ErrorProneEndPosMap endPosMap) {
  
  // find start, end positions for current list of imports (for replacement)
  if (importTrees.isEmpty()) {
    // start/end positions are just after the package expression
    hasExistingImports = false;
    startPos = endPosMap.getEndPosition(packageTree) + 2;   // +2 for semicolon and newline
    endPos = startPos;
  } else {
    // process list of imports and find start/end positions
    hasExistingImports = true;
    for (JCImport importTree : importTrees) {
      int currStartPos = importTree.getStartPosition();
      int currEndPos = endPosMap.getEndPosition(importTree);
      
      startPos = Math.min(startPos, currStartPos);
      endPos = Math.max(endPos, currEndPos);
    }  
  }
  
  // sanity check for start/end positions
  Preconditions.checkState(startPos <= endPos);
  
  // convert list of JCImports to list of strings
  importStrings = new TreeSet<>(IMPORT_ORDERING);
  importStrings.addAll(Lists.transform(importTrees, new Function<JCImport, String>() {
    @Override
    public String apply(JCImport input) {
      String importExpr = input.toString();
      return importExpr.substring(0, importExpr.length() - 2); // snip trailing ";\n"
    }
  }));
}