Java Code Examples for org.eclipse.jdt.core.ToolFactory

The following examples show how to use org.eclipse.jdt.core.ToolFactory. These examples are extracted from open source projects. 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 Project: eclipse.jdt.ls   Source File: Util.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) {
	if (start == end) {
		return true;
	}
	Assert.isTrue(start <= end);
	String trimmedText = buffer.getText(start, end - start).trim();
	if (0 == trimmedText.length()) {
		return true;
	} else {
		IScanner scanner = ToolFactory.createScanner(false, false, false, null);
		scanner.setSource(trimmedText.toCharArray());
		try {
			return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF;
		} catch (InvalidInputException e) {
			return false;
		}
	}
}
 
Example 2
Source Project: spotbugs   Source File: MarkerUtil.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param source
 *            must be not null
 * @param range
 *            can be null
 * @return may return null, otherwise an initialized scanner which may
 *         answer which source offset index belongs to which source line
 * @throws JavaModelException
 */
private static IScanner initScanner(IType source, ISourceRange range) throws JavaModelException {
    if (range == null) {
        return null;
    }
    char[] charContent = getContent(source);
    if (charContent == null) {
        return null;
    }
    IScanner scanner = ToolFactory.createScanner(false, false, false, true);
    scanner.setSource(charContent);
    int offset = range.getOffset();
    try {
        while (scanner.getNextToken() != ITerminalSymbols.TokenNameEOF) {
            // do nothing, just wait for the end of stream
            if (offset <= scanner.getCurrentTokenEndPosition()) {
                break;
            }
        }
    } catch (InvalidInputException e) {
        FindbugsPlugin.getDefault().logException(e, "Could not init scanner for type: " + source);
    }
    return scanner;
}
 
Example 3
Source Project: gwt-eclipse-plugin   Source File: TypeCreator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private String formatJava(IType type) throws JavaModelException {
  String source = type.getCompilationUnit().getSource();
  CodeFormatter formatter = ToolFactory.createCodeFormatter(type.getJavaProject().getOptions(true));
  TextEdit formatEdit = formatter.format(CodeFormatterFlags.getFlagsForCompilationUnitFormat(), source, 0,
      source.length(), 0, lineDelimiter);
  if (formatEdit == null) {
    CorePluginLog.logError("Could not format source for " + type.getCompilationUnit().getElementName());
    return source;
  }

  Document document = new Document(source);
  try {
    formatEdit.apply(document);
    source = document.get();
  } catch (BadLocationException e) {
    CorePluginLog.logError(e);
  }

  source = Strings.trimLeadingTabsAndSpaces(source);
  return source;
}
 
Example 4
/**
 * Removes comments and whitespace
 * @param reference the type reference
 * @return the reference only consisting of dots and java identifier characters
 */
public static String normalizeReference(String reference) {
	IScanner scanner= ToolFactory.createScanner(false, false, false, false);
	scanner.setSource(reference.toCharArray());
	StringBuffer sb= new StringBuffer();
	try {
		int tokenType= scanner.getNextToken();
		while (tokenType != ITerminalSymbols.TokenNameEOF) {
			sb.append(scanner.getRawTokenSource());
			tokenType= scanner.getNextToken();
		}
	} catch (InvalidInputException e) {
		Assert.isTrue(false, reference);
	}
	reference= sb.toString();
	return reference;
}
 
Example 5
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) {
	if (start == end)
		return true;
	Assert.isTrue(start <= end);
	String trimmedText= buffer.getText(start, end - start).trim();
	if (0 == trimmedText.length()) {
		return true;
	} else {
		IScanner scanner= ToolFactory.createScanner(false, false, false, null);
		scanner.setSource(trimmedText.toCharArray());
		try {
			return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF;
		} catch (InvalidInputException e) {
			return false;
		}
	}
}
 
Example 6
public static Long calculateSerialVersionId(ITypeBinding typeBinding, final IProgressMonitor monitor) throws CoreException, IOException {
	try {
		IFile classfileResource= getClassfile(typeBinding);
		if (classfileResource == null)
			return null;

		InputStream contents= classfileResource.getContents();
		try {
			IClassFileReader cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.ALL);
			if (cfReader != null) {
				return calculateSerialVersionId(cfReader);
			}
		} finally {
			contents.close();
		}
		return null;
	} finally {
		if (monitor != null)
			monitor.done();
	}
}
 
