下面列出了org.eclipse.jdt.core.dom.LineComment#org.eclipse.jdt.internal.compiler.util.Util 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Adds a problem to the provided CompilationResult object so that it will show up
* in the Problems/Warnings view.
*/
public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result,
boolean isWarning, String message, int sourceStart, int sourceEnd) {
if (result == null) return;
if (fileNameArray == null) fileNameArray = "(unknown).java".toCharArray();
int lineNumber = 0;
int columnNumber = 1;
int[] lineEnds = null;
lineNumber = sourceStart >= 0
? Util.getLineNumber(sourceStart, lineEnds = result.getLineSeparatorPositions(), 0, lineEnds.length-1)
: 0;
columnNumber = sourceStart >= 0
? Util.searchColumnNumber(result.getLineSeparatorPositions(), lineNumber,sourceStart)
: 0;
CategorizedProblem ecProblem = new LombokProblem(
fileNameArray, message, 0, new String[0],
isWarning ? ProblemSeverities.Warning : ProblemSeverities.Error,
sourceStart, sourceEnd, lineNumber, columnNumber);
result.record(ecProblem, null);
}
/**
* Checks if the completion is in the context of a method and on the type of one of its arguments
* Returns whether we found a completion node.
*/
private boolean checkRecoveredMethod() {
if (this.currentElement instanceof RecoveredMethod){
/* check if current awaiting identifier is the completion identifier */
if (this.indexOfAssistIdentifier() < 0) return false;
/* check if on line with an error already - to avoid completing inside
illegal type names e.g. int[<cursor> */
if (this.lastErrorEndPosition <= this.cursorLocation
&& Util.getLineNumber(this.lastErrorEndPosition, this.scanner.lineEnds, 0, this.scanner.linePtr)
== Util.getLineNumber(((CompletionScanner)this.scanner).completedIdentifierStart, this.scanner.lineEnds, 0, this.scanner.linePtr)){
return false;
}
RecoveredMethod recoveredMethod = (RecoveredMethod)this.currentElement;
/* only consider if inside method header */
if (!recoveredMethod.foundOpeningBrace
&& this.lastIgnoredToken == -1) {
//if (rParenPos < lParenPos){ // inside arguments
this.assistNode = this.getTypeReference(0);
this.lastCheckPoint = this.assistNode.sourceEnd + 1;
this.isOrphanCompletionNode = true;
return true;
}
}
return false;
}
public boolean visit(VariableDeclarationExpression node) {
if (!hasChildrenChanges(node)) {
return doVisitUnchangedChildren(node);
}
// same code as FieldDeclaration
int pos= node.getStartPosition();
if (node.getAST().apiLevel() == JLS2_INTERNAL) {
rewriteModifiers(node, INTERNAL_VDE_MODIFIERS_PROPERTY, pos);
} else {
rewriteModifiers2(node, VariableDeclarationExpression.MODIFIERS2_PROPERTY, pos);
}
pos= rewriteRequiredNode(node, VariableDeclarationExpression.TYPE_PROPERTY);
rewriteNodeList(node, VariableDeclarationExpression.FRAGMENTS_PROPERTY, pos, Util.EMPTY_STRING, ", "); //$NON-NLS-1$
return false;
}
public String nameForReporting(ASTNode location, ReferenceContext referenceContext) {
if (this.name == UNASSIGNED_CLOSEABLE_NAME) {
if (location != null && referenceContext != null) {
CompilationResult compResult = referenceContext.compilationResult();
if (compResult != null) {
int[] lineEnds = compResult.getLineSeparatorPositions();
int resourceLine = Util.getLineNumber(this.sourceStart, lineEnds , 0, lineEnds.length-1);
int reportLine = Util.getLineNumber(location.sourceStart, lineEnds , 0, lineEnds.length-1);
if (resourceLine != reportLine) {
char[] replacement = Integer.toString(resourceLine).toCharArray();
return String.valueOf(CharOperation.replace(UNASSIGNED_CLOSEABLE_NAME_TEMPLATE, TEMPLATE_ARGUMENT, replacement));
}
}
}
}
return String.valueOf(this.name);
}
public void resolveJavadoc() {
if (this.binding == null || this.javadoc != null) {
super.resolveJavadoc();
} else if ((this.bits & ASTNode.IsDefaultConstructor) == 0) {
if (this.binding.declaringClass != null && !this.binding.declaringClass.isLocalType()) {
// Set javadoc visibility
int javadocVisibility = this.binding.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
ClassScope classScope = this.scope.classScope();
ProblemReporter reporter = this.scope.problemReporter();
int severity = reporter.computeSeverity(IProblem.JavadocMissing);
if (severity != ProblemSeverities.Ignore) {
if (classScope != null) {
javadocVisibility = Util.computeOuterMostVisibility(classScope.referenceType(), javadocVisibility);
}
int javadocModifiers = (this.binding.modifiers & ~ExtraCompilerModifiers.AccVisibilityMASK) | javadocVisibility;
reporter.javadocMissing(this.sourceStart, this.sourceEnd, severity, javadocModifiers);
}
}
}
}
public boolean visit(MethodRef node) {
if (!hasChildrenChanges(node)) {
return doVisitUnchangedChildren(node);
}
rewriteNode(node, MethodRef.QUALIFIER_PROPERTY, node.getStartPosition(), ASTRewriteFormatter.NONE);
int pos= rewriteRequiredNode(node, MethodRef.NAME_PROPERTY);
if (isChanged(node, MethodRef.PARAMETERS_PROPERTY)) {
// eval position after opening parent
try {
int startOffset= getScanner().getTokenEndOffset(TerminalTokens.TokenNameLPAREN, pos);
rewriteNodeList(node, MethodRef.PARAMETERS_PROPERTY, startOffset, Util.EMPTY_STRING, ", "); //$NON-NLS-1$
} catch (CoreException e) {
handleException(e);
}
} else {
voidVisit(node, MethodRef.PARAMETERS_PROPERTY);
}
return false;
}
/**
* Extracts the type bounds' signatures from the given intersection type signature.
* Returns an empty array if the type signature is not an intersection type signature.
*
* @param intersectionTypeSignature the intersection type signature
* @return the signatures of the type bounds
* @exception IllegalArgumentException if the signature is syntactically incorrect
*
* @since 3.7.1
*/
public static char[][] getIntersectionTypeBounds(char[] intersectionTypeSignature) throws IllegalArgumentException {
if (getTypeSignatureKind(intersectionTypeSignature) != INTERSECTION_TYPE_SIGNATURE) {
return CharOperation.NO_CHAR_CHAR;
}
ArrayList args = new ArrayList();
int i = 1; // skip the '|'
int length = intersectionTypeSignature.length;
for (;;) {
int e = Util.scanClassTypeSignature(intersectionTypeSignature, i);
if (e < 0) {
throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$
}
args.add(CharOperation.subarray(intersectionTypeSignature, i, e + 1));
if (e == length - 1) {
int size = args.size();
char[][] result = new char[size][];
args.toArray(result);
return result;
} else if (intersectionTypeSignature[e + 1] != C_COLON) {
throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$
}
i = e + 2; // add one to skip C_COLON
}
}
public static File[][] getLibrariesFiles(File[] files) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return Util.isPotentialZipArchive(name);
}
};
final int filesLength = files.length;
File[][] result = new File[filesLength][];
for (int i = 0; i < filesLength; i++) {
File currentFile = files[i];
if (currentFile.exists() && currentFile.isDirectory()) {
result[i] = currentFile.listFiles(filter);
}
}
return result;
}
public int previousAvailableLineEnd(int position){
Parser parser = parser();
if (parser == null) return position;
Scanner scanner = parser.scanner;
if (scanner.lineEnds == null) return position;
int index = Util.getLineNumber(position, scanner.lineEnds, 0, scanner.linePtr);
if (index < 2) return position;
int previousLineEnd = scanner.lineEnds[index-2];
char[] source = scanner.source;
for (int i = previousLineEnd+1; i < position; i++){
if (!(source[i] == ' ' || source[i] == '\t')) return position;
}
return previousLineEnd;
}
public boolean isPackage(String qualifiedPackageName) {
if (this.packageCache != null)
return this.packageCache.containsKey(qualifiedPackageName);
this.packageCache = new Hashtable(41);
this.packageCache.put(Util.EMPTY_STRING, Util.EMPTY_STRING);
nextEntry : for (Enumeration e = this.zipFile.entries(); e.hasMoreElements(); ) {
String fileName = ((ZipEntry) e.nextElement()).getName();
// add the package name & all of its parent packages
int last = fileName.lastIndexOf('/');
while (last > 0) {
// extract the package name
String packageName = fileName.substring(0, last);
if (this.packageCache.containsKey(packageName))
continue nextEntry;
this.packageCache.put(packageName, packageName);
last = packageName.lastIndexOf('/');
}
}
return this.packageCache.containsKey(qualifiedPackageName);
}
public boolean visit(FieldDeclaration node) {
ASTNode javadoc= getChildNode(node, FieldDeclaration.JAVADOC_PROPERTY);
if (javadoc != null) {
javadoc.accept(this);
}
if (node.getAST().apiLevel() == JLS2_INTERNAL) {
printModifiers(getIntAttribute(node, INTERNAL_FIELD_MODIFIERS_PROPERTY), this.result);
} else {
visitList(node, FieldDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
}
getChildNode(node, FieldDeclaration.TYPE_PROPERTY).accept(this);
this.result.append(' ');
visitList(node, FieldDeclaration.FRAGMENTS_PROPERTY, String.valueOf(','));
this.result.append(';');
return false;
}
public boolean visit(SingleVariableDeclaration node) {
if (node.getAST().apiLevel() == JLS2_INTERNAL) {
printModifiers(getIntAttribute(node, INTERNAL_VARIABLE_MODIFIERS_PROPERTY), this.result);
} else {
visitList(node, SingleVariableDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
}
getChildNode(node, SingleVariableDeclaration.TYPE_PROPERTY).accept(this);
if (node.getAST().apiLevel() >= AST.JLS8 && node.isVarargs()) {
visitList(node, SingleVariableDeclaration.VARARGS_ANNOTATIONS_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
}
if (node.getAST().apiLevel() >= JLS3_INTERNAL) {
if (getBooleanAttribute(node, SingleVariableDeclaration.VARARGS_PROPERTY)) {
this.result.append("...");//$NON-NLS-1$
}
}
this.result.append(' ');
getChildNode(node, SingleVariableDeclaration.NAME_PROPERTY).accept(this);
visitExtraDimensions(node, INTERNAL_VARIABLE_EXTRA_DIMENSIONS_PROPERTY, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY);
ASTNode initializer= getChildNode(node, SingleVariableDeclaration.INITIALIZER_PROPERTY);
if (initializer != null) {
this.result.append('=');
initializer.accept(this);
}
return false;
}
public boolean visit(AnnotationTypeMemberDeclaration node) {
ASTNode javadoc= getChildNode(node, AnnotationTypeMemberDeclaration.JAVADOC_PROPERTY);
if (javadoc != null) {
javadoc.accept(this);
}
visitList(node, AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
getChildNode(node, AnnotationTypeMemberDeclaration.TYPE_PROPERTY).accept(this);
this.result.append(' ');
getChildNode(node, AnnotationTypeMemberDeclaration.NAME_PROPERTY).accept(this);
this.result.append("()");//$NON-NLS-1$
ASTNode def= getChildNode(node, AnnotationTypeMemberDeclaration.DEFAULT_PROPERTY);
if (def != null) {
this.result.append(" default ");//$NON-NLS-1$
def.accept(this);
}
this.result.append(';');
return false;
}
public boolean visit(NormalAnnotation node) {
if (!hasChildrenChanges(node)) {
return doVisitUnchangedChildren(node);
}
int pos= rewriteRequiredNode(node, NormalAnnotation.TYPE_NAME_PROPERTY);
if (isChanged(node, NormalAnnotation.VALUES_PROPERTY)) {
// eval position after opening parent
try {
int startOffset= getScanner().getTokenEndOffset(TerminalTokens.TokenNameLPAREN, pos);
rewriteNodeList(node, NormalAnnotation.VALUES_PROPERTY, startOffset, Util.EMPTY_STRING, ", "); //$NON-NLS-1$
} catch (CoreException e) {
handleException(e);
}
} else {
voidVisit(node, NormalAnnotation.VALUES_PROPERTY);
}
return false;
}
public boolean visit(WildcardType node) {
if (node.getAST().apiLevel() >= AST.JLS8) {
visitList(node, WildcardType.ANNOTATIONS_PROPERTY, String.valueOf(' '), Util.EMPTY_STRING, String.valueOf(' '));
}
this.result.append('?');
ASTNode bound = getChildNode(node, WildcardType.BOUND_PROPERTY);
if (bound != null) {
if (getBooleanAttribute(node, WildcardType.UPPER_BOUND_PROPERTY)) {
this.result.append(" extends ");//$NON-NLS-1$
} else {
this.result.append(" super ");//$NON-NLS-1$
}
bound.accept(this);
}
return false;
}
public boolean visit(ConstructorInvocation node) {
if (!hasChildrenChanges(node)) {
return doVisitUnchangedChildren(node);
}
int pos= node.getStartPosition();
if (node.getAST().apiLevel() >= JLS3_INTERNAL) {
pos= rewriteOptionalTypeParameters(node, ConstructorInvocation.TYPE_ARGUMENTS_PROPERTY, pos, Util.EMPTY_STRING, false, false);
}
try {
pos= getScanner().getTokenEndOffset(TerminalTokens.TokenNameLPAREN, pos);
rewriteNodeList(node, ConstructorInvocation.ARGUMENTS_PROPERTY, pos, Util.EMPTY_STRING, ", "); //$NON-NLS-1$
} catch (CoreException e) {
handleException(e);
}
return false;
}
public String toString() {
String s = Util.EMPTY_STRING;
s = s + "elementKindStack : int[] = {"; //$NON-NLS-1$
for (int i = 0; i <= this.elementPtr; i++) {
s = s + String.valueOf(this.elementKindStack[i]) + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "elementInfoStack : int[] = {"; //$NON-NLS-1$
for (int i = 0; i <= this.elementPtr; i++) {
s = s + String.valueOf(this.elementInfoStack[i]) + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
return s + super.toString();
}
public boolean visit(UnionType node) {
if (!hasChildrenChanges(node)) {
return doVisitUnchangedChildren(node);
}
rewriteNodeList(node, UnionType.TYPES_PROPERTY, node.getStartPosition(), Util.EMPTY_STRING, " | "); //$NON-NLS-1$
return false;
}
public static ClassFileReader read(File file, boolean fullyInitialize) throws ClassFormatException, IOException {
byte classFileBytes[] = Util.getFileByteContent(file);
ClassFileReader classFileReader = new ClassFileReader(classFileBytes, file.getAbsolutePath().toCharArray());
if (fullyInitialize) {
classFileReader.initialize();
}
return classFileReader;
}
private String getPreserveEmptyLines(int count, int emptyLinesRules) {
if (count == 0) {
int currentIndentationLevel = this.indentationLevel;
int useAlignmentBreakIndentation = useAlignmentBreakIndentation(emptyLinesRules);
switch (useAlignmentBreakIndentation) {
case PRESERVE_EMPTY_LINES_DO_NOT_USE_ANY_INDENTATION:
return Util.EMPTY_STRING;
default:
// Return the new indented line
StringBuffer buffer = new StringBuffer(getNewLine());
printIndentationIfNecessary(buffer);
if (useAlignmentBreakIndentation == PRESERVE_EMPTY_LINES_USE_TEMPORARY_INDENTATION) {
this.indentationLevel = currentIndentationLevel;
}
return buffer.toString();
}
}
if (this.blank_lines_between_import_groups >= 0) {
useAlignmentBreakIndentation(emptyLinesRules);
return getEmptyLines(this.blank_lines_between_import_groups);
}
if (this.formatter.preferences.number_of_empty_lines_to_preserve != 0) {
useAlignmentBreakIndentation(emptyLinesRules);
int linesToPreserve = Math.min(count, this.formatter.preferences.number_of_empty_lines_to_preserve);
return getEmptyLines(linesToPreserve);
}
return getNewLine();
}
public String createIndentationString(final int indentationLevel) {
if (indentationLevel < 0) {
throw new IllegalArgumentException();
}
int tabs = 0;
int spaces = 0;
switch(this.preferences.tab_char) {
case DefaultCodeFormatterOptions.SPACE :
spaces = indentationLevel * this.preferences.tab_size;
break;
case DefaultCodeFormatterOptions.TAB :
tabs = indentationLevel;
break;
case DefaultCodeFormatterOptions.MIXED :
int tabSize = this.preferences.tab_size;
if (tabSize != 0) {
int spaceEquivalents = indentationLevel * this.preferences.indentation_size;
tabs = spaceEquivalents / tabSize;
spaces = spaceEquivalents % tabSize;
}
break;
default:
return Util.EMPTY_STRING;
}
if (tabs == 0 && spaces == 0) {
return Util.EMPTY_STRING;
}
StringBuffer buffer = new StringBuffer(tabs + spaces);
for(int i = 0; i < tabs; i++) {
buffer.append('\t');
}
for(int i = 0; i < spaces; i++) {
buffer.append(' ');
}
return buffer.toString();
}
private TextEdit formatComment(int kind, String source, int indentationLevel, String lineSeparator, IRegion[] regions) {
Object oldOption = oldCommentFormatOption();
boolean isFormattingComments = false;
if (oldOption == null) {
switch (kind & K_MASK) {
case K_SINGLE_LINE_COMMENT:
isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT));
break;
case K_MULTI_LINE_COMMENT:
isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT));
break;
case K_JAVA_DOC:
isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT));
}
} else {
isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(oldOption);
}
if (isFormattingComments) {
if (lineSeparator != null) {
this.preferences.line_separator = lineSeparator;
} else {
this.preferences.line_separator = Util.LINE_SEPARATOR;
}
this.preferences.initial_indentation_level = indentationLevel;
if (this.codeSnippetParsingUtil == null) this.codeSnippetParsingUtil = new CodeSnippetParsingUtil();
this.codeSnippetParsingUtil.parseCompilationUnit(source.toCharArray(), getDefaultCompilerOptions(), true);
this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, true);
IRegion coveredRegion = getCoveredRegion(regions);
int start = coveredRegion.getOffset();
int end = start + coveredRegion.getLength();
this.newCodeFormatter.formatComment(kind, source, start, end, indentationLevel);
return this.newCodeFormatter.scribe.getRootEdit();
}
return null;
}
private TextEdit formatCompilationUnit(String source, int indentationLevel, String lineSeparator, IRegion[] regions, boolean includeComments) {
CompilationUnitDeclaration compilationUnitDeclaration = this.codeSnippetParsingUtil.parseCompilationUnit(source.toCharArray(), getDefaultCompilerOptions(), true);
if (lineSeparator != null) {
this.preferences.line_separator = lineSeparator;
} else {
this.preferences.line_separator = Util.LINE_SEPARATOR;
}
this.preferences.initial_indentation_level = indentationLevel;
this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, includeComments);
return this.newCodeFormatter.format(source, compilationUnitDeclaration);
}
private TextEdit internalFormatClassBodyDeclarations(String source, int indentationLevel, String lineSeparator, ASTNode[] bodyDeclarations, IRegion[] regions, boolean includeComments) {
if (lineSeparator != null) {
this.preferences.line_separator = lineSeparator;
} else {
this.preferences.line_separator = Util.LINE_SEPARATOR;
}
this.preferences.initial_indentation_level = indentationLevel;
this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, includeComments);
return this.newCodeFormatter.format(source, bodyDeclarations);
}
private TextEdit internalFormatExpression(String source, int indentationLevel, String lineSeparator, Expression expression, IRegion[] regions, boolean includeComments) {
if (lineSeparator != null) {
this.preferences.line_separator = lineSeparator;
} else {
this.preferences.line_separator = Util.LINE_SEPARATOR;
}
this.preferences.initial_indentation_level = indentationLevel;
this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, includeComments);
TextEdit textEdit = this.newCodeFormatter.format(source, expression);
return textEdit;
}
public static String versionFromJdkLevel(long jdkLevel) {
switch ((int)(jdkLevel>>16)) {
case ClassFileConstants.MAJOR_VERSION_1_1 :
if (jdkLevel == ClassFileConstants.JDK1_1)
return VERSION_1_1;
break;
case ClassFileConstants.MAJOR_VERSION_1_2 :
if (jdkLevel == ClassFileConstants.JDK1_2)
return VERSION_1_2;
break;
case ClassFileConstants.MAJOR_VERSION_1_3 :
if (jdkLevel == ClassFileConstants.JDK1_3)
return VERSION_1_3;
break;
case ClassFileConstants.MAJOR_VERSION_1_4 :
if (jdkLevel == ClassFileConstants.JDK1_4)
return VERSION_1_4;
break;
case ClassFileConstants.MAJOR_VERSION_1_5 :
if (jdkLevel == ClassFileConstants.JDK1_5)
return VERSION_1_5;
break;
case ClassFileConstants.MAJOR_VERSION_1_6 :
if (jdkLevel == ClassFileConstants.JDK1_6)
return VERSION_1_6;
break;
case ClassFileConstants.MAJOR_VERSION_1_7 :
if (jdkLevel == ClassFileConstants.JDK1_7)
return VERSION_1_7;
break;
case ClassFileConstants.MAJOR_VERSION_1_8 :
if (jdkLevel == ClassFileConstants.JDK1_8)
return VERSION_1_8;
break;
}
return Util.EMPTY_STRING; // unknown version
}
public void updateContext(InvocationSite invocationSite, CompilationResult unitResult) {
if (this.problem == null) return;
if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
this.problem.setSourceStart(invocationSite.sourceStart());
this.problem.setSourceEnd(invocationSite.sourceEnd());
int[] lineEnds = unitResult.getLineSeparatorPositions();
this.problem.setSourceLineNumber(Util.getLineNumber(invocationSite.sourceStart(), lineEnds, 0, lineEnds.length-1));
this.compilationResult = unitResult;
}
public void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException {
File f = new File(pathToJar);
if (!f.exists()) {
throw new FileNotFoundException(pathToJar + " not found"); //$NON-NLS-1$
}
IndexLocation indexLocation = new FileIndexLocation(new File(pathToIndexFile));
Index index = new Index(indexLocation, pathToJar, false /*reuse index file*/);
SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
index.separator = JAR_SEPARATOR;
ZipFile zip = new ZipFile(pathToJar);
try {
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
// iterate each entry to index it
ZipEntry ze = (ZipEntry) e.nextElement();
String zipEntryName = ze.getName();
if (Util.isClassFileName(zipEntryName)) {
final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
JavaSearchDocument entryDocument = new JavaSearchDocument(ze, new Path(pathToJar), classFileBytes, participant);
entryDocument.setIndex(index);
new BinaryIndexer(entryDocument).indexDocument();
}
}
index.save();
} finally {
zip.close();
}
return;
}
public static boolean isDeclaringPackageFragment(IPackageFragment packageFragment, ReferenceBinding typeBinding) {
char[] fileName = typeBinding.getFileName();
if (fileName != null) {
// retrieve the actual file name from the full path (sources are generally only containing it already)
fileName = CharOperation.replaceOnCopy(fileName, '/', '\\'); // ensure to not do any side effect on file name (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=136016)
fileName = CharOperation.lastSegment(fileName, '\\');
try {
switch (packageFragment.getKind()) {
case IPackageFragmentRoot.K_SOURCE :
if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(fileName) || !packageFragment.getCompilationUnit(new String(fileName)).exists()) {
return false; // unit doesn't live in selected package
}
break;
case IPackageFragmentRoot.K_BINARY :
// if (Util.isJavaFileName(fileName)) { // binary with attached source
// int length = fileName.length;
// System.arraycopy(fileName, 0, fileName = new char[length], 0, length - 4); // copy all but extension
// System.arraycopy(SuffixConstants.SUFFIX_class, 0, fileName, length - 4, 4);
// }
if (!Util.isClassFileName(fileName) || !packageFragment.getClassFile(new String(fileName)).exists()) {
return false; // classfile doesn't live in selected package
}
break;
}
} catch(JavaModelException e) {
// unable to determine kind; tolerate this match
}
}
return true; // by default, do not eliminate
}
public char[] getContents() {
if (this.contents != null)
return this.contents; // answer the cached source
// otherwise retrieve it
try {
return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding);
} catch (IOException e) {
// could not read file: returns an empty array
}
return CharOperation.NO_CHAR;
}