Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#getSource()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getSource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FullSourceWorkspaceCompletionTests.java    From dacapobench with Apache License 2.0 6 votes vote down vote up
private void complete(String projectName, String packageName, String unitName, String completeAt, String completeBehind, int[] ignoredKinds, int warmupCount,
    int iterationCount) throws CoreException {

  AbstractJavaModelTests.waitUntilIndexesReady();

  TestCompletionRequestor requestor = new TestCompletionRequestor();
  if (ignoredKinds != null) {
    for (int i = 0; i < ignoredKinds.length; i++) {
      requestor.setIgnored(ignoredKinds[i], true);
    }
  }

  ICompilationUnit unit = getCompilationUnit(projectName, packageName, unitName);

  String str = unit.getSource();
  int completionIndex = str.indexOf(completeAt) + completeBehind.length();

  if (DEBUG)
    System.out.print("Perform code assist inside " + unitName + "...");

  for (int j = 0; j < iterationCount; j++) {
    unit.codeComplete(completionIndex, requestor);
  }
  if (DEBUG)
    System.out.println("done!");
}
 
Example 2
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCompletion_javadoc() throws Exception {
	IJavaProject javaProject = JavaCore.create(project);
	ICompilationUnit unit = (ICompilationUnit) javaProject.findElement(new Path("org/sample/TestJavadoc.java"));
	unit.becomeWorkingCopy(null);
	String joinOnCompletion = System.getProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
	try {
		System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, "true");
		int[] loc = findCompletionLocation(unit, "inner.");
		CompletionParams position = JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]));
		String source = unit.getSource();
		changeDocument(unit, source, 3);
		Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, new NullProgressMonitor());
		changeDocument(unit, source, 4);
		CompletionList list = server.completion(position).join().getRight();
		CompletionItem resolved = server.resolveCompletionItem(list.getItems().get(0)).join();
		assertEquals("Test ", resolved.getDocumentation().getLeft());
	} finally {
		unit.discardWorkingCopy();
		if (joinOnCompletion == null) {
			System.clearProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION);
		} else {
			System.setProperty(JDTLanguageServer.JAVA_LSP_JOIN_ON_COMPLETION, joinOnCompletion);
		}
	}
}
 
Example 3
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Change copyCuToPackage(ICompilationUnit cu, IPackageFragment dest, NewNameProposer nameProposer, INewNameQueries copyQueries) {
	// XXX workaround for bug 31998 we will have to disable renaming of
	// linked packages (and cus)
	IResource res= ReorgUtils.getResource(cu);
	if (res != null && res.isLinked()) {
		if (ResourceUtil.getResource(dest) instanceof IContainer) {
			return copyFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest), nameProposer, copyQueries);
		}
	}

	String newName= nameProposer.createNewName(cu, dest);
	Change simpleCopy= new CopyCompilationUnitChange(cu, dest, copyQueries.createStaticQuery(newName));
	if (newName == null || newName.equals(cu.getElementName())) {
		return simpleCopy;
	}

	try {
		IPath newPath= cu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(cu, newName));
		INewNameQuery nameQuery= copyQueries.createNewCompilationUnitNameQuery(cu, newName);
		return new CreateCopyOfCompilationUnitChange(newPath, cu.getSource(), cu, nameQuery);
	} catch (CoreException e) {
		// Using inferred change
		return simpleCopy;
	}
}
 
Example 4
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Change copyCuToPackage(ICompilationUnit cu, IPackageFragment dest, NewNameProposer nameProposer, INewNameQueries copyQueries) {
	// XXX workaround for bug 31998 we will have to disable renaming of
	// linked packages (and cus)
	IResource res= ReorgUtils.getResource(cu);
	if (res != null && res.isLinked()) {
		if (ResourceUtil.getResource(dest) instanceof IContainer)
			return copyFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest), nameProposer, copyQueries);
	}

	String newName= nameProposer.createNewName(cu, dest);
	Change simpleCopy= new CopyCompilationUnitChange(cu, dest, copyQueries.createStaticQuery(newName));
	if (newName == null || newName.equals(cu.getElementName()))
		return simpleCopy;

	try {
		IPath newPath= cu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(cu, newName));
		INewNameQuery nameQuery= copyQueries.createNewCompilationUnitNameQuery(cu, newName);
		return new CreateCopyOfCompilationUnitChange(newPath, cu.getSource(), cu, nameQuery);
	} catch (CoreException e) {
		// Using inferred change
		return simpleCopy;
	}
}
 