Example 7
Source Project: aws-sdk-java-v2   Source File: JavaCodeFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JavaCodeFormatter using the default formatter options and
 * optionally applying user provided options on top.
 *
 * @param overrideOptions user provided options to apply on top of defaults
 */
public JavaCodeFormatter(final Map<String, Object> overrideOptions) {
    Map formatterOptions = new HashMap<>(DEFAULT_FORMATTER_OPTIONS);
    if (overrideOptions != null) {
        formatterOptions.putAll(overrideOptions);
    }

    this.codeFormatter = ToolFactory.createCodeFormatter(formatterOptions,
                                                         ToolFactory.M_FORMAT_EXISTING);
}
 
Example 8
Source Project: aws-sdk-java-v2   Source File: JavaCodeFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JavaCodeFormatter using the default formatter options and
 * optionally applying user provided options on top.
 *
 * @param overrideOptions user provided options to apply on top of defaults
 */
public JavaCodeFormatter(final Map<String, Object> overrideOptions) {
    Map formatterOptions = new HashMap<>(DEFAULT_FORMATTER_OPTIONS);
    if (overrideOptions != null) {
        formatterOptions.putAll(overrideOptions);
    }

    this.codeFormatter = ToolFactory.createCodeFormatter(formatterOptions,
                                                         ToolFactory.M_FORMAT_EXISTING);
}
 
Example 9
@SuppressWarnings("try")
public static String formatEclipseStyle(final Properties prop, final String content) {
  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("JavaFormatter.formatEclipseStyle")) {
    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("size", content.length()).build("args"));

    final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(prop);
    final IDocument document = new Document(content);
    final TextEdit textEdit =
        codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
            content,
            0,
            content.length(),
            0,
            null);
    if (nonNull(textEdit)) {
      textEdit.apply(document);
      return ensureCorrectNewLines(document.get());
    } else {
      return content;
    }
  } catch (Throwable e) {
    return content;
  }
}
 
Example 10
private String getContent(byte[] bytes, IProgressMonitor monitor) throws CoreException {
	ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler();
	String disassembledByteCode = null;
	try {
		disassembledByteCode = disassembler.disassemble(bytes, LF, ClassFileBytesDisassembler.WORKING_COPY);
		if (disassembledByteCode != null) {
			disassembledByteCode = DISASSEMBLED_HEADER + disassembledByteCode;
		}
	} catch (ClassFormatException e) {
		throw new CoreException(new Status(Status.ERROR, "", "Error disassembling", e));
	}
	return disassembledByteCode;
}
 
Example 11
Source Project: eclipse.jdt.ls   Source File: RefactoringScanner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void scan(ICompilationUnit cu)	throws JavaModelException {
		char[] chars= cu.getBuffer().getCharacters();
		fMatches= new HashSet<>();
		fScanner= ToolFactory.createScanner(true, true, false, true);
		fScanner.setSource(chars);

//		IImportContainer importContainer= cu.getImportContainer();
//		if (importContainer.exists())
//			fNoFlyZone= importContainer.getSourceRange();
//		else
//			fNoFlyZone= null;

		doScan();
		fScanner= null;
	}
 
Example 12
Source Project: eclipse.jdt.ls   Source File: RefactoringScanner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Scan the given text.
 * <p>
 * <strong>NOTE:</strong> Use only for testing.
 * </p>
 *
 * @param text the text
 */
public void scan(String text) {
	char[] chars= text.toCharArray();
	fMatches= new HashSet<>();
	fScanner= ToolFactory.createScanner(true, true, false, true);
	fScanner.setSource(chars);
	doScan();
	fScanner= null;
}
 
Example 13
protected IScanner getScanner(ICompilationUnit unit) {
	IJavaProject project= unit.getJavaProject();
	if (project.equals(fProjectCache)) {
		return fScannerCache;
	}

	fProjectCache= project;
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScannerCache= ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
	return fScannerCache;
}
 
