下面列出了怎么用com.intellij.psi.PsiLiteralExpression的API类实例代码及写法,或者点击链接到github查看源代码。
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
try {
PsiAnnotation psiAnnotation = this.getPsiAnnotation(psiElement);
if (psiAnnotation != null) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) psiAnnotation.findAttributeValue("value");
String value = String.valueOf(literalExpression.getValue());
if (value.startsWith(JSON_PREFIX)) {
return new LineMarkerInfo<>(psiAnnotation, psiAnnotation.getTextRange(), NutzCons.NUTZ,
new FunctionTooltip("快速配置"),
new OkJsonUpdateNavigationHandler(value),
GutterIconRenderer.Alignment.LEFT);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private List<PsiElement> findEndpoints(Module module, Predicate<String> uriCondition, Predicate<PsiLiteral> elementCondition) {
PsiManager manager = PsiManager.getInstance(module.getProject());
//TODO: use IdeaUtils.ROUTE_BUILDER_OR_EXPRESSION_CLASS_QUALIFIED_NAME somehow
PsiClass routeBuilderClass = ClassUtil.findPsiClass(manager, "org.apache.camel.builder.RouteBuilder");
List<PsiElement> results = new ArrayList<>();
if (routeBuilderClass != null) {
Collection<PsiClass> routeBuilders = ClassInheritorsSearch.search(routeBuilderClass, module.getModuleScope(), true)
.findAll();
for (PsiClass routeBuilder : routeBuilders) {
Collection<PsiLiteralExpression> literals = PsiTreeUtil.findChildrenOfType(routeBuilder, PsiLiteralExpression.class);
for (PsiLiteralExpression literal : literals) {
Object val = literal.getValue();
if (val instanceof String) {
String endpointUri = (String) val;
if (uriCondition.test(endpointUri) && elementCondition.test(literal)) {
results.add(literal);
}
}
}
}
}
return results;
}
@Override
public Optional<String> extractTextFromElement(PsiElement element, boolean concatString, boolean stripWhitespace) {
if (element instanceof PsiLiteralExpression) {
// need the entire line so find the literal expression that would hold the entire string (java)
PsiLiteralExpression literal = (PsiLiteralExpression) element;
Object o = literal.getValue();
String text = o != null ? o.toString() : null;
if (text == null) {
return Optional.empty();
}
if (concatString) {
final PsiPolyadicExpression parentOfType = PsiTreeUtil.getParentOfType(element, PsiPolyadicExpression.class);
if (parentOfType != null) {
text = parentOfType.getText();
}
}
// unwrap literal string which can happen in java too
if (stripWhitespace) {
return Optional.ofNullable(getInnerText(text));
}
return Optional.of(StringUtil.unquoteString(text.replace(QUOT, "\"")));
}
return Optional.empty();
}
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
PsiJavaElementPattern.Capture<PsiLiteralExpression> pattern = PsiJavaPatterns
.literalExpression()
.insideAnnotationParam(CamelIdeaUtils.BEAN_INJECT_ANNOTATION);
registrar.registerReferenceProvider(pattern, new CamelPsiReferenceProvider() {
@Override
protected PsiReference[] getCamelReferencesByElement(PsiElement element, ProcessingContext context) {
PsiNameValuePair param = PsiTreeUtil.getParentOfType(element, PsiNameValuePair.class);
if (param != null && param.getAttributeName().equals("value")) {
String value = param.getLiteralValue();
if (value != null) {
return new PsiReference[] {new BeanReference(element, value)};
}
}
return new PsiReference[0];
}
});
}
public void testGenerateDoc() throws Exception {
myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestDataWithCursorAfterQuestionMark());
PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
String componentName = "file";
String lookup = componentName + ":inbox?delete";
PsiManager manager = myFixture.getPsiManager();
PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);
String doc = new CamelDocumentationProvider().generateDoc(docInfo, null);
assertEquals(readExpectedFile(), doc);
String documentation = new CamelDocumentationProvider().generateDoc(element, null);
assertNotNull(documentation);
assertTrue(documentation.startsWith("<b>File Component</b><br/>The file component is used for reading or writing files.<br/>"));
}
public static void translate(PsiLiteralExpression element, TranslationContext ctx) {
String value = element.getText().trim();
if (value.toLowerCase().equals("null")) {
ctx.append(value);
return;
}
if (value.toLowerCase().endsWith("l")) {
ctx.append(value.substring(0, value.length() - 1));
return;
}
if (value.toLowerCase().endsWith("f") || value.toLowerCase().endsWith("d")) {
if (value.contains("0x")) {
ctx.append(value);
} else {
ctx.append(value.substring(0, value.length() - 1));
}
return;
}
ctx.append(value);
}
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean b) {
Project project = root.getProject();
List<FoldingDescriptor> descriptors = new ArrayList<>();
Collection<VirtualFile> propertiesFiles = FilenameIndex.getAllFilesByExt(project, "properties", GlobalSearchScope.projectScope(project));
Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
for (final PsiLiteralExpression literalExpression : literalExpressions) {
if (!NutzInjectConfUtil.isInjectConf(literalExpression)) {
continue;
}
String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
String key = NutzInjectConfUtil.getKey(value);
if (key != null) {
final List<String> properties = NutzInjectConfUtil.findProperties(project, propertiesFiles, key);
final TextRange textRange = new TextRange(literalExpression.getTextRange().getStartOffset() + 1, literalExpression.getTextRange().getEndOffset() - 1);
String data;
if (properties.size() == 1) {
data = properties.get(0);
} else if (properties.size() > 1) {
data = properties.get(0) + "[该键值存在多个配置文件中!]";
} else {
data = "[" + key + "]不存在,使用时可能产生异常,请检查!";
}
descriptors.add(new NutzLocalizationFoldingDescriptor(literalExpression.getNode(), textRange, data));
}
}
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
Project project = root.getProject();
String localizationPackage = NutzLocalUtil.getLocalizationPackage(project);
if (null == localizationPackage) {
return FoldingDescriptor.EMPTY;
}
List<FoldingDescriptor> descriptors = new ArrayList<>();
Collection<VirtualFile> propertiesFiles = FilenameIndex.getAllFilesByExt(project, "properties", GlobalSearchScope.projectScope(project));
Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
for (final PsiLiteralExpression literalExpression : literalExpressions) {
if (!NutzLocalUtil.isLocal(literalExpression)) {
continue;
}
String key = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
if (key != null) {
final List<String> properties = NutzLocalUtil.findProperties(project, propertiesFiles, localizationPackage, key);
TextRange textRange = new TextRange(literalExpression.getTextRange().getStartOffset() + 1, literalExpression.getTextRange().getEndOffset() - 1);
String value;
if (properties.size() == 1) {
value = properties.get(0);
} else if (properties.size() > 1) {
value = properties.get(0) + "[该键值存在多个配置文件中!]";
} else {
value = "国际化信息中不存在[" + key + "],使用时可能产生异常,请检查!";
}
descriptors.add(new NutzLocalizationFoldingDescriptor(literalExpression.getNode(), textRange, value));
}
}
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
if (ServiceManager.getService(element.getProject(), CamelService.class).isCamelPresent()) {
PsiExpressionList exps = PsiTreeUtil.getNextSiblingOfType(originalElement, PsiExpressionList.class);
if (exps != null) {
if (exps.getExpressions().length >= 1) {
// grab first string parameter (as the string would contain the camel endpoint uri
final PsiClassType stringType = PsiType.getJavaLangString(element.getManager(), element.getResolveScope());
PsiExpression exp = Arrays.stream(exps.getExpressions()).filter(
e -> e.getType() != null && stringType.isAssignableFrom(e.getType()))
.findFirst().orElse(null);
if (exp instanceof PsiLiteralExpression) {
Object o = ((PsiLiteralExpression) exp).getValue();
String val = o != null ? o.toString() : null;
// okay only allow this popup to work when its from a RouteBuilder class
PsiClass clazz = PsiTreeUtil.getParentOfType(originalElement, PsiClass.class);
if (clazz != null) {
PsiClassType[] types = clazz.getExtendsListTypes();
boolean found = Arrays.stream(types).anyMatch(p -> p.getClassName().equals("RouteBuilder"));
if (found) {
String componentName = asComponentName(val);
if (componentName != null) {
// the quick info cannot be so wide so wrap at 120 chars
return generateCamelComponentDocumentation(componentName, val, 120, element.getProject());
}
}
}
}
}
}
}
return null;
}
@Override
public PsiElement getPsiElementForCamelBeanMethod(PsiElement element) {
if (element instanceof PsiLiteral || element.getParent() instanceof PsiLiteralExpression) {
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(element, PsiExpressionList.class);
if (expressionList != null) {
final PsiIdentifier identifier = PsiTreeUtil.getChildOfType(expressionList.getPrevSibling(), PsiIdentifier.class);
if (identifier != null && identifier.getNextSibling() == null && ("method" .equals(identifier.getText()) || "bean" .equals(identifier.getText()))) {
return expressionList;
}
}
}
return null;
}
private String getStaticBeanName(PsiJavaCodeReferenceElement referenceElement, String beanName) {
final PsiType type = ((PsiReferenceExpression) referenceElement).getType();
if (type != null && JAVA_LANG_STRING.equals(type.getCanonicalText())) {
beanName = StringUtils.stripDoubleQuotes(PsiTreeUtil.getChildOfAnyType(referenceElement.getReference().resolve(), PsiLiteralExpression.class).getText());
}
return beanName;
}
/**
* Searching for the specific bean name and annotation to find it's {@link PsiClass}
* @param beanName - Name of the bean to search for.
* @param annotation - Type of bean annotation to filter on.
* @param project - Project reference to narrow the search inside.
* @return the {@link PsiClass} matching the bean name and annotation.
*/
public Optional<PsiClass> findBeanClassByName(String beanName, String annotation, Project project) {
for (PsiClass psiClass : getClassesAnnotatedWith(project, annotation)) {
final PsiAnnotation classAnnotation = psiClass.getAnnotation(annotation);
PsiAnnotationMemberValue attribute = classAnnotation.findAttributeValue("value");
if (attribute != null) {
if (attribute instanceof PsiReferenceExpressionImpl) {
//if the attribute value is field reference eg @bean(value = MyClass.BEAN_NAME)
final PsiField psiField = (PsiField) attribute.getReference().resolve();
String staticBeanName = StringUtils.stripDoubleQuotes(PsiTreeUtil.getChildOfAnyType(psiField, PsiLiteralExpression.class).getText());
if (beanName.equals(staticBeanName)) {
return Optional.of(psiClass);
}
} else {
final String value = attribute.getText();
if (beanName.equals(StringUtils.stripDoubleQuotes(value))) {
return Optional.of(psiClass);
}
}
} else {
if (Introspector.decapitalize(psiClass.getName()).equalsIgnoreCase(StringUtils.stripDoubleQuotes(beanName))) {
return Optional.of(psiClass);
}
}
}
return Optional.empty();
}
/**
* Returns the first operand from a {@link PsiPolyadicExpression}
*
* @param psiLiteralExpression the {@link PsiLiteralExpression} that is part of a {@link PsiPolyadicExpression}
* @return the first {@link PsiExpression} if the given {@link PsiLiteralExpression} is part of a {@link PsiPolyadicExpression}, null otherwise
*/
@Nullable
private static PsiExpression getFirstExpressionFromPolyadicExpression(PsiLiteralExpression psiLiteralExpression) {
if (isPartOfPolyadicExpression(psiLiteralExpression)) {
PsiPolyadicExpression psiPolyadicExpression = PsiTreeUtil.getParentOfType(psiLiteralExpression, PsiPolyadicExpression.class);
if (psiPolyadicExpression != null) {
return psiPolyadicExpression.getOperands()[0];
}
}
return null;
}
@Override
public String getElementText(PsiElement element) {
if (element instanceof PsiLiteralExpression) {
return ((PsiLiteralExpression) element).getValue().toString();
}
return element.getText();
}
@Override
public boolean isAvailableOnDataContext(DataContext dataContext) {
final PsiElement psiElement = findPsiElementAt(dataContext);
if (psiElement == null) {
return false;
}
//Make sure the cursor is located in the text where the method name is defined.
return psiElement.getParent() instanceof PsiLiteralExpression
&& psiElement.getNextSibling() == null
&& getCamelIdeaUtils().getBean(psiElement) != null;
}
public void testSmartCompletionDocumentation() throws Exception {
myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestData());
PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
String componentName = "file";
String lookup = componentName + ":inbox?delete";
PsiManager manager = myFixture.getPsiManager();
PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);
CamelDocumentationProvider.DocumentationElement de = (CamelDocumentationProvider.DocumentationElement) docInfo;
assertEquals(componentName, de.getComponentName());
assertEquals("delete", de.getText());
assertEquals("delete", de.getEndpointOption());
}
public void testSmartCompletionDocumentation() throws Exception {
myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestData());
PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
String componentName = "file";
String lookup = componentName + ":inbox?scheduler.";
PsiManager manager = myFixture.getPsiManager();
PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);
CamelDocumentationProvider.DocumentationElement de = (CamelDocumentationProvider.DocumentationElement) docInfo;
assertEquals(componentName, de.getComponentName());
assertEquals("schedulerProperties", de.getText());
assertEquals("schedulerProperties", de.getEndpointOption());
}
public void testHandleExternalLink() {
myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestDataWithCursorBeforeColon());
PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
CamelDocumentationProvider provider = new CamelDocumentationProvider();
boolean externalLink = provider.handleExternalLink(null, "http://bennet-schulz.com", element);
assertFalse(externalLink);
}
public void testStartRoute() {
// caret is at start of rout in the test java file
myFixture.configureByText("DummyTestData.java", CODE);
// this does not work with <caret> in the source code
// PsiElement element = myFixture.getElementAtCaret();
PsiElement element = myFixture.findElementByText("\"file:inbox\"", PsiLiteralExpression.class);
assertTrue(getCamelIdeaUtils().isCamelRouteStart(element));
}
public void testNotStartRoute() {
// caret is at start of rout in the test java file
myFixture.configureByText("DummyTestData.java", CODE);
// this does not work with <caret> in the source code
// PsiElement element = myFixture.getElementAtCaret();
PsiElement element = myFixture.findElementByText("\"log:out\"", PsiLiteralExpression.class);
assertFalse(getCamelIdeaUtils().isCamelRouteStart(element));
}
public void testStartRoute() {
// caret is at start of rout in the test java file
myFixture.configureByText("DummyTestData.java", CODE);
// this does not work with <caret> in the source code
// PsiElement element = myFixture.getElementAtCaret();
PsiElement element = myFixture.findElementByText("\"file:inbox\"", PsiLiteralExpression.class);
assertTrue(getCamelIdeaUtils().isCamelRouteStart(element));
}
public void testNotStartRoute() {
// caret is at start of rout in the test java file
myFixture.configureByText("DummyTestData.java", CODE);
// this does not work with <caret> in the source code
// PsiElement element = myFixture.getElementAtCaret();
PsiElement element = myFixture.findElementByText("\"log:out\"", PsiLiteralExpression.class);
assertFalse(getCamelIdeaUtils().isCamelRouteStart(element));
}
public void testShouldSkipActiveMQConnectionFactoryConstructor() {
myFixture.configureByText("DummyTestData.java", CODE);
PsiElement element = myFixture.findElementByText("\"vm://broker\"", PsiLiteralExpression.class);
assertTrue("ActiveMQConnectionFactory constructor should be skipped", getCamelIdeaUtils().skipEndpointValidation(element));
element = myFixture.findElementByText("\"vm://spring\"", PsiLiteralExpression.class);
assertTrue("spring ActiveMQConnectionFactory constructor should be skipped", getCamelIdeaUtils().skipEndpointValidation(element));
}
public void testShouldSkipActiveMQXAConnectionFactoryConstructor() {
myFixture.configureByText("DummyTestData.java", CODE);
PsiElement element = myFixture.findElementByText("\"vm://broker-xa\"", PsiLiteralExpression.class);
assertTrue("ActiveMQXAConnectionFactory constructor should be skipped", getCamelIdeaUtils().skipEndpointValidation(element));
element = myFixture.findElementByText("\"vm://spring-xa\"", PsiLiteralExpression.class);
assertTrue("spring ActiveMQXAConnectionFactory constructor should be skipped", getCamelIdeaUtils().skipEndpointValidation(element));
}
public void testFindUsageFromMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaBeanTestData.java", "CompleteJavaBeanRoute1TestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(beanTestData, \"anotherBeanMethod\")", referenceElement.getParent().getText());
}
/**
* Test if it can find usage from a Spring Service bean method to it's Camel routes bean method
*/
public void testFindUsageFromSpringServiceMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaSpringServiceBeanTestData.java", "CompleteJavaSpringServiceBeanRouteTestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(\"myServiceBean\", \"anotherBeanMethod\")", referenceElement.getParent().getText());
}
/**
* Test if it can find usage from a Spring Component bean method to it's Camel routes bean method
*/
public void testFindUsageFromSpringComponentMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaSpringComponentBeanTestData.java", "CompleteJavaSpringComponentBeanRouteTestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(\"myComponentBean\", \"anotherBeanMethod\")", referenceElement.getParent().getText());
}
/**
* Test if it can find usage from a Spring Repository bean method to it's Camel routes bean method
*/
public void testFindUsageFromSpringRepositoryMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaSpringRepositoryBeanTestData.java", "CompleteJavaSpringRepositoryBeanRouteTestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(\"myRepositoryBean\", \"anotherBeanMethod\")", referenceElement.getParent().getText());
}
public void testFindUsageFromWithOverloadedMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaBeanTest2Data.java", "CompleteJavaBeanRoute7TestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(beanTestData, \"myOverLoadedBean\")", referenceElement.getParent().getText());
}
/**
* Test if the find usage is working with camel DSL bean method call with parameters
*/
public void testFindUsageFromWithAmbiguousToBeanDSLWithParameters() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaBeanTest3Data.java", "CompleteJavaBeanRoute8TestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(beanTestData, \"myAmbiguousMethod(${body})\")", referenceElement.getParent().getText());
}