Example 5
Source File: QuickTemplateProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument getDocument(ICompilationUnit cu) throws JavaModelException {
	IFile file= (IFile) cu.getResource();
	IDocument document= JavaUI.getDocumentProvider().getDocument(new FileEditorInput(file));
	if (document == null) {
		return new Document(cu.getSource()); // only used by test cases
	}
	return document;
}
 
Example 6
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the AST node's original source code.
 */
public static String getSource(ASTNode node) {
  ICompilationUnit cu = getCompilationUnit(node);

  try {
    String source = cu.getSource();
    int endPos = node.getStartPosition() + node.getLength();
    return source.substring(node.getStartPosition(), endPos);

  } catch (JavaModelException e) {
    CorePluginLog.logError(e);
    return "";
  }
}
 
Example 7
Source File: ResourceMacro.java    From ContentAssist with MIT License 5 votes vote down vote up
/**
 * Obtains source code after this resource change.
 * @param elem the changed resource
 * @return the contents of the source code, or an empty string if the changed resource is not a file
 */
private String getCode(IJavaElement elem) {
    if (elem instanceof ICompilationUnit) {
        ICompilationUnit cu = (ICompilationUnit)elem;
        
        try {
            return cu.getSource();
        } catch (JavaModelException e) {
        }
    }
    return "";
}
 
Example 8
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String createSourceForNewCu(final ICompilationUnit unit, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(unit);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 2); //$NON-NLS-1$
		final String separator= StubUtility.getLineDelimiterUsed(fType.getJavaProject());
		final String block= getAlignedSourceBlock(unit, fNewSourceOfInputType);
		String fileComment= null;
		if (StubUtility.doAddComments(unit.getJavaProject()))
			fileComment= CodeGeneration.getFileComment(unit, separator);
		String content= CodeGeneration.getCompilationUnitContent(unit, fileComment, null, block, separator);
		if (content == null) {
			final StringBuffer buffer= new StringBuffer();
			if (!fType.getPackageFragment().isDefaultPackage()) {
				buffer.append("package ").append(fType.getPackageFragment().getElementName()).append(';'); //$NON-NLS-1$
			}
			buffer.append(separator).append(separator);
			buffer.append(block);
			content= buffer.toString();
		}
		unit.getBuffer().setContents(content);
		addImportsToTargetUnit(unit, new SubProgressMonitor(monitor, 1));
	} finally {
		monitor.done();
	}
	return unit.getSource();
}
 
Example 9
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getUnformattedSource(IProgressMonitor pm) throws CoreException {
	ICompilationUnit newCu= null;
	try {
		newCu= fAccessorPackage.getCompilationUnit(fAccessorPath.lastSegment()).getWorkingCopy(null);

		String typeComment= null, fileComment= null;
		final IJavaProject project= newCu.getJavaProject();
		final String lineDelim= StubUtility.getLineDelimiterUsed(project);
		if (StubUtility.doAddComments(project)) {
			typeComment= CodeGeneration.getTypeComment(newCu, fAccessorClassName, lineDelim);
			fileComment= CodeGeneration.getFileComment(newCu, lineDelim);
		}
		String classContent= createClass(lineDelim);
		String cuContent= CodeGeneration.getCompilationUnitContent(newCu, fileComment, typeComment, classContent, lineDelim);
		if (cuContent == null) {
			StringBuffer buf= new StringBuffer();
			if (fileComment != null) {
				buf.append(fileComment).append(lineDelim);
			}
			if (!fAccessorPackage.isDefaultPackage()) {
				buf.append("package ").append(fAccessorPackage.getElementName()).append(';'); //$NON-NLS-1$
			}
			buf.append(lineDelim).append(lineDelim);
			if (typeComment != null) {
				buf.append(typeComment).append(lineDelim);
			}
			buf.append(classContent);
			cuContent= buf.toString();
		}

		newCu.getBuffer().setContents(cuContent);
		addImportsToAccessorCu(newCu, pm);
		return newCu.getSource();
	} finally {
		if (newCu != null) {
			newCu.discardWorkingCopy();
		}
	}
}
 
