com.intellij.psi.PsiElementFactory Java Examples
The following examples show how to use
com.intellij.psi.PsiElementFactory.
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: FieldsDialog.java From GsonFormat with Apache License 2.0 | 6 votes |
public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity, PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project , String generateClassStr) { this.operator = operator; this.factory = factory; this.aClass = aClass; this.file = file; this.project = project; this.psiClass = psiClass; this.generateClassStr = generateClassStr; setContentPane(contentPane); setTitle("Virgo Model"); getRootPane().setDefaultButton(buttonOK); this.setAlwaysOnTop(true); initListener(classEntity, generateClassStr); }
Example #2
Source File: CodeGenerator.java From ParcelablePlease with Apache License 2.0 | 6 votes |
/** * Make the class implementing Parcelable */ private void makeClassImplementParcelable(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) { final PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes(); final String implementsType = "android.os.Parcelable"; for (PsiClassType implementsListType : implementsListTypes) { PsiClass resolved = implementsListType.resolve(); // Already implements Parcelable, no need to add it if (resolved != null && implementsType.equals(resolved.getQualifiedName())) { return; } } PsiJavaCodeReferenceElement implementsReference = elementFactory.createReferenceFromText(implementsType, psiClass); PsiReferenceList implementsList = psiClass.getImplementsList(); if (implementsList != null) { styleManager.shortenClassReferences(implementsList.add(implementsReference)); } }
Example #3
Source File: Processor.java From GsonFormat with Apache License 2.0 | 6 votes |
protected void generateConvertMethod(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { if (cls == null || cls.getName() == null) { return; } if (Config.getInstant().isObjectFromData()) { createMethod(factory, Config.getInstant().getObjectFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls); } if (Config.getInstant().isObjectFromData1()) { createMethod(factory, Config.getInstant().getObjectFromDataStr1().replace("$ClassName$", cls.getName()).trim(), cls); } if (Config.getInstant().isArrayFromData()) { createMethod(factory, Config.getInstant().getArrayFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls); } if (Config.getInstant().isArrayFromData1()) { createMethod(factory, Config.getInstant().getArrayFromData1Str().replace("$ClassName$", cls.getName()).trim(), cls); } }
Example #4
Source File: DocGenerateAction.java From CodeMaker with Apache License 2.0 | 6 votes |
/** * @see com.intellij.openapi.actionSystem.AnAction#actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent) */ @Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) { return; } DumbService dumbService = DumbService.getInstance(project); if (dumbService.isDumb()) { dumbService.showDumbModeNotification("CodeMaker plugin is not available during indexing"); return; } PsiFile javaFile = e.getData(CommonDataKeys.PSI_FILE); Editor editor = e.getData(CommonDataKeys.EDITOR); if (javaFile == null || editor == null) { return; } List<PsiClass> classes = CodeMakerUtil.getClasses(javaFile); PsiElementFactory psiElementFactory = PsiElementFactory.SERVICE.getInstance(project); for (PsiClass psiClass : classes) { for (PsiMethod psiMethod : PsiTreeUtil.getChildrenOfTypeAsList(psiClass, PsiMethod.class)) { createDocForMethod(psiMethod, psiElementFactory); } } }
Example #5
Source File: AddArgumentFixTest.java From litho with Apache License 2.0 | 6 votes |
@Test public void createAddMethodCallFix() { testHelper.getPsiClass( classes -> { // Setup test environment PsiClass cls = classes.get(0); PsiMethodCallExpression call = PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class); Project project = testHelper.getFixture().getProject(); PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); Editor editor = mock(Editor.class); when(editor.getCaretModel()).thenReturn(mock(CaretModel.class)); IntentionAction fix = AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory); assertThat(call.getArgumentList().getExpressions()[0].getText()) .isNotEqualTo("ClassName.methodName()"); fix.invoke(project, editor, testHelper.getFixture().getFile()); assertThat(call.getArgumentList().getExpressions()[0].getText()) .isEqualTo("ClassName.methodName()"); return true; }, "RequiredPropAnnotatorTest.java"); }
Example #6
Source File: Processor.java From GsonFormat with Apache License 2.0 | 6 votes |
protected void createMethod(PsiElementFactory factory, String method, PsiClass cls) { Try.run(new Try.TryListener() { @Override public void run() { cls.add(factory.createMethodFromText(method, cls)); } @Override public void runAgain() { } @Override public void error() { } }); }
Example #7
Source File: CodeGenerator.java From ParcelablePlease with Apache License 2.0 | 6 votes |
private void addImport(PsiElementFactory elementFactory, String fullyQualifiedName){ final PsiFile file = psiClass.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } final PsiJavaFile javaFile = (PsiJavaFile)file; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return; } // Check if already imported for (PsiImportStatementBase is : importList.getAllImportStatements()) { String impQualifiedName = is.getImportReference().getQualifiedName(); if (fullyQualifiedName.equals(impQualifiedName)){ return; // Already imported so nothing neede } } // Not imported yet so add it importList.add(elementFactory.createImportStatementOnDemand(fullyQualifiedName)); }
Example #8
Source File: Processor.java From GsonFormat with Apache License 2.0 | 6 votes |
protected void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) { if (fieldEntity.isGenerate()) { Try.run(new Try.TryListener() { @Override public void run() { cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, null), cls)); } @Override public void runAgain() { fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName())); cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, Constant.FIXME), cls)); } @Override public void error() { cls.addBefore(factory.createCommentFromText("// FIXME generate failure field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]); } }); } }
Example #9
Source File: OnEventGenerateUtils.java From litho with Apache License 2.0 | 6 votes |
/** * Adds comment to the given method "// An event handler ContextClassName.methodName(c, * parameterName) */ public static void addComment(PsiClass contextClass, PsiMethod method) { final Project project = contextClass.getProject(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final StringBuilder builder = new StringBuilder("// An event handler ") .append(LithoPluginUtils.getLithoComponentNameFromSpec(contextClass.getName())) .append(".") .append(method.getName()) .append("(") .append(CONTEXT_PARAMETER_NAME); for (PsiParameter parameter : method.getParameterList().getParameters()) { if (LithoPluginUtils.isParam(parameter)) { builder.append(", ").append(parameter.getName()); } } builder.append(")"); final PsiComment comment = factory.createCommentFromText(builder.toString(), method); method.addBefore(comment, method.getModifierList()); }
Example #10
Source File: MethodChainLookupElement.java From litho with Apache License 2.0 | 6 votes |
@VisibleForTesting static PsiExpression createMethodChain( Project project, String firstName, List<? extends String> methodNames) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); StringBuilder expressionText = new StringBuilder(firstName + "(" + TEMPLATE_INSERT_PLACEHOLDER_C + ")"); methodNames.forEach( methodName -> expressionText .append("\n.") .append(methodName) .append("(") .append(TEMPLATE_INSERT_PLACEHOLDER) .append(")")); return factory.createExpressionFromText(expressionText.toString(), null); }
Example #11
Source File: HaxeInheritPsiMixinImpl.java From intellij-haxe with Apache License 2.0 | 5 votes |
@NotNull @Override public PsiClassType[] getReferencedTypes() { LOG.debug("getReferencedTypes"); PsiJavaCodeReferenceElement[] refs = getReferenceElements(); PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); PsiClassType[] types = new PsiClassType[refs.length]; for (int i = 0; i < types.length; i++) { types[i] = factory.createType(refs[i]); } return types; }
Example #12
Source File: Processor.java From GsonFormat with Apache License 2.0 | 5 votes |
protected void generateGetterAndSetter(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) { if (Config.getInstant().isFieldPrivateMode()) { for (FieldEntity field : classEntity.getFields()) { createGetAndSetMethod(factory, cls, field); } } }
Example #13
Source File: CodeGenerator.java From ParcelablePlease with Apache License 2.0 | 5 votes |
/** * Generate and insert the Parcel and ParcelablePlease code */ public void generate() { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject()); JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(psiClass.getProject()); // Clear any previous clearPrevious(); // Implements parcelable makeClassImplementParcelable(elementFactory, styleManager); // @ParcelablePlease Annotation addAnnotation(elementFactory, styleManager); // Creator PsiField creatorField = elementFactory.createFieldFromText(generateCreator(), psiClass); // Describe contents method PsiMethod describeContentsMethod = elementFactory.createMethodFromText(generateDescribeContents(), psiClass); // Method for writing to the parcel PsiMethod writeToParcelMethod = elementFactory.createMethodFromText(generateWriteToParcel(), psiClass); styleManager.shortenClassReferences( psiClass.addBefore(describeContentsMethod, psiClass.getLastChild())); styleManager.shortenClassReferences( psiClass.addBefore(writeToParcelMethod, psiClass.getLastChild())); styleManager.shortenClassReferences(psiClass.addBefore(creatorField, psiClass.getLastChild())); }
Example #14
Source File: CodeGenerator.java From ParcelablePlease with Apache License 2.0 | 5 votes |
/** * Add the @Parcelable annotation if not already annotated */ private void addAnnotation(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) { boolean annotated = AnnotationUtil.isAnnotated(psiClass, ANNOTATION_PACKAGE+"."+ANNOTATION_NAME, false); if (!annotated) { styleManager.shortenClassReferences(psiClass.getModifierList().addAnnotation( ANNOTATION_NAME)); } }
Example #15
Source File: Processor.java From GsonFormat with Apache License 2.0 | 5 votes |
public void process(ClassEntity classEntity, PsiElementFactory factory, PsiClass cls, IProcessor visitor) { mainPackage = PsiClassUtil.getPackage(cls); onStarProcess(classEntity, factory, cls, visitor); for (FieldEntity fieldEntity : classEntity.getFields()) { generateField(factory, fieldEntity, cls, classEntity); } for (ClassEntity innerClass : classEntity.getInnerClasss()) { generateClass(factory, innerClass, cls, visitor); } generateGetterAndSetter(factory, cls, classEntity); generateConvertMethod(factory, cls, classEntity); onEndProcess(classEntity, factory, cls, visitor); }
Example #16
Source File: PsiQuickFixFactory.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static LocalQuickFix createAddAnnotationQuickFix(@NotNull PsiClass psiClass, @NotNull String annotationFQN, @Nullable String annotationParam) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject()); PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText("@" + annotationFQN + "(" + StringUtil.notNullize(annotationParam) + ")", psiClass); final PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes(); return new AddAnnotationFix(annotationFQN, psiClass, attributes); }
Example #17
Source File: LombokLightModifierList.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override @NotNull public PsiAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(getProject()); final PsiAnnotation psiAnnotation = elementFactory.createAnnotationFromText('@' + qualifiedName, null); myAnnotations.put(qualifiedName, psiAnnotation); return psiAnnotation; }
Example #18
Source File: LombokToStringHandler.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void processClass(@NotNull PsiClass psiClass) { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject()); final PsiClassType stringClassType = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_STRING, psiClass.getResolveScope()); final PsiMethod toStringMethod = findPublicNonStaticMethod(psiClass, "toString", stringClassType); if (null != toStringMethod) { toStringMethod.delete(); } addAnnotation(psiClass, ToString.class); }
Example #19
Source File: BeanUtils.java From camel-idea-plugin with Apache License 2.0 | 5 votes |
public List<ReferenceableBeanId> findReferenceableBeanIdsByType(Module module, Predicate<String> idCondition, PsiType expectedBeanType) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(module.getProject()); return findReferenceableBeanIds(module, idCondition).stream() .filter(ref -> { PsiClass psiClass = resolveToPsiClass(ref); if (psiClass != null) { PsiClassType beanType = elementFactory.createType(psiClass); return expectedBeanType.isAssignableFrom(beanType); } return false; }) .collect(Collectors.toList()); }
Example #20
Source File: ChangeAnnotationParameterQuickFix.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { final PsiAnnotation myAnnotation = (PsiAnnotation) startElement; final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myAnnotation); if (editor != null) { WriteCommandAction.writeCommandAction(project, psiFile).run(() -> { final PsiNameValuePair valuePair = selectAnnotationAttribute(myAnnotation); if (null != valuePair) { // delete this parameter valuePair.delete(); } if (null != myNewValue) { //add new parameter final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myAnnotation.getProject()); PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText("@" + myAnnotation.getQualifiedName() + "(" + myName + "=" + myNewValue + ")", myAnnotation.getContext()); final PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes(); myAnnotation.setDeclaredAttributeValue(attributes[0].getName(), attributes[0].getValue()); } UndoUtil.markPsiFileForUndo(psiFile); } ); } }
Example #21
Source File: CreateFieldQuickFix.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { final PsiClass myClass = (PsiClass) startElement; final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myClass.getLBrace()); if (editor != null) { WriteCommandAction.writeCommandAction(project, psiFile).run(() -> { final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project); final PsiField psiField = psiElementFactory.createField(myName, myType); final PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { for (String modifier : myModifiers) { modifierList.setModifierProperty(modifier, true); } } if (null != myInitializerText) { PsiExpression psiInitializer = psiElementFactory.createExpressionFromText(myInitializerText, psiField); psiField.setInitializer(psiInitializer); } final List<PsiGenerationInfo<PsiField>> generationInfos = GenerateMembersUtil.insertMembersAtOffset(myClass.getContainingFile(), editor.getCaretModel().getOffset(), Collections.singletonList(new PsiGenerationInfo<>(psiField))); if (!generationInfos.isEmpty()) { PsiField psiMember = generationInfos.iterator().next().getPsiMember(); editor.getCaretModel().moveToOffset(psiMember.getTextRange().getEndOffset()); } UndoUtil.markPsiFileForUndo(psiFile); } ); } }
Example #22
Source File: DocGenerateAction.java From CodeMaker with Apache License 2.0 | 5 votes |
/** * Create doc for method. * * @param psiMethod the psi method * @param psiElementFactory the psi element factory */ private void createDocForMethod(PsiMethod psiMethod, PsiElementFactory psiElementFactory) { try { checkFilesAccess(psiMethod); PsiDocComment psiDocComment = psiMethod.getDocComment(); //return if the method has comment if (psiDocComment != null) { return; } String interfaceName = CodeMakerUtil.findClassNameOfSuperMethod(psiMethod); if (interfaceName == null) { return; } String methodName = psiMethod.getName(); Map<String, Object> map = Maps.newHashMap(); map.put("interface", interfaceName); map.put("method", methodName); map.put("paramsType", generateMethodParamsType(psiMethod)); String seeDoc = VelocityUtil.evaluate(seeDocTemplate, map); PsiDocComment seeDocComment = psiElementFactory.createDocCommentFromText(seeDoc); WriteCommandAction writeCommandAction = new DocWriteAction(psiMethod.getProject(), seeDocComment, psiMethod, psiMethod.getContainingFile()); RunResult result = writeCommandAction.execute(); if (result.hasException()) { LOGGER.error(result.getThrowable()); Messages.showErrorDialog("CodeMaker plugin is not available, cause: " + result.getThrowable().getMessage(), "CodeMaker plugin"); } } catch (Exception e) { LOGGER.error("Create @see Doc failed", e); } }
Example #23
Source File: PsiConsultantImpl.java From dagger-intellij-plugin with Apache License 2.0 | 5 votes |
/** * Return the appropriate return class for a given method element. * * @param psiMethod the method to get the return class from. * @param expandType set this to true if return types annotated with @Provides(type=?) * should be expanded to the appropriate collection type. * @return the appropriate return class for the provided method element. */ public static PsiClass getReturnClassFromMethod(PsiMethod psiMethod, boolean expandType) { if (psiMethod.isConstructor()) { return psiMethod.getContainingClass(); } PsiClassType returnType = ((PsiClassType) psiMethod.getReturnType()); if (returnType != null) { // Check if has @Provides annotation and specified type if (expandType) { PsiAnnotationMemberValue attribValue = findTypeAttributeOfProvidesAnnotation(psiMethod); if (attribValue != null) { if (attribValue.textMatches(SET_TYPE)) { String typeName = "java.util.Set<" + returnType.getCanonicalText() + ">"; returnType = ((PsiClassType) PsiElementFactory.SERVICE.getInstance(psiMethod.getProject()) .createTypeFromText(typeName, psiMethod)); } else if (attribValue.textMatches(MAP_TYPE)) { // TODO(radford): Supporting map will require fetching the key type and also validating // the qualifier for the provided key. // // String typeName = "java.util.Map<String, " + returnType.getCanonicalText() + ">"; // returnType = ((PsiClassType) PsiElementFactory.SERVICE.getInstance(psiMethod.getProject()) // .createTypeFromText(typeName, psiMethod)); } } } return returnType.resolve(); } return null; }
Example #24
Source File: GenerateJavadocAction.java From easy_javadoc with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(@NotNull AnActionEvent anActionEvent) { Project project = anActionEvent.getData(LangDataKeys.PROJECT); if (project == null) { return; } // 选中翻译功能 Editor editor = anActionEvent.getData(LangDataKeys.EDITOR); if (editor != null) { String selectedText = editor.getSelectionModel().getSelectedText(true); if (StringUtils.isNotBlank(selectedText)) { // 中译英 if (LanguageUtil.isAllChinese(selectedText)) { writerService.write(project, editor, translatorService.translateCh2En(selectedText)); } // 自动翻译 else { String result = translatorService.autoTranslate(selectedText); new TranslateResultView(result).show(); } return; } } PsiElement psiElement = anActionEvent.getData(LangDataKeys.PSI_ELEMENT); if (psiElement == null || psiElement.getNode() == null) { return; } String comment = docGeneratorService.generate(psiElement); if (StringUtils.isEmpty(comment)) { return; } PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(project); PsiDocComment psiDocComment = factory.createDocCommentFromText(comment); writerService.write(project, psiElement, psiDocComment); }
Example #25
Source File: AddArgumentFix.java From litho with Apache License 2.0 | 5 votes |
static PsiExpressionList createArgumentList( PsiElement context, String clsName, String methodName, PsiElementFactory elementFactory) { final PsiMethodCallExpression stub = (PsiMethodCallExpression) elementFactory.createExpressionFromText( "methodName(" + clsName + "." + methodName + "())", context); return stub.getArgumentList(); }
Example #26
Source File: AddArgumentFix.java From litho with Apache License 2.0 | 5 votes |
/** Creates new fix, that adds static method call as an argument to the originalMethodCall. */ static IntentionAction createAddMethodCallFix( PsiMethodCallExpression originalMethodCall, String clsName, String methodName, PsiElementFactory elementFactory) { PsiExpressionList newArgumentList = createArgumentList(originalMethodCall.getContext(), clsName, methodName, elementFactory); String fixDescription = "Add ." + methodName + "() " + getCapitalizedMethoName(originalMethodCall); return new AddArgumentFix(originalMethodCall, newArgumentList, fixDescription); }
Example #27
Source File: TemplateService.java From litho with Apache License 2.0 | 5 votes |
private PsiMethod readMethodTemplate(String targetName, Project project) { // TemplateSettings#loadDefaultLiveTemplates PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); return Optional.ofNullable( DecodeDefaultsUtil.getDefaultsInputStream(this, "methodTemplates/methods")) .map(TemplateService::load) .filter(element -> TAG_ROOT.equals(element.getName())) .map(element -> element.getChild(targetName)) .map(template -> template.getAttributeValue("method")) .map(method -> factory.createMethodFromText(method, null)) .orElse(null); }
Example #28
Source File: GenerateAllJavadocAction.java From easy_javadoc with Apache License 2.0 | 5 votes |
/** * 保存Javadoc * * @param project 工程 * @param psiElement 当前元素 */ private void saveJavadoc(Project project, PsiElement psiElement) { if (psiElement == null) { return; } String comment = docGeneratorService.generate(psiElement); if (StringUtils.isBlank(comment)) { return; } PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(project); PsiDocComment psiDocComment = factory.createDocCommentFromText(comment); writerService.write(project, psiElement, psiDocComment); }
Example #29
Source File: PsiMethodUtil.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 4 votes |
@NotNull public static PsiCodeBlock createCodeBlockFromText(@NotNull String blockText, @NotNull PsiElement psiElement) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiElement.getProject()); return elementFactory.createCodeBlockFromText("{" + blockText + "}", psiElement); }
Example #30
Source File: LombokEnumConstantBuilder.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 4 votes |
@NotNull @Override public PsiEnumConstantInitializer getOrCreateInitializingClass() { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(getProject()); return factory.createEnumConstantFromText("foo{}", null).getInitializingClass(); }