Example 14
Source Project: eclipse.jdt.ls   Source File: NLSScanner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static NLSLine[] scan(ICompilationUnit cu) throws JavaModelException, BadLocationException, InvalidInputException {
	IJavaProject javaProject= cu.getJavaProject();
	IScanner scanner= null;
	if (javaProject != null) {
		String complianceLevel= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
		scanner= ToolFactory.createScanner(true, true, true, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(true, true, false, true);
	}
	return scan(scanner, cu.getBuffer().getCharacters());
}
 
Example 15
Source Project: coming   Source File: SJavaTokenComparator.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a token comparator for the given string.
 *
 * @param text the text to be tokenized
 * @param textTokenComparatorFactory a factory to create text token comparators
 */
public SJavaTokenComparator(String text) {


  fText= text;

  int length= fText.length();
  fStarts= new int[length];
  fLengths= new int[length];
  fTokens= new String[length];
  fCount= 0;

  IScanner scanner= ToolFactory.createScanner(true, false, false, false); // returns comments & whitespace
  scanner.setSource(fText.toCharArray());
  int endPos= 0;
  try {
    int tokenType;
    while ((tokenType= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) {
      int start= scanner.getCurrentTokenStartPosition();
      int end= scanner.getCurrentTokenEndPosition()+1;
      // Comments are treated as a single token (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=78063)
      if (!TokenScanner.isComment(tokenType)) {
        recordTokenRange(start, end - start);
      }
      endPos= end;
    }
  } catch (InvalidInputException ex) {
    // We couldn't parse part of the input. Fall through and make the rest a single token
  }
  // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=13907
  if (endPos < length) {
    recordTokenRange(endPos, length - endPos);
  }
}
 
Example 16
Source Project: gwt-eclipse-plugin   Source File: TypeCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private boolean isValidComment(String template) {
  IScanner scanner = ToolFactory.createScanner(true, false, false, false);
  scanner.setSource(template.toCharArray());
  try {
    int next = scanner.getNextToken();
    while (TokenScanner.isComment(next)) {
      next = scanner.getNextToken();
    }
    return next == ITerminalSymbols.TokenNameEOF;
  } catch (InvalidInputException e) {
    // If there are lexical errors, the comment is invalid
  }
  return false;
}
 
Example 17
Source Project: celerio   Source File: EclipseCodeFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "deprecation"})
public void setFormatterSettings(List<Setting> settings) {

    // // change the option to wrap each enum constant on a new line
    // options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
    // DefaultCodeFormatterConstants.createAlignmentValue(true,
    // DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
    // DefaultCodeFormatterConstants.INDENT_ON_COLUMN));
    //
    if (settings != null) {
        options = newHashMap();
        for (Setting s : settings) {
            options.put(s.getId(), s.getValue());
        }
    } else {
        options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

        options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
        options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
        options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);

        options.put(JavaCore.FORMATTER_LINE_SPLIT, "160");
        options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
        options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
    }

    // instanciate the default code formatter with the given options
    codeFormatter = ToolFactory.createCodeFormatter(options);
}
 
Example 18
Source Project: jenerate   Source File: JavaCodeFormatterImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String formatCode(IType objectClass, String source) throws JavaModelException, BadLocationException {
    String lineDelim = getLineDelimiterUsed(objectClass);
    int indent = getUsedIndentation(objectClass) + 1;
    TextEdit textEdit = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            source, 0, source.length(), indent, lineDelim);
    if (textEdit == null) {
        return source;
    }
    Document document = new Document(source);
    textEdit.apply(document);
    return document.get();
}
 
Example 19
private boolean isValidComment(String template) {
	IScanner scanner= ToolFactory.createScanner(true, false, false, false);
	scanner.setSource(template.toCharArray());
	try {
		int next= scanner.getNextToken();
		while (TokenScanner.isComment(next)) {
			next= scanner.getNextToken();
		}
		return next == ITerminalSymbols.TokenNameEOF;
	} catch (InvalidInputException e) {
	}
	return false;
}
 
