Reports any String.indexOf() expressions which can be replaced with a call to the String.contains() method available in Java 5 and newer.
Signed-off-by: Lars Grefer <eclipse@larsgrefer.de>
public boolean checkFor(String what) {
List<TestMessage> ll = ((TestMessageHandler) compiler.getMessageHandler()).getMessages();
for (TestMessage element: ll) {
- if (element.toString().indexOf(what) != -1)
+ if (element.toString().contains(what))
return true;
}
return false;
if (text.startsWith("woven class ")) numWovenClassMessages++;
if (text.startsWith("compiled:")) numCompiledMessages++;
if (programmableString != null
- && text.indexOf(programmableString) != -1) {
+ && text.contains(programmableString)) {
count--;
if (count==0) {
if (debugTests) System.out.println("Just got message '"+newText+"' - asking build to cancel");
public boolean containsMessage(String prefix,String distinguishingMarks) {
for (String element: messagesReceived) {
if (element.startsWith(prefix) &&
- element.indexOf(distinguishingMarks)!=-1) return true;
+ element.contains(distinguishingMarks)) return true;
}
return false;
}
while (null != (entry = outjar.getNextEntry())) {
String fileName = entry.getName();
fileName = fileName.replace('\\', '/');
- if (fileName.indexOf("CVS") == -1) {
+ if (!fileName.contains("CVS")) {
boolean b = expectedOutputJarContents.remove(fileName);
assertTrue("Unexpectedly found : " + fileName + " in outjar", b);
}
File binBase = openFile(outdirName);
String[] toResources = FileUtil.listFiles(binBase);
for (String fileName : toResources) {
- if (fileName.indexOf("CVS") == -1) {
+ if (!fileName.contains("CVS")) {
boolean b = expectedOutdirContents.remove(fileName);
assertTrue("Extraneous resources: " + fileName, b);
}
for (File fromResource : fromResources) {
String name = FileUtil.normalizedPath(fromResource, srcBase);
// System.err.println("Checking "+name);
- if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
+ if (!name.startsWith("CVS/") && (!name.contains("/CVS/")) && !name.endsWith("/CVS")) {
resources.add(name);
}
}
File[] fromResources = FileUtil.listFiles(srcBase, aspectjResourceFileFilter);
for (File fromResource : fromResources) {
String name = FileUtil.normalizedPath(fromResource, srcBase);
- if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
+ if (!name.startsWith("CVS/") && (!name.contains("/CVS/")) && !name.endsWith("/CVS")) {
resources.add(name);
}
}
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
- boolean isCVSRelated = name.indexOf("/cvs/") != -1;
+ boolean isCVSRelated = name.contains("/cvs/");
return (!isCVSRelated && !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj"));
}
};
private List<IProgramElement> findMatchesHelper(IProgramElement node, String pattern, IProgramElement.Kind kind, List<IProgramElement> matches) {
- if (node != null && node.getName().indexOf(pattern) != -1) {
+ if (node != null && node.getName().contains(pattern)) {
if (kind == null || node.getKind().equals(kind)) {
matches.add(node);
}
private IProgramElement getChild(IProgramElement parent, String s) {
List<IProgramElement> kids = parent.getChildren();
for (IProgramElement element : kids) {
- if (element.getName().indexOf(s) != -1)
+ if (element.getName().contains(s))
return element;
}
return null;
private void findChild(String s, IProgramElement ipe) {
if (ipe == null)
return;
- if (ipe.getName().indexOf(s) != -1) {
+ if (ipe.getName().contains(s)) {
foundNode = ipe;
return;
}
doBuild("bad-injar.lst");
messages = getMessages("bad-injar.lst");
message = (TestMessage)messages.get(0);
- assertTrue(message.getContainedMessage().getMessage().indexOf("skipping missing, empty or corrupt inpath entry") != -1);
+ assertTrue(message.getContainedMessage().getMessage().contains("skipping missing, empty or corrupt inpath entry"));
}
public void testErrorMessages() throws IOException {
List messages = getMessages("invalid-entry.lst");
TestMessage message = (TestMessage)messages.get(0);
- assertTrue(message.getContainedMessage().getMessage(), message.getContainedMessage().getMessage().indexOf("aaa.bbb") != -1);
+ assertTrue(message.getContainedMessage().getMessage(), message.getContainedMessage().getMessage().contains("aaa.bbb"));
}
if (text.startsWith("woven class ")) numWovenClassMessages++;
if (text.startsWith("compiled:")) numCompiledMessages++;
if (programmableString != null
- && text.indexOf(programmableString) != -1) {
+ && text.contains(programmableString)) {
count--;
if (count==0) {
if (debugTests) System.out.println("Just got message '"+newText+"' - asking build to cancel");
for (Object o : messagesReceived) {
String element = (String) o;
if (element.startsWith(prefix) &&
- element.indexOf(distinguishingMarks) != -1) return true;
+ element.contains(distinguishingMarks)) return true;
}
return false;
}
}
// only add aspect documentation if we're in the correct
// file for the given IProgramElement
- if (file.getName().indexOf(fullname + ".html") != -1) {
+ if (file.getName().contains(fullname + ".html")) {
addAspectDocumentation(decl, fileContents, index);
}
} else {
// moved this here because then can use the IProgramElement.Kind
// rather than checking to see if there's advice - this fixes
// the case with an inner aspect not having the title "Aspect"
- if (decl.getKind().equals(IProgramElement.Kind.ASPECT) && file.getName().indexOf(decl.toSignatureString()) != -1) {
+ if (decl.getKind().equals(IProgramElement.Kind.ASPECT) && file.getName().contains(decl.toSignatureString())) {
// only want to change "Class" to "Aspect" if we're in the
// file corresponding to the IProgramElement
String fullname = "";
} else {
fullname += decl.toSignatureString();
}
- if (file.getName().indexOf(fullname + ".html") == -1) {
+ if (!file.getName().contains(fullname + ".html")) {
// we're still in the file for a parent IPE
continue;
}
*/
private static String getRelativePathFromHere(String packagePath) {
StringBuffer result = new StringBuffer("");
- if (packagePath != null && (packagePath.indexOf("/") != -1)) {
+ if (packagePath != null && (packagePath.contains("/"))) {
StringTokenizer sTok = new StringTokenizer(packagePath, "/", false);
while (sTok.hasMoreTokens()) {
sTok.nextToken(); // don't care about the token value
if (member.getKind().equals(IProgramElement.Kind.METHOD)
|| member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) {
- if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.indexOf("abstract ") != -1) {
+ if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.contains("abstract ")) {
writer.println(";");
} else {
writer.println(" { }");
BufferedReader reader = new BufferedReader(new FileReader(htmlFile));
String line = reader.readLine();
while (line != null) {
- if (line.indexOf(requiredString) != -1) {
+ if (line.contains(requiredString)) {
reader.close();
return true;
}
BufferedReader reader = new BufferedReader(new FileReader(htmlFile));
String line = reader.readLine();
while (line != null) {
- if (line.indexOf(sectionHeader) != -1) {
+ if (line.contains(sectionHeader)) {
String nextLine = reader.readLine();
while (nextLine != null &&
- (nextLine.indexOf("========") == -1)) {
- if (nextLine.indexOf(requiredString) != -1) {
+ (!nextLine.contains("========"))) {
+ if (nextLine.contains(requiredString)) {
reader.close();
return true;
}
BufferedReader reader = new BufferedReader(new FileReader(htmlFile));
String line = reader.readLine();
while (line != null) {
- if (line.indexOf("START OF CLASS DATA") != -1) {
+ if (line.contains("START OF CLASS DATA")) {
// found the required class data section
String subLine = reader.readLine();
while(subLine != null
- && (subLine.indexOf("========") == -1)){
+ && (!subLine.contains("========"))){
int relIndex = subLine.indexOf(relationship.toString());
int targetIndex = subLine.indexOf(target);
if ((relIndex != -1) && (targetIndex != -1)) {
if (((htmlFile == null) || !htmlFile.getAbsolutePath().endsWith("html"))) {
return false;
}
- if (sectionHeader.indexOf("DETAIL") == -1) {
+ if (!sectionHeader.contains("DETAIL")) {
return false;
}
BufferedReader reader = new BufferedReader(new FileReader(htmlFile));
String line = reader.readLine();
while (line != null) {
- if (line.indexOf(sectionHeader) != -1) {
+ if (line.contains(sectionHeader)) {
// found the required main section
String nextLine = reader.readLine();
- while (nextLine != null && (nextLine.indexOf("========") == -1)) {
+ while (nextLine != null && (!nextLine.contains("========"))) {
// On JDK11 it looks like <a id="doIt()"> on earlier JDKs it can look like <a name="doit">
- if ((LangUtil.is11VMOrGreater() && nextLine.indexOf("ID=\""+source+"\"") != -1 || nextLine.indexOf("id=\""+source+"\"") != -1) ||
- nextLine.indexOf("NAME=\""+source+"\"") != -1 || nextLine.indexOf("name=\""+source+"\"") != -1) {
+ if ((LangUtil.is11VMOrGreater() && nextLine.contains("ID=\"" + source + "\"") || nextLine.contains("id=\"" + source + "\"")) ||
+ nextLine.contains("NAME=\"" + source + "\"") || nextLine.contains("name=\"" + source + "\"")) {
// found the required subsection
String subLine = reader.readLine();
while(subLine != null
- && (subLine.indexOf("========") == -1)
- && (subLine.indexOf("NAME") == -1 && subLine.indexOf("name") == -1)) {
+ && (!subLine.contains("========"))
+ && (!subLine.contains("NAME") && !subLine.contains("name"))) {
int relIndex = subLine.indexOf(relationship.toString());
int targetIndex = subLine.indexOf(target);
if ((relIndex != -1) && (targetIndex != -1)) {
if (((htmlFile == null) || !htmlFile.getAbsolutePath().endsWith("html"))) {
return false;
}
- if (sectionHeader.indexOf("SUMMARY") == -1) {
+ if (!sectionHeader.contains("SUMMARY")) {
return false;
}
BufferedReader reader = new BufferedReader(new FileReader(htmlFile));
String line = reader.readLine();
while (line != null) {
- if (line.indexOf(sectionHeader) != -1) {
+ if (line.contains(sectionHeader)) {
// found the required main section
String nextLine = reader.readLine();
- while (nextLine != null && (nextLine.indexOf("========") == -1)) {
- if (nextLine.indexOf(source) != -1) {
+ while (nextLine != null && (!nextLine.contains("========"))) {
+ if (nextLine.contains(source)) {
// found the required subsection
String subLine = nextLine;
while(subLine != null
- && (subLine.indexOf("========") == -1)
- && (subLine.indexOf("<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">") == -1)) {
+ && (!subLine.contains("========"))
+ && (!subLine.contains("<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">"))) {
int relIndex = subLine.indexOf(relationship.toString());
int targetIndex = subLine.indexOf(target);
if ((relIndex != -1) && (targetIndex != -1)) {
if (folder.endsWith("/")) {
folder = folder.substring(0, folder.length() - 1);
}
- if (folder.indexOf("/") != -1) {
+ if (folder.contains("/")) {
folder = folder.replace("/", "\\/");
}
sb.append(folder);
// this code needs a speed overhaul... and some proper tests
// Two static parts because one may be enclosing jpsp (269522)
if (sig1 != null) {
- if (sig1.indexOf("Lorg/aspectj/lang") != -1) {
+ if (sig1.contains("Lorg/aspectj/lang")) {
if (sig1.endsWith("Lorg/aspectj/lang/JoinPoint$StaticPart;")) {
sig1 = sig1.substring(0, sig1.lastIndexOf("Lorg/aspectj/lang/JoinPoint$StaticPart;"));
}
// this code needs a speed overhaul... and some proper tests
// Two static parts because one may be enclosing jpsp (269522)
if (sig1 != null) {
- if (sig1.indexOf("Lorg/aspectj/lang") != -1) {
+ if (sig1.contains("Lorg/aspectj/lang")) {
if (sig1.endsWith("Lorg/aspectj/lang/JoinPoint$StaticPart;")) {
sig1 = sig1.substring(0, sig1.lastIndexOf("Lorg/aspectj/lang/JoinPoint$StaticPart;"));
}
ipeSig = ipeSig.substring(0, idx);
}
if (ipeSig != null) {
- if (ipeSig.indexOf("Lorg/aspectj/lang") != -1) {
+ if (ipeSig.contains("Lorg/aspectj/lang")) {
if (ipeSig.endsWith("Lorg/aspectj/lang/JoinPoint$StaticPart;")) {
ipeSig = ipeSig.substring(0, ipeSig.lastIndexOf("Lorg/aspectj/lang/JoinPoint$StaticPart;"));
}
// check if someone is calling us with something that is a signature already
assert name.charAt(0) != '[';
- if (name.indexOf("<") == -1) {
+ if (!name.contains("<")) {
// not parameterized
return new StringBuilder("L").append(name.replace('.', '/')).append(';').toString();
} else {
StringBuffer buf = new StringBuffer("(");
String type;
int index;
- int var_index = (access.indexOf("static") >= 0) ? 0 : 1;
+ int var_index = (access.contains("static")) ? 0 : 1;
try { // Read all declarations between for `(' and `)'
if (signature.charAt(0) != '(') {
NameValuePair nvGen = new NameValuePair("id", evg, cp);
// Check it looks right
- assertTrue("Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().indexOf("id=4") != -1);
+ assertTrue("Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().contains("id=4"));
ObjectType t = new ObjectType("SimpleAnnotation");
NameValuePair nvGen = new NameValuePair("id", evg, cp);
// Check it looks right
- assertTrue("Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().indexOf("id=4") != -1);
+ assertTrue("Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().contains("id=4"));
ObjectType t = new ObjectType("SimpleAnnotation");
ClassElementValue evg = new ClassElementValue(classType, cp);
assertTrue("Unexpected value for contained class: '" + evg.getClassString() + "'",
- evg.getClassString().indexOf("Integer") != -1);
+ evg.getClassString().contains("Integer"));
checkSerialize(evg, cp);
}
AnnotationGen[] annos = mainMethod.getAnnotationsOnParameter(0);
assertTrue("Should be two annotation on the 'argv' parameter to main() but there are "+annos.length,annos.length==2);
assertTrue("This annotation should contain the string 'fruit=Apples' but it is "+annos[0].toString(),
- annos[0].toString().indexOf("fruit=Apples")!=-1);
+ annos[0].toString().contains("fruit=Apples"));
assertTrue("This annotation should contain the string 'fruit=Oranges' but it is "+annos[1].toString(),
- annos[1].toString().indexOf("fruit=Oranges")!=-1);
+ annos[1].toString().contains("fruit=Oranges"));
}
AnnotationGen[] annos = mainMethod.getAnnotationsOnParameter(0);
assertTrue("Should be two annotation on the 'argv' parameter to main() but there are "+annos.length,annos.length==2);
assertTrue("This annotation should contain the string 'fruit=Apples' but it is "+annos[0].toString(),
- annos[0].toString().indexOf("fruit=Apples")!=-1);
+ annos[0].toString().contains("fruit=Apples"));
assertTrue("This annotation should contain the string 'fruit=Oranges' but it is "+annos[1].toString(),
- annos[1].toString().indexOf("fruit=Oranges")!=-1);
+ annos[1].toString().contains("fruit=Oranges"));
assertTrue(wipe("temp5","HelloWorld.class"));
}
public void testJava9ImageFile() throws IOException {
String sunbootClasspath = System.getProperty("sun.boot.class.path");
- if (sunbootClasspath==null || sunbootClasspath.indexOf(".jimage")==-1) {
+ if (sunbootClasspath==null || !sunbootClasspath.contains(".jimage")) {
// Not java9
return;
}
return true;
}
String text = message.getMessage();
- return (text.indexOf(infix) != -1);
+ return (text.contains(infix));
}
public void ignore(Kind kind) {
boolean useEclipseCompiles = false;
boolean verbose = false;
if (null != config) {
- if (-1 != config.indexOf("useEclipseCompiles")) {
+ if (config.contains("useEclipseCompiles")) {
useEclipseCompiles = true;
}
- if (-1 != config.indexOf("verbose")) {
+ if (config.contains("verbose")) {
verbose = true;
}
}
if ((null == line) || (0 == line.length())) {
return;
}
- if (!gotLicense && (null != license) && (-1 != line.indexOf(license))) {
+ if (!gotLicense && (null != license) && (line.contains(license))) {
gotLicense = true;
}
if (!gotCopyright && (null != copyright)) {
start = loc + 4;
}
- return (-1 != line.indexOf("*/"));
+ return (line.contains("*/"));
}
} // class Header
*/
protected Result specifyResultFor(BuildSpec buildSpec) {
if (buildSpec.trimTesting
- && (-1 != buildSpec.module.indexOf("testing"))) { // XXXNameLiteral
+ && (buildSpec.module.contains("testing"))) { // XXXNameLiteral
String warning = "Warning - cannot trimTesting for testing modules: ";
handler.log(warning + buildSpec.module);
}
if (path.equals("org.eclipse.ajdt.core.ASPECTJRT_CONTAINER")) {
classpathVariables.add("ASPECTJRT_LIB");
} else {
- if (-1 == path.indexOf("JRE")) { // warn non-JRE containers
+ if (!path.contains("JRE")) { // warn non-JRE containers
messager.log("cannot handle con yet: " + toString);
}
}
boolean inQuote = false;
while (st.hasMoreTokens()) {
String s = st.nextToken();
- if ((1 == s.length()) && (-1 != DELIM.indexOf(s))) {
+ if ((1 == s.length()) && (DELIM.contains(s))) {
if ("\"".equals(s)) { // end quote (or escaped)
if (inQuote) {
inQuote = false;
* Checks if the pattern looks like "com.foo.Bar" - an exact name
*/
private String looksLikeExactName(String typePattern) {
- if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.indexOf("*") != -1) {
+ if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.contains("*")) {
return null;
}
return typePattern.replace('$', '.');
String parentAspectName = concreteAspect.extend;
- if (parentAspectName.indexOf("<") != -1) {
+ if (parentAspectName.contains("<")) {
// yikes, generic parent
parent = world.resolve(UnresolvedType.forName(parentAspectName), true);
if (parent.isMissing()) {
return null;
}
String clazz = value.substring(0, value.length() - 6);
- boolean qualified = clazz.indexOf(".") != -1;
+ boolean qualified = clazz.contains(".");
if (!qualified) {
// if not qualified, have to assume java.lang
clazz = "java.lang." + clazz;
} catch (Exception ex) {
// Expecting: java.lang.NoClassDefFoundError: LTWAspect
String m = ex.getMessage();
- if (-1 == m.indexOf("java.lang.NoClassDefFoundError")) {
+ if (!m.contains("java.lang.NoClassDefFoundError")) {
fail("Expecting java.lang.NoClassDefFoundError but caught " + ex);
}
}
// expecting error
String message = ex.getMessage();
// expecting error - seems to be wrapped wrong
- if (-1 == message.indexOf("around advice")) {
+ if (!message.contains("around advice")) {
failWithException(ex);
}
} catch (Error ex) {
invokeMain(clazz, new String[] {});
fail("Should reject bad aspect MissingFile");
} catch (AbortException ae) {
- assertTrue("Unexpected cause: " + ae.getMessage(), ae.getMessage().indexOf("bad aspect library") != -1);
+ assertTrue("Unexpected cause: " + ae.getMessage(), ae.getMessage().contains("bad aspect library"));
}
}
/** @return IMessage.WARNING unless message contains error or info */
protected static IMessage.Kind inferKind(String message) { // XXX dubious
- if (-1 != message.indexOf("error")) {
+ if (message.contains("error")) {
return IMessage.ERROR;
- } else if (-1 != message.indexOf("info")) {
+ } else if (message.contains("info")) {
return IMessage.INFO;
} else {
return IMessage.WARNING;
public String getPointcutText() {
String text = getPointcut().toString();
- if (text.indexOf("BindingTypePattern") == -1)
+ if (!text.contains("BindingTypePattern"))
return text;
// has been wrecked by resolution, try to reconstruct from tokens
if (pointcutDesignator != null) {
String name = new String(binding.selector);
if (name.startsWith("ajc$")) {
long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference
- if (name.indexOf("interField") != -1) {
+ if (name.contains("interField")) {
if ((metaTagBits & TagBits.AnnotationForField) != 0)
return;
- } else if (name.indexOf("interConstructor") != -1) {
+ } else if (name.contains("interConstructor")) {
if ((metaTagBits & TagBits.AnnotationForConstructor) != 0)
return;
- } else if (name.indexOf("interMethod") != -1) {
+ } else if (name.contains("interMethod")) {
if ((metaTagBits & TagBits.AnnotationForMethod) != 0)
return;
- } else if (name.indexOf("declare_" + DeclareAnnotation.AT_TYPE + "_") != -1) {
+ } else if (name.contains("declare_" + DeclareAnnotation.AT_TYPE + "_")) {
if ((metaTagBits & TagBits.AnnotationForAnnotationType) != 0 || (metaTagBits & TagBits.AnnotationForType) != 0)
return;
- } else if (name.indexOf("declare_" + DeclareAnnotation.AT_FIELD + "_") != -1) {
+ } else if (name.contains("declare_" + DeclareAnnotation.AT_FIELD + "_")) {
if ((metaTagBits & TagBits.AnnotationForField) != 0)
return;
- } else if (name.indexOf("declare_" + DeclareAnnotation.AT_CONSTRUCTOR + "_") != -1) {
+ } else if (name.contains("declare_" + DeclareAnnotation.AT_CONSTRUCTOR + "_")) {
if ((metaTagBits & TagBits.AnnotationForConstructor) != 0)
return;
- } else if (name.indexOf("declare_eow") != -1) {
+ } else if (name.contains("declare_eow")) {
if ((metaTagBits & TagBits.AnnotationForField) != 0)
return;
}
this.delegate = aProblem;
// if this was a problem that came via the weaver, it will already have
// pinpoint info, don't do it twice...
- if (delegate.getMessage().indexOf("message issued...") == -1) {
+ if (!delegate.getMessage().contains("message issued...")) {
this.message = delegate.getMessage() + "\n" + pinpoint;
} else {
this.message = delegate.getMessage();
lintValue = AjCompilerOptions.ERROR;
} else {
// Possibly a name=value comma separated list of configurations
- if (lintMode.indexOf("=")!=-1) {
+ if (lintMode.contains("=")) {
this.lintMode = AJLINT_DEFAULT;
lintOptionsMap = new HashMap<String,String>();
StringTokenizer tokenizer = new StringTokenizer(lintMode,",");
}
private boolean acceptResource(String resourceName, boolean fromFile) {
- if ((resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS"))
+ if ((resourceName.startsWith("CVS/")) || (resourceName.contains("/CVS/")) || (resourceName.endsWith("/CVS"))
|| (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/"))
- || (resourceName.indexOf("/.svn/") != -1) || (resourceName.endsWith("/.svn")) ||
+ || (resourceName.contains("/.svn/")) || (resourceName.endsWith("/.svn")) ||
// Do not copy manifests if either they are coming from a jar or we are writing to a jar
(resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos != null))) {
return false;
}
return null; // this is the "OK" return value!
}
- else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) {
+ else if (p.isFile() && p.getName().contains("org.aspectj.runtime")) {
// likely to be a variant from the springsource bundle repo b272591
return null;
}
if (compiledTypes != null) {
for (char[] className : (Iterable<char[]>) compiledTypes.keySet()) {
String typeName = new String(className).replace('/', '.');
- if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
+ if (!typeName.contains(BcelWeaver.SYNTHETIC_CLASS_POSTFIX)) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
// This can happen in a case where another problem has occurred that prevented it being
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
String fqname = itd.getOnType().toString();
- if (fqname.indexOf(".") != -1) {
+ if (fqname.contains(".")) {
// TODO the string handling round here is embarrassing
node.addFullyQualifiedName(fqname + "." + new String(itd.getDeclaredSelector()));
fqname = fqname.substring(fqname.lastIndexOf(".") + 1);
declared = true;
extraDetails = extraDetails.substring(0, extraDetails.length() - "[deow=true]".length());
}
- if (extraDetails != null && extraDetails.indexOf("[Xlint:") != -1) {
+ if (extraDetails != null && extraDetails.contains("[Xlint:")) {
isLintMessage = true;
lintkey = extraDetails.substring(extraDetails.indexOf("[Xlint:"));
lintkey = lintkey.substring("[Xlint:".length());
File file = loc.getSourceFile();
if (null != file) {
String name = file.getName();
- if (!toString || (-1 == text.indexOf(name))) {
+ if (!toString || (!text.contains(name))) {
sb.append(FileUtil.getBestPath(file));
if (loc.getLine() > 0) {
sb.append(":" + loc.getLine());
public void testIncrementalOption() throws InvalidInputException {
AjdtCommand.genBuildConfig(new String[] { "-incremental" }, counter);
- assertTrue("didn't specify source root", outputWriter.getContents().indexOf("specify a source root") != -1);
+ assertTrue("didn't specify source root", outputWriter.getContents().contains("specify a source root"));
outputWriter.flushBuffer();
AjdtCommand.genBuildConfig(new String[] { "-incremental", "-sourceroots", Constants.TESTDATA_PATH + "/src1" }, counter);
outputWriter.flushBuffer();
AjdtCommand.genBuildConfig(new String[] { "-incremental", "testdata/src1/Hello.java" }, counter);
- assertTrue("specified a file", outputWriter.getContents().indexOf(
- "incremental mode only handles source files using -sourceroots") != -1);
+ assertTrue("specified a file", outputWriter.getContents().contains("incremental mode only handles source files using -sourceroots"));
}
public void testBadOptionAndUsagePrinting() throws InvalidInputException {
}
// usage printed by caller to genBuildConfig now...
assertTrue(outputWriter.getContents() + " contains? " + "Usage",
- outputWriter.getContents().indexOf("-mubleBadOption") != -1);
+ outputWriter.getContents().contains("-mubleBadOption"));
}
}
String text = byteArrayOut.toString();
- assertTrue(text + " contains? " + "Usage", text.indexOf("Usage") != -1);
+ assertTrue(text + " contains? " + "Usage", text.contains("Usage"));
}
public void q() throws InvalidInputException {
String text = byteArrayOut.toString();
// String text2 = byteArrayErr.toString();
- assertTrue("version output does not include 'AspectJ Compiler', output was:\n'" + text + "'", text
- .indexOf("AspectJ Compiler") != -1);
+ assertTrue("version output does not include 'AspectJ Compiler', output was:\n'" + text + "'", text.contains("AspectJ Compiler"));
}
public void testNonExistingLstFile() {
AjdtCommand.genBuildConfig(new String[] { "@mumbleDoesNotExist" }, counter);
- assertTrue(outputWriter.getContents(), outputWriter.getContents().indexOf("file does not exist") != -1);
+ assertTrue(outputWriter.getContents(), outputWriter.getContents().contains("file does not exist"));
}
protected void setUp() throws Exception {
boolean jar2Found = false;
for (Object o : cp) {
String element = (String) o;
- if (element.indexOf("1.jar") != -1) jar1Found = true;
- if (element.indexOf("2.jar") != -1) jar2Found = true;
+ if (element.contains("1.jar")) jar1Found = true;
+ if (element.contains("2.jar")) jar2Found = true;
}
assertTrue(
config.getClasspath().toString(),
"-bootclasspath", PATH },
messageWriter);
assertTrue("Should find '" + PATH + "' contained in the first entry of '" + config.getBootclasspath().toString(),
- config.getBootclasspath().get(0).indexOf(PATH) != -1);
+ config.getBootclasspath().get(0).contains(PATH));
config = genBuildConfig(new String[] {
},
boolean jar2Found = false;
for (Object o : cp) {
String element = (String) o;
- if (element.indexOf("1.jar") != -1) jar1Found = true;
- if (element.indexOf("2.jar") != -1) jar2Found = true;
+ if (element.contains("1.jar")) jar1Found = true;
+ if (element.contains("2.jar")) jar2Found = true;
}
assertTrue(
config.getClasspath().toString(),
String record;
while ((null != (record = reader.readLine())) && (result == false)) {
if (record.startsWith("----")) currentHeading = record;
- else if ((record.indexOf(contents) != -1) && currentHeading.indexOf(heading) != -1) result = true;
+ else if ((record.contains(contents)) && currentHeading.contains(heading)) result = true;
}
reader.close();
}
final int numMessages = handler.numMessages(IMessage.WARNING, true);
if (1 == numMessages) { // permit aspectjrt.jar warning
IMessage m = handler.getMessages(IMessage.WARNING, true)[0];
- if (!(m.isWarning() && (-1 != m.getMessage().indexOf("aspectjrt.jar")))) {
+ if (!(m.isWarning() && (m.getMessage().contains("aspectjrt.jar")))) {
assertTrue(handler.toString(), false);
}
} else if (0 != numMessages) {
}
}
if (text != null) {
- if (message.getMessage().indexOf(text) == -1) {
+ if (!message.getMessage().contains(text)) {
return false;
}
}
private String substituteSandbox(String path) {
// the longhand form of the non 1.3 API: path.replace("$sandbox", ajc.getSandboxDirectory().getAbsolutePath());
- while (path.indexOf("$sandbox") != -1) {
+ while (path.contains("$sandbox")) {
int pos = path.indexOf("$sandbox");
String firstbit = path.substring(0, pos);
String endbit = path.substring(pos + 8);
cpIndex = i;
args[i + 1] = substituteSandbox(args[i + 1]);
String next = args[i + 1];
- hasruntime = ((null != next) && (-1 != next.indexOf("aspectjrt.jar")));
+ hasruntime = ((null != next) && (next.contains("aspectjrt.jar")));
} else if ("-p".equals(args[i]) || "--module-path".equals(args[i])) {
args[i + 1] = substituteSandbox(args[i + 1]);
}
}
boolean needsJRTFS = LangUtil.is19VMOrGreater();
if (needsJRTFS) {
- if (args[cpIndex].indexOf(LangUtil.JRT_FS) == -1) {
+ if (!args[cpIndex].contains(LangUtil.JRT_FS)) {
String jrtfsPath = LangUtil.getJrtFsFilePath();
args[cpIndex] = jrtfsPath + File.pathSeparator + args[cpIndex];
}
return false; // body of an itd-m
}
return true;
- } else if (methodName.indexOf("_aroundBody") != -1) {
+ } else if (methodName.contains("_aroundBody")) {
return true;
}
// these aren't the droids you're looking for...move along...... pr148727
// check going bang in this case we check for $ (crap...) - we can't check the outer because the declaring type
// is considered unresolved...
if (// isParameterized && <-- might need this bit...
- !getDeclaringType().isGenericType() && getDeclaringType().getName().indexOf("$") == -1) {
+ !getDeclaringType().isGenericType() && !getDeclaringType().getName().contains("$")) {
throw new IllegalStateException("Can't ask to parameterize a member of non-generic type: " + getDeclaringType()
+ " kind(" + getDeclaringType().typeKind + ")");
}
}
public boolean isSynthetic() {
- return signature.indexOf("$ajc") != -1;
+ return signature.contains("$ajc");
}
public final boolean isFinal() {
// grab javaclass... but it doesnt know the originating file
// }
}
- if (binaryPath.indexOf("!") == -1) {
+ if (!binaryPath.contains("!")) {
File f = getDeclaringType().getSourceLocation().getSourceFile();
// Replace the source file suffix with .class
int i = f.getPath().lastIndexOf('.');
* @return a type object represnting that JVM bytecode signature.
*/
public static UnresolvedType forSignature(String signature) {
- assert !(signature.startsWith("L") && signature.indexOf("<") != -1);
+ assert !(signature.startsWith("L") && signature.contains("<"));
switch (signature.charAt(0)) {
case 'B':
return UnresolvedType.BYTE;
return name.replace('.','/');
}
- if (name.indexOf("<") == -1) {
+ if (!name.contains("<")) {
// not parameterized
return new StringBuilder("L").append(name.replace('.', '/')).append(';').toString();
} else {
public String getClassName() {
if (className == null) {
String name = getName();
- if (name.indexOf("<") != -1) {
+ if (name.contains("<")) {
name = name.substring(0, name.indexOf("<"));
}
int index = name.lastIndexOf('.');
// 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"})
String value = ann.getStringFormOfValue("value");
// Slightly lazy, just doing a string indexof
- if (value == null || value.indexOf(lintkey) != -1) {
+ if (value == null || value.contains(lintkey)) {
return true;
}
}
if (jps == null) {
return;
}
- if (jps.indexOf("arrayconstruction") != -1) {
+ if (jps.contains("arrayconstruction")) {
optionalJoinpoint_ArrayConstruction = true;
}
- if (jps.indexOf("synchronization") != -1) {
+ if (jps.contains("synchronization")) {
optionalJoinpoint_Synchronization = true;
}
}
break;
} else {
if (t.isAnnotation()) {
- if (v.indexOf("(") != -1) {
+ if (v.contains("(")) {
throw new RuntimeException(
"Compiler limitation: annotation values can only currently be marker annotations (no values): "
+ v);
if (typePattern instanceof WildTypePattern && (annotationValues == null || annotationValues.isEmpty())) {
WildTypePattern wildTypePattern = (WildTypePattern) typePattern;
String fullyQualifiedName = wildTypePattern.maybeGetCleanName();
- if (fullyQualifiedName != null && fullyQualifiedName.indexOf(".") != -1) {
+ if (fullyQualifiedName != null && fullyQualifiedName.contains(".")) {
ResolvedType resolvedType = world.resolve(UnresolvedType.forName(fullyQualifiedName));
if (resolvedType != null && !resolvedType.isMissing()) {
typePattern = new ExactTypePattern(resolvedType, false, false);
ret.add(possibleMatch);
continue;
}
- if (possibleMatch.indexOf("$") != -1) {
+ if (possibleMatch.contains("$")) {
names = splitNames(possibleMatch, false); // ??? not most efficient
if (namePatterns[0].matches(names[names.length - 1])) {
ret.add(possibleMatch);
// System.out.println("expected exception: " + re);
return;
} catch (Throwable t) {
- assertTrue(prefix, t.getMessage().indexOf(prefix) != -1);
+ assertTrue(prefix, t.getMessage().contains(prefix));
return;
}
assertTrue("should have failed", false);
public static Type stringToType(String typeName, Class classScope)
throws ClassNotFoundException {
try {
- if (typeName.indexOf("<") == -1) {
+ if (!typeName.contains("<")) {
return AjTypeSystem.getAjType(Class.forName(typeName,false,classScope.getClassLoader()));
} else {
return makeParameterizedType(typeName,classScope);
assertEquals(2,fooTypes.length);
// Alex -> Adrian: looks like you can not make assumption on the ordering
String s = " " + fooTypes[0].getName() + " " + fooTypes[1].getName();
- assertTrue(s.indexOf(" org.aspectj.internal.lang.reflect.Foo$Z") >= 0);
- assertTrue(s.indexOf(" org.aspectj.internal.lang.reflect.Foo$XX") >= 0);
+ assertTrue(s.contains(" org.aspectj.internal.lang.reflect.Foo$Z"));
+ assertTrue(s.contains(" org.aspectj.internal.lang.reflect.Foo$XX"));
}
public void testGetConstructor() throws Exception {
for (Method m : ms) {
match = match + "--" + m.getName();
}
- assertTrue(match.indexOf("aMethod") >=0);
+ assertTrue(match.contains("aMethod"));
}
public void testGetDeclaredPointcut() throws Exception {
assertEquals(2,pcs.length);
// AV was corrupted, cannot rely on ordering
String match = "simpleAspectMethodExecution--simpleAspectCall";
- assertTrue(match.indexOf(pcs[0].getName()) >= 0);
- assertTrue(match.indexOf(pcs[1].getName()) >= 0);
+ assertTrue(match.contains(pcs[0].getName()));
+ assertTrue(match.contains(pcs[1].getName()));
}
public void testGetPointcuts() {
static void checkSoftExceptionString(String s) {
- assertTrue(-1 != s.indexOf("SoftException"));
- assertTrue(-1 != s.indexOf("Caused by: java.lang.Error"));
- assertTrue(-1 != s.indexOf("xyz"));
- assertTrue(-1 != s.indexOf("testSoftExceptionPrintStackTrace"));
+ assertTrue(s.contains("SoftException"));
+ assertTrue(s.contains("Caused by: java.lang.Error"));
+ assertTrue(s.contains("xyz"));
+ assertTrue(s.contains("testSoftExceptionPrintStackTrace"));
}
}
}
// If there are stars we'll try to resolve the file here
- else if (line.indexOf("*") != -1) {
+ else if (line.contains("*")) {
log("The argfile line '" + line + "' is invalid",
Project.MSG_WARN);
}
int loc = path.lastIndexOf(prefix);
if ((-1 != loc) && ((loc + minLength) <= path.length())) {
String rest = path.substring(loc + prefixLength);
- if (-1 != rest.indexOf(File.pathSeparator)) {
+ if (rest.contains(File.pathSeparator)) {
return null;
}
if (rest.startsWith(infix) || rest.startsWith(altInfix)) {
*/
public void setInpathDirCopyFilter(String filter) {
if (null != filter) {
- if (-1 == filter.indexOf("**/*.class")) {
+ if (!filter.contains("**/*.class")) {
filter = "**/*.class," + filter;
}
}
String message = fail.getMessage();
if (LangUtil.isEmpty(message)) {
message = "<no message>";
- } else if (-1 != message.indexOf(USAGE_SUBSTRING)) {
+ } else if (message.contains(USAGE_SUBSTRING)) {
continue;
}
Throwable t = fail.getThrown();
String m = e.getMessage();
if (null == m) {
assertTrue("not " + exceptionString, false);
- } else if (-1 == m.indexOf(exceptionString)) {
+ } else if (!m.contains(exceptionString)) {
assertEquals(exceptionString, e.getMessage());
}
}
if (NOFILE.equals(input)) {
// add nothing
} else if (input.endsWith(".lst")) {
- if (-1 != input.indexOf(",")) {
+ if (input.contains(",")) {
throw new IllegalArgumentException(
"lists not supported: " + input);
} else if (null == testdataDir) {
}
assertTrue(
"expecting aspectj in classpath",
- (-1 != classpath.indexOf("aspectjrt.jar")));
+ (classpath.contains("aspectjrt.jar")));
}
CompilerArg createCompilerArg(String value) {
boolean matched = false;
for (int i = 0; !matched && (i < results.length); i++) {
String s = results[i];
- matched = (null != s) && (-1 != s.indexOf(DEFAULT));
+ matched = (null != s) && (s.contains(DEFAULT));
}
if (!matched) {
fail(DEFAULT + " not found in " + Arrays.asList(results));
boolean gotItem(List<IMessage> list, String substring) {
for (IMessage element: list) {
String s = element.getMessage();
- if ((null != s) && (-1 != s.indexOf(substring))) {
+ if ((null != s) && (s.contains(substring))) {
return true;
}
}
input = input.toLowerCase();
}
for (String substring : substrings) {
- if (-1 != input.indexOf(substring)) {
+ if (input.contains(substring)) {
return true;
}
}
continue; // hmm
}
String text = message.getMessage();
- if ((null != text) && (-1 != text.indexOf(sought))) {
+ if ((null != text) && (text.contains(sought))) {
return true;
}
}
String[] paths = FileUtil.listFiles(expectedBaseDir);
boolean result = true;
for (String path : paths) {
- if (-1 != path.indexOf("CVS")) {
+ if (path.contains("CVS")) {
continue;
}
if (!sameFiles(handler, expectedBaseDir, actualBaseDir, path) && result) {
} catch (IllegalArgumentException e) {
assertTrue("exception: " + errors[i], fail);
String m = e.getMessage();
- if (-1 == m.indexOf(errors[i])) {
+ if (!m.contains(errors[i])) {
fail(errors[i] + " not in " + m);
}
}
if (m_stdErrSpec != null) {
String stderr2 = stderr.toString();
// Working around this ridiculous message that still comes out of Java7 builds:
- if (stderr2.indexOf("Class JavaLaunchHelper is implemented in both")!=-1 && stderr2.indexOf('\n')!=-1) {
+ if (stderr2.contains("Class JavaLaunchHelper is implemented in both") && stderr2.indexOf('\n')!=-1) {
stderr2 = stderr2.replaceAll("objc\\[[0-9]*\\]: Class JavaLaunchHelper is implemented in both [^\n]*\n","");
}
// JDK 11 is complaining about illegal reflective calls - temporary measure ignore these - does that get all tests passing and this is the last problem?
- if (stderr2.indexOf("WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor") != -1) {
+ if (stderr2.contains("WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor")) {
// WARNING: An illegal reflective access operation has occurred
// WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor (file:/Users/aclement/gits/org.aspectj/loadtime/bin/) to class java.lang.ClassLoader
// WARNING: Please consider reporting this to the maintainers of org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor
public void setTest(AjcTest t) {
this.myTest = t;
- if (options != null && (options.indexOf("-1.5") != -1)) {
+ if (options != null && (options.contains("-1.5"))) {
myTest.setVm("1.5");
}
}
lineNo++;
String outputLine = strTok.nextToken().trim();
/* Avoid trying to match on ajSandbox source names that appear in messages */
- if (outputLine.indexOf(line) == -1) {
+ if (!outputLine.contains(line)) {
matches = false;
break;
}
found.addAll(outputFound);
for (String lineFound : outputFound) {
for (String lineExpected : expectedOutputLines) {
- if (lineFound.indexOf(lineExpected)!= -1) {
+ if (lineFound.contains(lineExpected)) {
found.remove(lineFound);
expected.remove(lineExpected);
continue;
!gotHit && iter.hasNext();
) {
String substring = (String) iter.next();
- if (-1 != this.description.indexOf(substring)) {
+ if (this.description.contains(substring)) {
gotHit = true;
}
}
}
} else {
String messages = "" + handler;
- if (-1 == messages.indexOf(contains)) {
+ if (!messages.contains(contains)) {
assertTrue(messages, false);
}
}
}
if (null != resultContains) {
String result = "" + spec.testSetup.commandOptions;
- if (-1 == result.indexOf(resultContains)) {
+ if (!result.contains(resultContains)) {
assertTrue(
"expected " + resultContains + " got " + result,
false);
assertTrue("expected " + messagesContain, false);
} else {
String messages = handler.toString();
- if (-1 == messages.indexOf(messagesContain)) {
+ if (!messages.contains(messagesContain)) {
assertTrue(
"expected "
+ messagesContain
String command = (String) dummyReports.remove(0);
assertTrue(0 == dummyReports.size());
if ((null == command)
- || (-1 == command.indexOf(expectedInCommand))) {
+ || (!command.contains(expectedInCommand))) {
assertTrue("expected "
+ expectedInCommand
+ "got "
// so compile succeeds but run not attempted
//result.errors = Main.RA_ErrorLine;
// result.runOptions = Main.RA_String;
- } else if (isNumber(first) || (-1 != first.indexOf(":"))) {
+ } else if (isNumber(first) || (first.contains(":"))) {
exp.addAll(makeMessages(IMessage.ERROR, words, 0, lastFile));
} else {
String[] args = new String[words.length - 1];
}
input = description.toString();
String error = null;
- if (-1 != input.indexOf("&")) {
+ if (input.contains("&")) {
error = "char &";
- } else if (-1 != input.indexOf("<")) {
+ } else if (input.contains("<")) {
error = "char <";
- } else if (-1 != input.indexOf(">")) {
+ } else if (input.contains(">")) {
error = "char >";
- } else if (-1 != input.indexOf("\"")) {
+ } else if (input.contains("\"")) {
error = "char \"";
}
if (null != error) {
protected boolean expectedException(Throwable thrown) {
if (null != spec.expectedException) {
String cname = thrown.getClass().getName();
- if (-1 != cname.indexOf(spec.expectedException)) {
+ if (cname.contains(spec.expectedException)) {
return true; // caller sets value for returns normally
}
}
protected boolean expectedException(ByteArrayOutputStream bout) {
return ((null != spec.expectedException)
- && (-1 != bout.toString().indexOf(spec.expectedException)));
+ && (bout.toString().contains(spec.expectedException)));
}
/**
|| LangUtil.isEmpty(rhs_s)) {
return 0;
}
- if ((-1 != lhs_s.indexOf(rhs_s))
- || (-1 != rhs_s.indexOf(lhs_s))) {
+ if ((lhs_s.contains(rhs_s))
+ || (rhs_s.contains(lhs_s))) {
return 0;
}
return String.CASE_INSENSITIVE_ORDER.compare(lhs_s, rhs_s);
} else if (null == actual) {
return false; // expected something
} else {
- return (-1 != actual.indexOf(expected));
+ return (actual.contains(expected));
}
}
String exp = (String) o;
if (path.startsWith(exp)) {
String suffix = path.substring(exp.length());
- if (-1 == suffix.indexOf("/")) { // normalized...
+ if (!suffix.contains("/")) { // normalized...
expected.remove(path);
// found - do not add to unexpected
return false;
ps = ";";
String cp = System.getProperty("java.class.path");
if (null != cp) {
- if (-1 != cp.indexOf(";")) {
+ if (cp.contains(";")) {
ps = ";";
- } else if (-1 != cp.indexOf(":")) {
+ } else if (cp.contains(":")) {
ps = ":";
}
// else warn?
public static void escape(String input, String target, String escape, StringBuffer sink) {
if ((null == sink) || isEmpty(input) || isEmpty(target) || isEmpty(escape)) {
return;
- } else if (-1 == input.indexOf(target)) { // avoid StringTokenizer construction
+ } else if (!input.contains(target)) { // avoid StringTokenizer construction
sink.append(input);
return;
}
if (isEmpty(input)) {
return result;
}
- if ((!haveDelim) || (-1 == input.indexOf(delim))) {
+ if ((!haveDelim) || (!input.contains(delim))) {
result.add(input);
return result;
}
StringBuffer sb = new StringBuffer();
sb.append(SPLIT_START);
for (int i = 0; i < input.length; i++) {
- if (-1 != input[i].indexOf(SPLIT_DELIM)) {
+ if (input[i].contains(SPLIT_DELIM)) {
if (null != errs) {
errs.append("\nLangUtil.unsplit(..) - item " + i + ": \"" + input[i]
+ " contains \"" + SPLIT_DELIM + "\"");
// only info if redirect from http to https
String m = e.getMessage();
if ((m != null)
- && (-1 != m.indexOf("protocol"))
- && (-1 != m.indexOf("https"))
+ && (m.contains("protocol"))
+ && (m.contains("https"))
&& "http".equals(link.url.getProtocol())) {
info("httpsRedirect", link);
return;
if ((null != prefix) && (!(path.startsWith(prefix)))) {
return false;
}
- if ((null != substring) && (-1 == path.indexOf(substring))) {
+ if ((null != substring) && (!path.contains(substring))) {
return false;
}
if ((null != suffix) && (!(path.endsWith(suffix)))) {
String m = e.getFullMessage();
boolean ok =
(null != expectedInExceptionMessage)
- && (-1 != m.indexOf(expectedInExceptionMessage));
+ && (m.contains(expectedInExceptionMessage));
if (!ok) {
e.printStackTrace(System.err);
if (null != expectedInExceptionMessage) {
}
} else {
if ((null == expectedIn)
- || (-1 == expectedIn.indexOf(expected))) {
+ || (!expectedIn.contains(expected))) {
assertionFailed(
"expected \""
+ expected
printed = true;
}
String s = o.toString();
- if (-1 != s.indexOf(",")) {
+ if (s.contains(",")) {
throw new IllegalArgumentException("comma in " + s);
}
sb.append(s);
public void test016_ByteConversionInstructions() {
runTest("RuntimeException thrown: Could not find instruction: org.apache.bcel.generic.B2I");
String output = getLastRunResult().getStdErr();
- assertTrue("Expected to find [b2] in this output but didn't:"+output,output.indexOf("[b2]")!=-1);
- assertTrue("Expected to find [b127] in this output but didn't:"+output,output.indexOf("[b127]")!=-1);
- assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
+ assertTrue("Expected to find [b2] in this output but didn't:"+output, output.contains("[b2]"));
+ assertTrue("Expected to find [b127] in this output but didn't:"+output, output.contains("[b127]"));
+ assertTrue("Expected to find [b0] in this output but didn't:"+output, output.contains("[b0]"));
- assertTrue("Expected to find [c65] in this output but didn't:"+output,output.indexOf("[c65]")!=-1);
- assertTrue("Expected to find [c66] in this output but didn't:"+output,output.indexOf("[c66]")!=-1);
- assertTrue("Expected to find [c67] in this output but didn't:"+output,output.indexOf("[c67]")!=-1);
+ assertTrue("Expected to find [c65] in this output but didn't:"+output, output.contains("[c65]"));
+ assertTrue("Expected to find [c66] in this output but didn't:"+output, output.contains("[c66]"));
+ assertTrue("Expected to find [c67] in this output but didn't:"+output, output.contains("[c67]"));
- assertTrue("Expected to find [s1] in this output but didn't:"+output,output.indexOf("[s1]")!=-1);
- assertTrue("Expected to find [s32767] in this output but didn't:"+output,output.indexOf("[s32767]")!=-1);
- assertTrue("Expected to find [b0] in this output but didn't:"+output,output.indexOf("[b0]")!=-1);
+ assertTrue("Expected to find [s1] in this output but didn't:"+output, output.contains("[s1]"));
+ assertTrue("Expected to find [s32767] in this output but didn't:"+output, output.contains("[s32767]"));
+ assertTrue("Expected to find [b0] in this output but didn't:"+output, output.contains("[b0]"));
}
public void test017_PrivateMethodCallsInAroundAdvice() {
runTest("proper handling of ExceptionInIntializer inside clinit in presence of after throwing advice");
String s = getLastRunResult().getStdErr();
assertTrue("Output should contain java.lang.ExceptionInInitializerError but is '"+s+"'",
- s.indexOf("java.lang.ExceptionInInitializerError")!=-1);
+ s.contains("java.lang.ExceptionInInitializerError"));
// No getCause on 1.3 JVMs
// assertTrue("Output should contain 'CAUSE=org.aspectj.lang.NoAspectBoundException' but is '"+s+"'",
// s.indexOf("CAUSE=org.aspectj.lang.NoAspectBoundException")!=-1);
AsmManager.dumptree(pw, AsmManager.lastActiveStructureModel.getHierarchy().getRoot(), 0);
pw.flush();
String tree = baos.toString();
- assertTrue("Expected 'Red [enumvalue]' somewhere in here:" + tree, tree.indexOf("Red [enumvalue]") != -1);
+ assertTrue("Expected 'Red [enumvalue]' somewhere in here:" + tree, tree.contains("Red [enumvalue]"));
}
}
String[] lines = ls.getLines();
for (int i = 0; i < lines.length; i++) {
String existingLine = lines[i];
- if (fileContents[i].indexOf("MethodDeclarationLineNumber") == -1 && !fileContents[i].equals(existingLine)) {
+ if (!fileContents[i].contains("MethodDeclarationLineNumber") && !fileContents[i].equals(existingLine)) {
dump("File contents:", fileContents);
dump("Actual:", lines);
fail("\nDifference in method " + m.getName() + " on line " + i + " between the expected:\n" + fileContents[i]
String warning = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.DECLARE_WARNING,
"declare warning: \"warning\"").getHandleIdentifier();
assertTrue("shouldn't have incremented counter for declare warning handle " + "because only one declare warning statement",
- warning.indexOf("!0") == -1 && warning.indexOf("!2") == -1);
+ !warning.contains("!0") && !warning.contains("!2"));
String error = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.DECLARE_ERROR, "declare error: \"error\"")
.getHandleIdentifier();
assertTrue("shouldn't have incremented counter for declare error handle " + "because only one declare error statement",
- error.indexOf("!0") == -1 && error.indexOf("!2") == -1);
+ !error.contains("!0") && !error.contains("!2"));
}
// public void testOnlyIncrementSameAdviceKindFromInjar_pr159896() {
String expected = "<recursivepackage{RecursiveCatcher.java'RecursiveCatcher~recursiveCall~I?method-call(void recursivepackage.RecursiveCatcher.recursiveCall(int))";
for (Object entry : entries) {
String str = (String) entry;
- if (str.indexOf(expected) != -1) {
+ if (str.contains(expected)) {
gotSomethingValid = true;
}
}
// Look for the message relating to 'List' and check the offsets
for (IMessage iMessage : ms) {
LintMessage m = (LintMessage) iMessage;
- if (m.toString().indexOf("List") != -1) {
+ if (m.toString().contains("List")) {
// 225/228 on windows - 237/240 on linux
if (!(m.getSourceStart() == 225 || m.getSourceStart() == 237)) {
fail("Did not get expected start position, was:" + m.getSourceStart());
pw.write(irm.toString());
pw.flush();
String model = baos.toString();
- assertTrue(model.indexOf("<{Choice.java[Choice=[aspect declarations]") != -1);
- assertTrue(model.indexOf("<{Choice.java'X[Keys=[declared on]") != -1);
+ assertTrue(model.contains("<{Choice.java[Choice=[aspect declarations]"));
+ assertTrue(model.contains("<{Choice.java'X[Keys=[declared on]"));
}
public void testGenerics1() throws Exception {
public void testIncrementalResourceAdditionToInPath() throws Exception {
runTest("incremental with addition of resource to inpath directory");
RunResult result = run("Hello");
- assertTrue("Should have been advised",result.getStdOut().indexOf("World") != -1);
+ assertTrue("Should have been advised", result.getStdOut().contains("World"));
nextIncrement(false);
assertFalse("Resource file should not exist yet",new File(ajc.getSandboxDirectory(),"AResourceFile.txt").exists());
copyFileAndDoIncrementalBuild("changes/AResourceFile.txt", "indir/AResourceFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
- if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
+ if (aspectName.equals("") && line.contains("aspect name=\"")) {
aspectCount++;
- } else if (line.indexOf("aspect name=\"" + aspectName + "\"") != -1) {
+ } else if (line.contains("aspect name=\"" + aspectName + "\"")) {
aspectCount++;
}
line = reader.readLine();
protected void assertContains(String expectedSubstring, Object object) {
String actualString = object.toString();
- if (actualString.indexOf(expectedSubstring) == -1) {
+ if (!actualString.contains(expectedSubstring)) {
fail("Expected to find '" + expectedSubstring + "' in '" + actualString + "'");
}
}
AjCompiler compiler = CompilerFactory.getCompilerForProjectWithDir(sandboxDir + File.separator + projectName);
List<IMessage> messages = ((MultiProjTestMessageHandler) compiler.getMessageHandler()).getErrorMessages();
for (IMessage element : messages) {
- if (element.getMessage().indexOf(anError) != -1) {
+ if (element.getMessage().contains(anError)) {
return;
}
}
// the unwovenClassFiles should have filenames that point to the output dir
// (which in this case is the sandbox dir) and not where they came from.
for (UnwovenClassFile ucf: unwovenClassFiles) {
- if (ucf.getFilename().indexOf(expectedOutputDir) == -1) {
+ if (!ucf.getFilename().contains(expectedOutputDir)) {
fileNames.add(ucf.getFilename());
}
}
// the unwovenClassFiles should have filenames that point to the output dir
// (which in this case is the sandbox dir) and not where they came from.
for (UnwovenClassFile ucf: unwovenClassFiles) {
- if (ucf.getFilename().indexOf(expectedOutputDir) == -1) {
+ if (!ucf.getFilename().contains(expectedOutputDir)) {
fileNames.add(ucf.getFilename());
}
}
List<String> fileNames = new ArrayList<>();
for (UnwovenClassFile ucf: unwovenClassFiles) {
- if (ucf.getFilename().indexOf(expectedOutputDir) == -1) {
+ if (!ucf.getFilename().contains(expectedOutputDir)) {
fileNames.add(ucf.getFilename());
}
}
// 2 errors are reported when there is a clash - one against the aspect, one against the affected target type.
// each of the two errors are recorded against the compilation result for the aspect and the target
// So it comes out as 4 - but for now I am tempted to leave it because at least it shows there is a problem...
- assertTrue("Was:" + getErrorMessages(p).get(0), getErrorMessages(p).get(0).toString().indexOf("conflicts") != -1);
+ assertTrue("Was:" + getErrorMessages(p).get(0), getErrorMessages(p).get(0).toString().contains("conflicts"));
}
public void testOutputLocationCallbacks2() {
build(p);
checkWasFullBuild();
assertEquals(1, getErrorMessages(p).size());
- assertTrue(((Message) getErrorMessages(p).get(0)).getMessage().indexOf(
- "Syntax error on token \")\", \"name pattern\" expected") != -1);
+ assertTrue(((Message) getErrorMessages(p).get(0)).getMessage().contains("Syntax error on token \")\", \"name pattern\" expected"));
}
public void testIncrementalMixin() {
initialiseProject(p);
build(p);
List<IMessage> l = getErrorMessages(p);
- assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1);
+ assertTrue(l.toString().contains("ManagedResource cannot be resolved to a type"));
// checkWasFullBuild();
alter(p, "inc1");
build(p);
// checkWasntFullBuild();
List<String> compilerErrors = getCompilerErrorMessages(p);
- assertTrue(compilerErrors.toString().indexOf("NullPointerException") == -1);
+ assertTrue(!compilerErrors.toString().contains("NullPointerException"));
l = getErrorMessages(p);
- assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1);
+ assertTrue(l.toString().contains("ManagedResource cannot be resolved to a type"));
}
public void testIncrementalAnnoStyle_pr286341() {
private IProgramElement findFile(IProgramElement whereToLook, String filesubstring) {
if (whereToLook.getSourceLocation() != null && whereToLook.getKind().isSourceFile()
- && whereToLook.getSourceLocation().getSourceFile().toString().indexOf(filesubstring) != -1) {
+ && whereToLook.getSourceLocation().getSourceFile().toString().contains(filesubstring)) {
return whereToLook;
}
for (IProgramElement element : whereToLook.getChildren()) {
Kind k = element.getKind();
ISourceLocation sloc = element.getSourceLocation();
- if (sloc != null && k.isSourceFile() && sloc.getSourceFile().toString().indexOf(filesubstring) != -1) {
+ if (sloc != null && k.isSourceFile() && sloc.getSourceFile().toString().contains(filesubstring)) {
return element;
}
if (k.isSourceFile()) {
List<String> files = getCompiledFiles(projectName);
boolean found = false;
for (String object: files) {
- if (object.indexOf(typeNameSubstring) != -1) {
+ if (object.contains(typeNameSubstring)) {
found = true;
}
}
List<IMessage> warnings = getWarningMessages("PR133117");
List<IMessage> noGuardWarnings = new ArrayList<>();
for (IMessage warning: warnings) {
- if (warning.getMessage().indexOf("Xlint:noGuardForLazyTjp") != -1) {
+ if (warning.getMessage().contains("Xlint:noGuardForLazyTjp")) {
noGuardWarnings.add(warning);
}
}
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect = "Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '" + expect + "' in the list of decisions made:\n" + decisions,
- decisions.indexOf(expect) != -1);
+ decisions.contains(expect));
}
public void testPr133532_3() {
public File getOutputLocationForClass(File compilationUnit) {
String relativePath = "";
String compilationUnitName = compilationUnit.getAbsolutePath();
- if (compilationUnitName.indexOf("srcRootOne") != -1) {
+ if (compilationUnitName.contains("srcRootOne")) {
relativePath = "target/main/classes";
- } else if (compilationUnitName.indexOf("srcRootTwo") != -1) {
+ } else if (compilationUnitName.contains("srcRootTwo")) {
relativePath = "target/test/classes";
- } else if (compilationUnitName.indexOf("srcRootThree") != -1) {
+ } else if (compilationUnitName.contains("srcRootThree")) {
relativePath = "target/anotherTest/classes";
}
File ret = new File(projectHome, relativePath);
/** @return true if input is not null and contains no path separator */
private static boolean isValidFileName(String input) {
- return ((null != input) && (-1 == input.indexOf(File.pathSeparator)));
+ return ((null != input) && (!input.contains(File.pathSeparator)));
}
private static void listFiles(final File baseDir, String dir, ArrayList<String> result) {
}
ArrayList<String> result = new ArrayList<String>();
- if (LangUtil.isEmpty(delim) || (-1 == input.indexOf(delim))) {
+ if (LangUtil.isEmpty(delim) || (!input.contains(delim))) {
result.add(input.trim());
} else {
StringTokenizer st = new StringTokenizer(input, delim);
boolean result = false;
if (!LangUtil.isEmpty(input)) {
for (int i = 0; !result && (i < infixes.length); i++) {
- result = (-1 != input.indexOf(infixes[i]));
+ result = (input.contains(infixes[i]));
}
}
return result;
* @param useSuffix if true, then use dir as suffix to path
*/
private static void doDirPaths(File dir, ArrayList<String> paths) {
- if ((null == dir) || !dir.canRead() || (-1 != dir.getPath().indexOf("CVS"))) {
+ if ((null == dir) || !dir.canRead() || (dir.getPath().contains("CVS"))) {
return;
}
File[] files = dir.listFiles();
GenericSignature.FieldTypeSignature cSig = parser.parseAsFieldSignature("Ljava/util/List</;");
fail("Expected IllegalStateException");
} catch (IllegalStateException ex) {
- assertTrue(ex.getMessage().indexOf("Ljava/util/List</;") != -1);
+ assertTrue(ex.getMessage().contains("Ljava/util/List</;"));
}
}
LangUtil.elideEndingLines(LangUtil.StringChecker.TEST_PACKAGES, stackBuffer, 10);
String result = stackBuffer.toString();
- if (-1 == result.indexOf("(... ")) {
+ if (!result.contains("(... ")) {
// brittle - will fail under different top-level drivers
String m = "when running under eclipse or Ant, expecting (... in trace: ";
assertTrue(m + result, false);
LangUtil.elideEndingLines(LangUtil.StringChecker.TEST_PACKAGES, stackBuffer, 25);
result = stackBuffer.toString();
- assertTrue(result, -1 != result.indexOf("(... "));
- assertTrue(result, -1 == result.indexOf("org.aspectj.testing"));
+ assertTrue(result, result.contains("(... "));
+ assertTrue(result, !result.contains("org.aspectj.testing"));
}
}
Pointcut pointcut = parser.parsePointcut();
parser.checkEof();
pointcut.check(null, struct.enclosingType.getWorld());
- if (!allowIf && pointcutString.indexOf("if()") >= 0 && hasIf(pointcut)) {
+ if (!allowIf && pointcutString.contains("if()") && hasIf(pointcut)) {
reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString + "'", struct);
return null;
}
// TAG: WeavingMessage
if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName();
- if (tName.indexOf("no debug info available") != -1) {
+ if (tName.contains("no debug info available")) {
tName = "no debug info available";
} else {
tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath());
*/
private String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
- if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) {
+ if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().contains("no debug info available")) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
if (binary != -1 && binary < takeFrom) {
// we have been woven by a binary aspect
String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1);
- if (pathToBinaryLoc.indexOf(".jar") != -1) {
+ if (pathToBinaryLoc.contains(".jar")) {
// only want to add the extra info if we're from a jar file
int lastSlash = pathToBinaryLoc.lastIndexOf('/');
if (lastSlash == -1) {
try {
unresolvedType = UnresolvedType.forName(name);
} catch (BCException bce) {
- if (bce.getMessage().indexOf("nameToSignature") == -1) {
+ if (!bce.getMessage().contains("nameToSignature")) {
bce.printStackTrace(System.err);
}
return null;
*/
public static String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
- if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) {
+ if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().contains("no debug info available")) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box
if (kind == ResolvedTypeMunger.Field) { // ITD FIELD
// String name = rtMunger.getSignature().toString();
String name = sig.getDeclaringType().getClassName() + "." + sig.getName();
- if (name.indexOf("$") != -1) {
+ if (name.contains("$")) {
name = name.substring(name.indexOf("$") + 1);
}
IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_FIELD, getBinarySourceLocation(
} else if (kind == ResolvedTypeMunger.Method) { // ITD
// METHOD
String name = sig.getDeclaringType().getClassName() + "." + sig.getName();
- if (name.indexOf("$") != -1) {
+ if (name.contains("$")) {
name = name.substring(name.indexOf("$") + 1);
}
IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_METHOD, getBinarySourceLocation(
return pe;
} else if (kind == ResolvedTypeMunger.Constructor) {
String name = sig.getDeclaringType().getClassName() + "." + sig.getDeclaringType().getClassName();
- if (name.indexOf("$") != -1) {
+ if (name.contains("$")) {
name = name.substring(name.indexOf("$") + 1);
}
IProgramElement pe = new ProgramElement(model, name, IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,
String record;
while ((null != (record = reader.readLine())) && (result == false)) {
if (record.startsWith("----")) currentHeading = record;
- else if ((record.indexOf(contents) != -1) && currentHeading.indexOf(heading) != -1) result = true;
+ else if ((record.contains(contents)) && currentHeading.contains(heading)) result = true;
}
reader.close();
}
String expected = "Type referred to is not an annotation type";
String msg = ((IMessage) mh.messages.get(0)).toString();
- assertTrue("Expected: " + expected + " but got " + msg, msg.indexOf(expected) != -1);
+ assertTrue("Expected: " + expected + " but got " + msg, msg.contains(expected));
}
public void testReferenceViaFormalToNonAnnotationType() {
String expected = "Type referred to is not an annotation type";
String msg = ((IMessage) mh.messages.get(0)).toString();
- assertTrue("Expected: " + expected + " but got " + msg, msg.indexOf(expected) != -1);
+ assertTrue("Expected: " + expected + " but got " + msg, msg.contains(expected));
// expected = "Binding not supported in @pcds (1.5.0 M1 limitation): null";
// msg = ((IMessage)mh.messages.get(1)).toString();
.parsePointcutExpression("bean(service.*");
fail("should not be able to parse bean(service.*)");
} catch(IllegalArgumentException ex) {
- assertTrue("contains bean",ex.getMessage().indexOf("bean") != -1);
+ assertTrue("contains bean", ex.getMessage().contains("bean"));
}
}
pc = parser.parsePointcutExpression("args(String)", null, new PointcutParameter[] { param });
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
- assertTrue("formal unbound", ex.getMessage().indexOf("formal unbound") != -1);
+ assertTrue("formal unbound", ex.getMessage().contains("formal unbound"));
}
try {
pc = parser.parsePointcutExpression("args(y)");
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
- assertTrue("no match for type name", ex.getMessage().indexOf("warning no match for this type name: y") != -1);
+ assertTrue("no match for type name", ex.getMessage().contains("warning no match for this type name: y"));
}
}
try {
p.parsePointcutExpression("this(FooBar)");
} catch (IllegalArgumentException ex) {
- assertTrue("should have xlint:invalidAbsoluteTypeName", ex.getMessage().indexOf("Xlint:invalidAbsoluteTypeName") != -1);
+ assertTrue("should have xlint:invalidAbsoluteTypeName", ex.getMessage().contains("Xlint:invalidAbsoluteTypeName"));
}
Properties props = new Properties();
props.put("invalidAbsoluteTypeName", "ignore");