Example 10
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Gets compilation unit's source
 *
 * @param unit
 *            affected compilation unit
 * @param comment
 *            comment to be replaced; set null if comment is not present
 * @return new compilation unit's source
 */
private String getNewUnitSource(final ICompilationUnit unit, final Comment comment) {
	String source = null;
	try {
		source = unit.getSource();
		if (comment != null) {
			final int endOfComment = comment.getLength() + comment.getStartPosition();
			source = source.replace(source.substring(0, endOfComment), getCopyrightText());
		}
	} catch (final JavaModelException e) {
		ConsoleUtils.printError(e.getMessage());
	}
	return source;
}
 
Example 11
Source File: CodeActionUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static Range getRange(ICompilationUnit unit, String search, int length) throws JavaModelException {
	String str = unit.getSource();
	int start = str.lastIndexOf(search);
	return JDTUtils.toRange(unit, start, length);
}
 
Example 12
Source File: SnippetCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static List<CompletionItem> getGenericSnippets(SnippetCompletionContext scc) throws JavaModelException {
	List<CompletionItem> res = new ArrayList<>();
	CompletionContext completionContext = scc.getCompletionContext();
	char[] completionToken = completionContext.getToken();
	if (completionToken == null) {
		return Collections.emptyList();
	}
	int tokenLocation = completionContext.getTokenLocation();
	JavaContextType contextType = (JavaContextType) JavaLanguageServerPlugin.getInstance().getTemplateContextRegistry().getContextType(JavaContextType.ID_STATEMENTS);
	if (contextType == null) {
		return Collections.emptyList();
	}
	ICompilationUnit cu = scc.getCompilationUnit();
	IDocument document = new Document(cu.getSource());
	DocumentTemplateContext javaContext = contextType.createContext(document, completionContext.getOffset(), completionToken.length, cu);
	Template[] templates = null;
	if ((tokenLocation & CompletionContext.TL_STATEMENT_START) != 0) {
		templates = JavaLanguageServerPlugin.getInstance().getTemplateStore().getTemplates(JavaContextType.ID_STATEMENTS);
	} else {
		// We only support statement templates for now.
	}

	if (templates == null || templates.length == 0) {
		return Collections.emptyList();
	}

	for (Template template : templates) {
		if (!javaContext.canEvaluate(template)) {
			continue;
		}
		TemplateBuffer buffer = null;
		try {
			buffer = javaContext.evaluate(template);
		} catch (BadLocationException | TemplateException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
			continue;
		}
		if (buffer == null) {
			continue;
		}
		String content = buffer.getString();
		if (Strings.containsOnlyWhitespaces(content)) {
			continue;
		}
		final CompletionItem item = new CompletionItem();
		item.setLabel(template.getName());
		item.setInsertText(content);
		item.setDetail(template.getDescription());
		setFields(item, cu);
		res.add(item);
	}

	return res;
}
 
Example 13
Source File: AbstractCompilationUnitBasedTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
protected int[] findCompletionLocation(ICompilationUnit unit, String completeBehind) throws JavaModelException {
	String str= unit.getSource();
	int cursorLocation = str.lastIndexOf(completeBehind) + completeBehind.length();
	return JsonRpcHelpers.toLine(unit.getBuffer(), cursorLocation);
}
 