Example 20
protected IScanner getScanner(ICompilationUnit unit) {
	IJavaProject project= unit.getJavaProject();
	if (project.equals(fProjectCache))
		return fScannerCache;

	fProjectCache= project;
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScannerCache= ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
	return fScannerCache;
}
 
Example 21
public void scan(ICompilationUnit cu)	throws JavaModelException {
		char[] chars= cu.getBuffer().getCharacters();
		fMatches= new HashSet<TextMatch>();
		fScanner= ToolFactory.createScanner(true, true, false, true);
		fScanner.setSource(chars);

//		IImportContainer importContainer= cu.getImportContainer();
//		if (importContainer.exists())
//			fNoFlyZone= importContainer.getSourceRange();
//		else
//			fNoFlyZone= null;

		doScan();
		fScanner= null;
	}
 
Example 22
/**
 * Scan the given text.
 * <p>
 * <strong>NOTE:</strong> Use only for testing.
 * </p>
 * 
 * @param text the text
 */
public void scan(String text) {
	char[] chars= text.toCharArray();
	fMatches= new HashSet<TextMatch>();
	fScanner= ToolFactory.createScanner(true, true, false, true);
	fScanner.setSource(chars);
	doScan();
	fScanner= null;
}
 
Example 23
public static NLSLine[] scan(ICompilationUnit cu) throws JavaModelException, BadLocationException, InvalidInputException {
	IJavaProject javaProject= cu.getJavaProject();
	IScanner scanner= null;
	if (javaProject != null) {
		String complianceLevel= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
		String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
		scanner= ToolFactory.createScanner(true, true, true, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(true, true, false, true);
	}
	return scan(scanner, cu.getBuffer().getCharacters());
}
 
Example 24
/**
 * A visitor that maps a selection to a given ASTNode. The result node is
 * determined as follows:
 * <ul>
 *   <li>first the visitor tries to find a node that is covered by <code>start</code> and
 *       <code>length</code> where either <code>start</code> and <code>length</code> exactly
 *       matches the node or where the text covered before and after the node only consists
 *       of white spaces or comments.</li>
 * 	 <li>if no such node exists than the node that encloses the range defined by
 *       start and end is returned.</li>
 *   <li>if the length is zero than also nodes are considered where the node's
 *       start or end position matches <code>start</code>.</li>
 *   <li>otherwise <code>null</code> is returned.</li>
 * </ul>
 *
 * @param root the root node from which the search starts
 * @param start the start offset
 * @param length the length
 * @param source the source of the compilation unit
 *
 * @return the result node
 * @throws JavaModelException if an error occurs in the Java model
 *
 * @since		3.0
 */
public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException {
	NodeFinder finder= new NodeFinder(start, length);
	root.accept(finder);
	ASTNode result= finder.getCoveredNode();
	if (result == null)
		return null;
	Selection selection= Selection.createFromStartLength(start, length);
	if (selection.covers(result)) {
		IBuffer buffer= source.getBuffer();
		if (buffer != null) {
			IScanner scanner= ToolFactory.createScanner(false, false, false, false);
			scanner.setSource(buffer.getText(start, length).toCharArray());
			try {
				int token= scanner.getNextToken();
				if (token != ITerminalSymbols.TokenNameEOF) {
					int tStart= scanner.getCurrentTokenStartPosition();
					if (tStart == result.getStartPosition() - start) {
						scanner.resetTo(tStart + result.getLength(), length - 1);
						token= scanner.getNextToken();
						if (token == ITerminalSymbols.TokenNameEOF)
							return result;
					}
				}
			} catch (InvalidInputException e) {
			}
		}
	}
	return finder.getCoveringNode();
}
 
Example 25
/**
 * Creates a TokenScanner
 * @param document The textbuffer to create the scanner on
 * @param project the current Java project
 */
public TokenScanner(IDocument document, IJavaProject project) {
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScanner= ToolFactory.createScanner(true, false, false, sourceLevel, complianceLevel); // no line info required
	fScanner.setSource(document.get().toCharArray());
	fDocument= document;
	fEndPosition= fScanner.getSource().length - 1;
}
 
Example 26
/**
 * Creates a TokenScanner
 * @param typeRoot The type root to scan on
 * @throws CoreException thrown if the buffer cannot be accessed
 */
public TokenScanner(ITypeRoot typeRoot) throws CoreException {
	IJavaProject project= typeRoot.getJavaProject();
	IBuffer buffer= typeRoot.getBuffer();
	if (buffer == null) {
		throw new CoreException(createError(DOCUMENT_ERROR, "Element has no source", null)); //$NON-NLS-1$
	}
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScanner= ToolFactory.createScanner(true, false, true, sourceLevel, complianceLevel); // line info required

	fScanner.setSource(buffer.getCharacters());
	fDocument= null; // use scanner for line information
	fEndPosition= fScanner.getSource().length - 1;
}
 
Example 27
private boolean isValidComment(String template) {
	IScanner scanner= ToolFactory.createScanner(true, false, false, false);
	scanner.setSource(template.toCharArray());
	try {
		int next= scanner.getNextToken();
		while (TokenScanner.isComment(next)) {
			next= scanner.getNextToken();
		}
		return next == ITerminalSymbols.TokenNameEOF;
	} catch (InvalidInputException e) {
	}
	return false;
}
 
Example 28
private boolean isValidComment(String template) {
	IScanner scanner= ToolFactory.createScanner(true, false, false, false);
	scanner.setSource(template.toCharArray());
	try {
		int next= scanner.getNextToken();
		while (TokenScanner.isComment(next)) {
			next= scanner.getNextToken();
		}
		return next == ITerminalSymbols.TokenNameEOF;
	} catch (InvalidInputException e) {
	}
	return false;
}
 
Example 29
private static int firstOpeningBraceOffset(IInitializer iInitializer) throws JavaModelException {
	try {
		IScanner scanner= ToolFactory.createScanner(false, false, false, false);
		scanner.setSource(iInitializer.getSource().toCharArray());
		int token= scanner.getNextToken();
		while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLBRACE)
			token= scanner.getNextToken();
		if (token == ITerminalSymbols.TokenNameLBRACE)
			return iInitializer.getSourceRange().getOffset() + scanner.getCurrentTokenStartPosition() + scanner.getRawTokenSource().length;
		return iInitializer.getSourceRange().getOffset();
	} catch (InvalidInputException e) {
		return iInitializer.getSourceRange().getOffset();
	}
}
 
Example 30
/**
 * Creates a token comparator for the given string.
 *
 * @param text the text to be tokenized
 */
public JavaTokenComparator(String text) {
	Assert.isLegal(text != null);

	fText= text;

	int length= fText.length();
	fStarts= new int[length];
	fLengths= new int[length];
	fCount= 0;

	IScanner scanner= ToolFactory.createScanner(true, true, false, false); // returns comments & whitespace
	scanner.setSource(fText.toCharArray());
	int endPos= 0;
	try {
		int tokenType;
		while ((tokenType= scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) {
			int start= scanner.getCurrentTokenStartPosition();
			int end= scanner.getCurrentTokenEndPosition()+1;
			// Comments and strings should not be treated as a single token, see https://bugs.eclipse.org/78063
			if (TokenScanner.isComment(tokenType) || tokenType == ITerminalSymbols.TokenNameStringLiteral) {
				// Line comments are often commented code, so lets treat them as code. See https://bugs.eclipse.org/216707
				boolean parseAsJava= tokenType == ITerminalSymbols.TokenNameCOMMENT_LINE;
				int dl= parseAsJava ? getCommentStartTokenLength(tokenType) : 0;
				if (dl > 0)
					recordTokenRange(start, dl);
				parseSubrange(start + dl, text.substring(start + dl, end), parseAsJava);
			} else {
				recordTokenRange(start, end - start);
			}
			endPos= end;
		}
	} catch (InvalidInputException ex) {
		// We couldn't parse part of the input. Fall through and make the rest a single token
	}
	// Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=13907
	if (endPos < length) {
		recordTokenRange(endPos, length - endPos);
	}
}