Example 14
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu= (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[0];
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.text.NumberFormat",
			"java.util.Properties",
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 15
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1WithOrder() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java is missing", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[] { "junit", "java.text", "java.io", "java" };
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite",
			"java.text.NumberFormat",
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.util.Properties"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 16
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports1() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack1;\n");
	buf.append("\n");
	buf.append("import static java.lang.System.out;\n");
	buf.append("\n");
	buf.append("public class C {\n");
	buf.append("    public int foo() {\n");
	buf.append("        out.print(File.separator);\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
	String[] order= new String[] { "java", "pack", "#java" };
	IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		buf = new StringBuilder();
		buf.append("package pack1;\n");
		buf.append("\n");
		buf.append("import java.io.File;\n");
		buf.append("\n");
		buf.append("import static java.lang.System.out;\n");
		buf.append("\n");
		buf.append("public class C {\n");
		buf.append("    public int foo() {\n");
		buf.append("        out.print(File.separator);\n");
		buf.append("    }\n");
		buf.append("}\n");
		assertTrue(cu.getSource().equals(buf.toString()));
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 17
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testStaticImports2() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("pack1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package pack1;\n");
	buf.append("\n");
	buf.append("import static java.io.File.*;\n");
	buf.append("\n");
	buf.append("public class C {\n");
	buf.append("    public String foo() {\n");
	buf.append("        return pathSeparator + separator + File.separator;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null);
	String[] order= new String[] { "#java.io.File", "java", "pack" };
	IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {});
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		buf = new StringBuilder();
		buf.append("package pack1;\n");
		buf.append("\n");
		buf.append("import static java.io.File.pathSeparator;\n");
		buf.append("import static java.io.File.separator;\n");
		buf.append("\n");
		buf.append("import java.io.File;\n");
		buf.append("\n");
		buf.append("public class C {\n");
		buf.append("    public String foo() {\n");
		buf.append("        return pathSeparator + separator + File.separator;\n");
		buf.append("    }\n");
		buf.append("}\n");
		assertTrue(cu.getSource().equals(buf.toString()));
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 18
Source File: LocalCorrectionQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testMultiCatchUncaughtExceptions() throws Exception {

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.io.EOFException;\n");
	buf.append("import java.io.FileNotFoundException;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() throws EOFException {}\n");
	buf.append("    public void bar() throws FileNotFoundException {}\n");
	buf.append("    public void test() {\n");
	buf.append("        System.out.println(1);\n");
	buf.append("        foo();\n");
	buf.append("        System.out.println(2);\n");
	buf.append("        bar();\n");
	buf.append("        System.out.println(3);\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("import java.io.EOFException;\n");
	buf.append("import java.io.FileNotFoundException;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() throws EOFException {}\n");
	buf.append("    public void bar() throws FileNotFoundException {}\n");
	buf.append("    public void test() {\n");
	buf.append("        try {\n");
	buf.append("            System.out.println(1);\n");
	buf.append("            foo();\n");
	buf.append("            System.out.println(2);\n");
	buf.append("            bar();\n");
	buf.append("            System.out.println(3);\n");
	buf.append("        } catch (EOFException | FileNotFoundException e) {\n");
	buf.append("            // TODO Auto-generated catch block\n");
	buf.append("            e.printStackTrace();\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	Expected e1 = new Expected("Surround with try/multi-catch", buf.toString());

	String beginningExpr = "System.out.println(1);";
	String endingExpr = "System.out.println(3);";
	String sourceCode = cu.getSource();
	int offset = sourceCode.indexOf(beginningExpr);
	int length = sourceCode.indexOf(endingExpr) - offset + endingExpr.length();
	Range selection = JDTUtils.toRange(cu, offset, length);
	assertCodeActions(cu, selection, e1);
}
 
Example 19
Source File: NLSSearchResultRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Finds the key defined by the given match. The assumption is that the key is the only argument
 * and it is a string literal i.e. quoted ("...") or a string constant i.e. 'static final
 * String' defined in the same class.
 * 
 * @param keyPositionResult reference parameter: will be filled with the position of the found
 *            key
 * @param enclosingElement enclosing java element
 * @return a string denoting the key, {@link #NO_KEY} if no key can be found and
 *         <code>null</code> otherwise
 * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code>
 */
private String findKey(Position keyPositionResult, IJavaElement enclosingElement) throws CoreException {
	ICompilationUnit unit= (ICompilationUnit)enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
	if (unit == null)
		return null;

	String source= unit.getSource();
	if (source == null)
		return null;

	IJavaProject javaProject= unit.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(false, false, false, sourceLevel, complianceLevel);
	} else {
		scanner= ToolFactory.createScanner(false, false, false, false);
	}
	scanner.setSource(source.toCharArray());
	scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length());

	try {
		if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT)
			return null;

		if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier)
			return null;

		String src= new String(scanner.getCurrentTokenSource());
		int tokenStart= scanner.getCurrentTokenStartPosition();
		int tokenEnd= scanner.getCurrentTokenEndPosition();

		if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) {
			// Old school
			// next must be key string. Ignore methods which do not take a single String parameter (Bug 295040).
			int nextToken= scanner.getNextToken();
			if (nextToken != ITerminalSymbols.TokenNameStringLiteral && nextToken != ITerminalSymbols.TokenNameIdentifier)
				return null;

			tokenStart= scanner.getCurrentTokenStartPosition();
			tokenEnd= scanner.getCurrentTokenEndPosition();
			int token;
			while ((token= scanner.getNextToken()) == ITerminalSymbols.TokenNameDOT) {
				if ((nextToken= scanner.getNextToken()) != ITerminalSymbols.TokenNameIdentifier) {
						return null;
				}
				tokenStart= scanner.getCurrentTokenStartPosition();
				tokenEnd= scanner.getCurrentTokenEndPosition();
			}
			if (token != ITerminalSymbols.TokenNameRPAREN)
				return null;
			
			if (nextToken == ITerminalSymbols.TokenNameStringLiteral) {
				keyPositionResult.setOffset(tokenStart + 1);
				keyPositionResult.setLength(tokenEnd - tokenStart - 1);
				return source.substring(tokenStart + 1, tokenEnd);
			} else if (nextToken == ITerminalSymbols.TokenNameIdentifier) {
				keyPositionResult.setOffset(tokenStart);
				keyPositionResult.setLength(tokenEnd - tokenStart + 1);
				IType parentClass= (IType)enclosingElement.getAncestor(IJavaElement.TYPE);
				IField[] fields= parentClass.getFields();
				String identifier= source.substring(tokenStart, tokenEnd + 1);
				for (int i= 0; i < fields.length; i++) {
					if (fields[i].getElementName().equals(identifier)) {
						if (!Signature.getSignatureSimpleName(fields[i].getTypeSignature()).equals("String")) //$NON-NLS-1$
							return null;
						Object obj= fields[i].getConstant();
						return obj instanceof String ? ((String)obj).substring(1, ((String)obj).length() - 1) : NO_KEY;
					}
				}
			}
			return NO_KEY;
		} else {
			IJavaElement[] keys= unit.codeSelect(tokenStart, tokenEnd - tokenStart + 1);

			// an interface can't be a key
			if (keys.length == 1 && keys[0].getElementType() == IJavaElement.TYPE && ((IType) keys[0]).isInterface())
				return null;

			keyPositionResult.setOffset(tokenStart);
			keyPositionResult.setLength(tokenEnd - tokenStart + 1);
			return src;
		}
	} catch (InvalidInputException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example 20
Source File: PackageParser.java    From aDoctor with MIT License 3 votes vote down vote up
public static PackageBean parse(IPackageFragment pPackage) throws JavaModelException {
    PackageBean packageBean = new PackageBean();
    CodeParser codeParser = new CodeParser();
    String textualContent = "";

    ArrayList<ClassBean> classes = new ArrayList<>();

    packageBean.setName(pPackage.getElementName());

    for (ICompilationUnit cu : pPackage.getCompilationUnits()) {

        textualContent += cu.getSource();

        CompilationUnit parsed = codeParser.createParser(cu.getSource());
        TypeDeclaration typeDeclaration = (TypeDeclaration) parsed.types().get(0);

        ArrayList<String> imported = new ArrayList<>();

        for (IImportDeclaration importedResource : cu.getImports()) {
            imported.add(importedResource.getElementName());
        }

        classes.add(ClassParser.parse(typeDeclaration, packageBean.getName(), imported));
    }

    packageBean.setTextContent(textualContent);

    return packageBean;
}