com.intellij.psi.codeStyle.JavaCodeStyleManager Java Examples

The following examples show how to use com.intellij.psi.codeStyle.JavaCodeStyleManager. 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: CrudUtils.java    From crud-intellij-plugin with Apache License 2.0 6 votes vote down vote up
public static void doOptimize(Project project) {
    DumbService.getInstance(project).runWhenSmart((DumbAwareRunnable) () -> new WriteCommandAction(project) {
        @Override
        protected void run(@NotNull Result result) {
            for (VirtualFile virtualFile : virtualFiles) {
                try {
                    PsiJavaFile javaFile = (PsiJavaFile) PsiManager.getInstance(project).findFile(virtualFile);
                    if (javaFile != null) {
                        CodeStyleManager.getInstance(project).reformat(javaFile);
                        JavaCodeStyleManager.getInstance(project).optimizeImports(javaFile);
                        JavaCodeStyleManager.getInstance(project).shortenClassReferences(javaFile);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            virtualFiles.clear();
        }
    }.execute());
}
 
Example #2
Source File: JavaBuilder.java    From OkHttpParamsGet with Apache License 2.0 6 votes vote down vote up
@Override
public void build(PsiFile psiFile, Project project1, Editor editor) {
    if (psiFile == null) return;
    WriteCommandAction.runWriteCommandAction(project1, () -> {
        if (editor == null) return;
        Project project = editor.getProject();
        if (project == null) return;
        PsiElement mouse = psiFile.findElementAt(editor.getCaretModel().getOffset());
        PsiClass psiClass = PsiTreeUtil.getParentOfType(mouse, PsiClass.class);
        if (psiClass == null) return;

        if (psiClass.getNameIdentifier() == null) return;
        String className = psiClass.getNameIdentifier().getText();

        PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

        build(editor, mouse, elementFactory, project, psiClass, psiFile, className);

        JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
        styleManager.optimizeImports(psiFile);
        styleManager.shortenClassReferences(psiClass);

    });
}
 
Example #3
Source File: InjectWriter.java    From android-butterknife-zelezny with Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws Throwable {
    final IButterKnife butterKnife = ButterKnifeFactory.findButterKnifeForPsiElement(mProject, mFile);
    if (butterKnife == null) {
        return; // Butterknife library is not available for project
    }

    if (mCreateHolder) {
        generateAdapter(butterKnife);
    } else {
        if (Utils.getInjectCount(mElements) > 0) {
            generateFields(butterKnife);
        }
        generateInjects(butterKnife);
        if (Utils.getClickCount(mElements) > 0) {
            generateClick();
        }
        Utils.showInfoNotification(mProject, String.valueOf(Utils.getInjectCount(mElements)) + " injections and " + String.valueOf(Utils.getClickCount(mElements)) + " onClick added to " + mFile.getName());
    }

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(mFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false).runWithoutProgress();
}
 
Example #4
Source File: UseSlf4jAnnotationQuickFix.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement,
                   @NotNull PsiElement endElement) {
  super.invoke(project, file, startElement, endElement);

  final PsiNamedElement psiNamedElement = elementToRemove.getElement();
  if (null != psiNamedElement) {
    final Collection<PsiReference> all = ReferencesSearch.search(psiNamedElement).findAll();

    final String loggerName = getLoggerName(PsiTreeUtil.getParentOfType(psiNamedElement, PsiClass.class));
    for (PsiReference psiReference : all) {
      psiReference.handleElementRename(loggerName);
    }

    psiNamedElement.delete();

    JavaCodeStyleManager.getInstance(project).removeRedundantImports((PsiJavaFile) file);
  }
}
 
Example #5
Source File: NewClassCommandAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(@NotNull Result<PsiFile> result) throws Throwable {
    final PsiPackage packageElement = directoryService.getPackage(directory);
    if (packageElement == null) {
        throw new InvalidDirectoryException("Target directory does not provide a package");
    }

    final String fileName = Extensions.append(name, StdFileTypes.JAVA);
    final PsiFile found = directory.findFile(fileName);
    if (found != null) {
        throw new ClassAlreadyExistsException("Class '" + name + "'already exists in " + packageElement.getName());
    }

    final String packageName = packageElement.getQualifiedName();
    final String className = Extensions.remove(this.name, StdFileTypes.JAVA);
    try {
        final String java = converter.convert(packageName, className, json);
        final PsiFile classFile = fileFactory.createFileFromText(fileName, JavaFileType.INSTANCE, java);
        CodeStyleManager.getInstance(classFile.getProject()).reformat(classFile);
        JavaCodeStyleManager.getInstance(classFile.getProject()).optimizeImports(classFile);
        final PsiFile created = (PsiFile) directory.add(classFile);
        result.setResult(created);
    } catch (IOException e) {
        throw new ClassCreationException("Failed to create new class from JSON", e);
    }
}
 
Example #6
Source File: BaseLombokHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addAnnotation(@NotNull PsiModifierListOwner targetElement, @NotNull PsiAnnotation newPsiAnnotation,
                           @NotNull Class<? extends Annotation> annotationClass) {
  final PsiAnnotation presentAnnotation = PsiAnnotationSearchUtil.findAnnotation(targetElement, annotationClass);

  final Project project = targetElement.getProject();
  final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
  javaCodeStyleManager.shortenClassReferences(newPsiAnnotation);

  if (null == presentAnnotation) {
    PsiModifierList modifierList = targetElement.getModifierList();
    if (null != modifierList) {
      modifierList.addAfter(newPsiAnnotation, null);
    }
  } else {
    presentAnnotation.setDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME,
      newPsiAnnotation.findDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME));
  }
}
 
Example #7
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: PropertyProcessor.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
private boolean addExtendInterfaces(ClassInfo info, JavaCodeStyleManager styleManager,
                                    PsiElementFactory elementFactory, PsiClass psic) {
    List<String> interfaces = info.getInterfaces();
    if(interfaces != null){
        PsiReferenceList list = psic.getExtendsList();
        if(list == null){
            Util.log(" psic.getExtendsList() == null");
            return false;
        }
        for(String inter : interfaces){
            PsiJavaCodeReferenceElement reference = elementFactory.createReferenceFromText(inter, psic);
            styleManager.shortenClassReferences(reference);
            list.add(reference);
        }
    }
    return true;
}
 
Example #9
Source File: TypeInterfaceExtend__Poolable.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public void makeInterfaceExtend(PsiClass mClass, PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) {
    // get extend interfaces.
    final PsiClassType[] implementsListTypes = mClass.getExtendsListTypes();
    final String implementsType = "com.heaven7.java.data.mediator.DataPools.Poolable";

    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, mClass);
    PsiReferenceList implementsList = mClass.getExtendsList();
    if (implementsList != null) {
        styleManager.shortenClassReferences(implementsReference);
        implementsList.add(implementsReference);
    }
}
 
Example #10
Source File: GodClassPreviewResultDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public GodClassPreviewResultDialog(@NotNull Project project, @NotNull MutableDiffRequestChain requestChain,
                                   @NotNull DiffDialogHints hints, ExtractClassPreviewProcessor previewProcessor) {
    super(project, requestChain, hints);
    this.myChain = requestChain;
    this.project = project;
    this.diffContentFactory = DiffContentFactory.getInstance();
    this.previewProcessor = previewProcessor;
    this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    this.codeStyleManager = CodeStyleManager.getInstance(project);
}
 
Example #11
Source File: CodeGenerator.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public void generate() {
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(mClass.getProject());

    removeExistingParcelableImplementation(mClass);

    // Describe contents method
    PsiMethod describeContentsMethod = elementFactory.createMethodFromText(generateDescribeContents(), mClass);
    // Method for writing to the parcel
    PsiMethod writeToParcelMethod = elementFactory.createMethodFromText(generateWriteToParcel(mFields), mClass);

    // Default constructor if needed
    String defaultConstructorString = generateDefaultConstructor(mClass);
    PsiMethod defaultConstructor = null;

    if (defaultConstructorString != null) {
        defaultConstructor = elementFactory.createMethodFromText(defaultConstructorString, mClass);
    }

    // Constructor
    PsiMethod constructor = elementFactory.createMethodFromText(generateConstructor(mFields, mClass), mClass);
    // CREATOR
    PsiField creatorField = elementFactory.createFieldFromText(generateStaticCreator(mClass), mClass);

    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mClass.getProject());

    // Shorten all class references
    styleManager.shortenClassReferences(mClass.addBefore(describeContentsMethod, mClass.getLastChild()));
    styleManager.shortenClassReferences(mClass.addBefore(writeToParcelMethod, mClass.getLastChild()));

    // Only adds if available
    if (defaultConstructor != null) {
        styleManager.shortenClassReferences(mClass.addBefore(defaultConstructor, mClass.getLastChild()));
    }

    styleManager.shortenClassReferences(mClass.addBefore(constructor, mClass.getLastChild()));
    styleManager.shortenClassReferences(mClass.addBefore(creatorField, mClass.getLastChild()));

    makeClassImplementParcelable(elementFactory);
}
 
Example #12
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * 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: Processor.java    From GsonFormat with Apache License 2.0 5 votes vote down vote up
protected void formatJavCode(PsiClass cls) {
    if (cls == null) {
        return;
    }
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(cls.getProject());
    styleManager.optimizeImports(cls.getContainingFile());
    styleManager.shortenClassReferences(cls);
}
 
Example #15
Source File: AbstractFileProvider.java    From CodeGen with MIT License 5 votes vote down vote up
protected PsiFile createFile(Project project, @NotNull PsiDirectory psiDirectory, String fileName, String context, FileType fileType) {
    PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, context);
    // reformat class
    CodeStyleManager.getInstance(project).reformat(psiFile);
    if (psiFile instanceof PsiJavaFile) {
        JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
        styleManager.optimizeImports(psiFile);
        styleManager.shortenClassReferences(psiFile);
    }
    // TODO: 加入覆盖判断
    psiDirectory.add(psiFile);
    return psiFile;
}
 
Example #16
Source File: ParameterNamePolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    underTest = new ParameterNamePolicy(codeStyleManager);
}
 
Example #17
Source File: FieldNamePolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    underTest = new FieldNamePolicy(codeStyleManager);
}
 
Example #18
Source File: PolygeneConcernUtil.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@NotNull
public static PsiAnnotation addOrReplaceConcernAnnotation( @NotNull PsiModifierListOwner modifierListOwner,
                                                           @NotNull PsiClass concernClassToAdd )
{
    Project project = modifierListOwner.getProject();
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance( project );
    PsiElementFactory factory = psiFacade.getElementFactory();
    PsiAnnotation existingConcernsAnnotation = findAnnotation( modifierListOwner, QUALIFIED_NAME_CONCERNS );

    boolean isReplace = false;
    PsiAnnotation newConcernsAnnotation;
    if( existingConcernsAnnotation != null )
    {
        // Check duplicate
        List<PsiAnnotationMemberValue> concernsValues = getConcernsAnnotationValue( existingConcernsAnnotation );
        for( PsiAnnotationMemberValue concernValue : concernsValues )
        {
            PsiJavaCodeReferenceElement concernClassReference = getConcernClassReference( concernValue );
            if( concernClassReference == null )
            {
                continue;
            }

            PsiElement concernClass = concernClassReference.resolve();
            if( concernClassToAdd.equals( concernClass ) )
            {
                return existingConcernsAnnotation;
            }
        }

        isReplace = true;
    }

    String concernAnnotationText = createConcernAnnotationText( existingConcernsAnnotation, concernClassToAdd );
    newConcernsAnnotation =
        factory.createAnnotationFromText( concernAnnotationText, modifierListOwner );

    if( isReplace )
    {
        // Replace @Concerns instead
        existingConcernsAnnotation.replace( newConcernsAnnotation );
    }
    else
    {
        // @Concerns doesn't exists, add it as first child
        PsiModifierList modifierList = modifierListOwner.getModifierList();
        modifierList.addBefore( newConcernsAnnotation, modifierList.getFirstChild() );
    }

    // Shorten all class references if possible
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance( project );
    codeStyleManager.shortenClassReferences( newConcernsAnnotation );

    return newConcernsAnnotation;
}
 
Example #19
Source File: PolygeneMixinUtil.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@NotNull
public static PsiAnnotation addOrReplaceMixinAnnotation( @NotNull PsiModifierListOwner modifierListOwner,
                                                         @NotNull PsiClass mixinClassToAdd )
{
    Project project = modifierListOwner.getProject();
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance( project );
    PsiElementFactory factory = psiFacade.getElementFactory();
    PsiAnnotation existingMixinsAnnotation = findAnnotation( modifierListOwner, QUALIFIED_NAME_MIXINS );

    boolean isReplace = false;
    PsiAnnotation newMixinsAnnotation;
    if( existingMixinsAnnotation != null )
    {
        // Check duplicate
        List<PsiAnnotationMemberValue> mixinsValues = getMixinsAnnotationValue( existingMixinsAnnotation );
        for( PsiAnnotationMemberValue mixinValue : mixinsValues )
        {
            PsiJavaCodeReferenceElement mixinClassReference = getMixinClassReference( mixinValue );
            if( mixinClassReference == null )
            {
                continue;
            }

            PsiElement mixinClass = mixinClassReference.resolve();
            if( mixinClassToAdd.equals( mixinClass ) )
            {
                return existingMixinsAnnotation;
            }
        }

        isReplace = true;
    }

    String mixinsAnnotationText = createMixinsAnnotationText( existingMixinsAnnotation, mixinClassToAdd );
    newMixinsAnnotation = factory.createAnnotationFromText( mixinsAnnotationText, modifierListOwner );

    if( isReplace )
    {
        // Replace @Mixins instead
        existingMixinsAnnotation.replace( newMixinsAnnotation );
    }
    else
    {
        // @Mixins doesn't exists, add it as first child
        PsiModifierList modifierList = modifierListOwner.getModifierList();
        modifierList.addBefore( newMixinsAnnotation, modifierList.getFirstChild() );
    }

    // Shorten all class references if possible
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance( project );
    codeStyleManager.shortenClassReferences( newMixinsAnnotation );

    return newMixinsAnnotation;
}
 
Example #20
Source File: InflateLocalVariableAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
    DocumentUtil.writeInRunUndoTransparentAction(new Runnable() {
        @Override
        public void run() {
            List<AndroidView> androidViews = AndroidUtils.getIDsFromXML(xmlFile);

            PsiStatement psiStatement = PsiTreeUtil.getParentOfType(psiElement, PsiStatement.class);
            if (psiStatement == null) {
                return;
            }

            PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiStatement.getProject());

            PsiElement[] localVariables = PsiTreeUtil.collectElements(psiStatement.getParent(), new PsiElementFilter() {
                @Override
                public boolean isAccepted(PsiElement element) {
                    return element instanceof PsiLocalVariable;
                }
            });

            Set<String> variables = new HashSet<String>();
            for (PsiElement localVariable : localVariables) {
                variables.add(((PsiLocalVariable) localVariable).getName());
            }

            for (AndroidView v : androidViews) {
                if (!variables.contains(v.getFieldName())) {
                    String sb1;

                    if (variableName != null) {
                        sb1 = String.format("%s %s = (%s) %s.findViewById(%s);", v.getName(), v.getFieldName(), v.getName(), variableName, v.getId());
                    } else {
                        sb1 = String.format("%s %s = (%s) findViewById(%s);", v.getName(), v.getFieldName(), v.getName(), v.getId());
                    }

                    PsiStatement statementFromText = elementFactory.createStatementFromText(sb1, null);
                    psiStatement.getParent().addAfter(statementFromText, psiStatement);
                }
            }

            JavaCodeStyleManager.getInstance(psiStatement.getProject()).shortenClassReferences(psiStatement.getParent());
            new ReformatAndOptimizeImportsProcessor(psiStatement.getProject(), psiStatement.getContainingFile(), true).run();

        }
    });

}
 
Example #21
Source File: InflateThisExpressionAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {

    DocumentUtil.writeInRunUndoTransparentAction(new Runnable() {
        @Override
        public void run() {
            List<AndroidView> androidViews = AndroidUtils.getIDsFromXML(xmlFile);

            PsiStatement psiStatement = PsiTreeUtil.getParentOfType(psiElement, PsiStatement.class);
            if(psiStatement == null) {
                return;
            }

            // collection class field
            // check if we need to set them
            PsiClass psiClass = PsiTreeUtil.getParentOfType(psiStatement, PsiClass.class);
            Set<String> fieldSet = new HashSet<String>();
            for(PsiField field: psiClass.getFields()) {
                fieldSet.add(field.getName());
            }

            // collect this.foo = "" and (this.)foo = ""
            // collection already init variables
            final Set<String> thisSet = new HashSet<String>();
            PsiTreeUtil.processElements(psiStatement.getParent(), new PsiElementProcessor() {

                @Override
                public boolean execute(@NotNull PsiElement element) {

                    if(element instanceof PsiThisExpression) {
                        attachFieldName(element.getParent());
                    } else if(element instanceof PsiAssignmentExpression) {
                       attachFieldName(((PsiAssignmentExpression) element).getLExpression());
                    }

                    return true;
                }

                private void attachFieldName(PsiElement psiExpression) {

                    if(!(psiExpression instanceof PsiReferenceExpression)) {
                        return;
                    }

                    PsiElement psiField = ((PsiReferenceExpression) psiExpression).resolve();
                    if(psiField instanceof PsiField) {
                        thisSet.add(((PsiField) psiField).getName());
                    }
                }
            });


            PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiStatement.getProject());
            for (AndroidView v: androidViews) {

                if(!fieldSet.contains(v.getFieldName())) {
                    String sb = "private " + v.getName() + " " + v.getFieldName() + ";";
                    psiClass.add(elementFactory.createFieldFromText(sb, psiClass));
                }

                if(!thisSet.contains(v.getFieldName())) {

                    String sb1;
                    if(variableName != null) {
                        sb1 = String.format("this.%s = (%s) %s.findViewById(%s);", v.getFieldName(), v.getName(), variableName, v.getId());
                    } else {
                        sb1 = String.format("this.%s = (%s) findViewById(%s);", v.getFieldName(), v.getName(), v.getId());
                    }


                    PsiStatement statementFromText = elementFactory.createStatementFromText(sb1, null);

                    psiStatement.getParent().addAfter(statementFromText, psiStatement);
                }

            }

            JavaCodeStyleManager.getInstance(psiStatement.getProject()).shortenClassReferences(psiStatement.getParent());
            new ReformatAndOptimizeImportsProcessor(psiStatement.getProject(), psiStatement.getContainingFile(), true).run();

        }
    });

}
 
Example #22
Source File: PropertyGenerator.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
/**
 * 1, add Override for super properties.
 * 2, generate super.
 * 3, remove fields/methods which have no annotation of @Keep and @ImplMethod.
 */
void generate() {
    final Project project = mPsiClass.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
    //remove exist method
    removeExistingImpl(mPsiClass);

    List<PsiMethod> methods = new ArrayList<>();
    List<PsiField> fields = new ArrayList<>();

    //generate PROP_selected if possible.
    if(mHasSelectable) {
        fields.add(createConstantField(mPsiClass, elementFactory, Property.PROP_selected));
    }
    //generate for current properties.
    generateProperties(elementFactory, mProps, methods, fields, false);

    final PsiMethod anchor = methods.get(methods.size() - 1);
    PsiComment doc = null;
    if (mSuperFields != null && !mSuperFields.isEmpty()) {
        doc = elementFactory.createCommentFromText(
                "/* \n================== start methods from super properties =============== \n" +
                        "======================================================================= */",
                null);
        //generate for super properties
        generateProperties(elementFactory, mSuperFields, methods, fields, true);
    }

    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    for (PsiField pf : fields) {
        styleManager.shortenClassReferences(pf);
        mPsiClass.add(pf);
    }
    for (PsiMethod psi : methods) {
        styleManager.shortenClassReferences(mPsiClass.addBefore(psi, mPsiClass.getLastChild()));
        if (psi == anchor && doc != null) {
            mPsiClass.addBefore(doc, mPsiClass.getLastChild());
        }
    }
    //extend Poolable.
    TypeInterfaceExtend__Poolable poolable = new TypeInterfaceExtend__Poolable();
    if (!poolable.isSuperClassHas(mPsiClass)) {
        poolable.makeInterfaceExtend(mPsiClass, elementFactory, styleManager);
    }
}
 
Example #23
Source File: PropertyProcessor.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
private void generateInternal(PsiClass mPsiClass, ClassInfo info) {
    if(mPsiClass.getName() == null){
        Util.log("mPsiClass.getName() == null");
        return;
    }
    final Project project = mPsiClass.getProject();
    //delete if exist
    PsiClass psiClass_pre = JavaPsiFacade.getInstance(project).findClass(getSuperClassAsInterfaceName(mPsiClass),
            GlobalSearchScope.projectScope(project));
    if(psiClass_pre != null && psiClass_pre.isValid()){
        if(!psiClass_pre.isWritable()){
            Util.log("the previous PsiClass (" + psiClass_pre.getQualifiedName() + ") can write. will be ignored.");
            return;
        }
        psiClass_pre.delete();
    }

    final String name = "I" + mPsiClass.getName();
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

    PsiElement parent = mPsiClass.getParent();
    if(parent instanceof PsiClass){
        Util.log("start nested class.");
        PsiClass psic = elementFactory.createInterface(name);
        psic.getModifierList().addAnnotation("com.heaven7.java.data.mediator.Fields(value ={\n"
                + buildFieldAnnotations(info.getPropertyInfos())+ "\n} , generateJsonAdapter = false)");
        if (!addExtendInterfaces(info, styleManager, elementFactory, psic)) {
            return;
        }
        styleManager.shortenClassReferences(parent.addAfter(psic, mPsiClass));
    }else{
        PsiDirectory dir = mPsiClass.getContainingFile().getContainingDirectory();
        PsiClass psiClass = createJavaFile(name, "@com.heaven7.java.data.mediator.Fields(value ={\n"
                                    + buildFieldAnnotations(info.getPropertyInfos())
                + "\n}, generateJsonAdapter = false) "
                + "public interface " + name + "{}");
        if (!addExtendInterfaces(info, styleManager, elementFactory, psiClass)) {
            return;
        }
        styleManager.shortenClassReferences(psiClass);
        dir.add(psiClass);
    }
}
 
Example #24
Source File: DelombokHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void finish(Project project, PsiFile psiFile) {
  JavaCodeStyleManager.getInstance(project).optimizeImports(psiFile);
  UndoUtil.markPsiFileForUndo(psiFile);
}
 
Example #25
Source File: ProjectModule.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Provides
@Singleton
public JavaCodeStyleManager provideCodeStyleManager(@Nonnull Project project) {
    return JavaCodeStyleManager.getInstance(project);
}
 
Example #26
Source File: ParameterNamePolicy.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@Inject
public ParameterNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) {
    this.codeStyleManager = codeStyleManager;
}
 
Example #27
Source File: FieldNamePolicy.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@Inject
public FieldNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) {
    this.codeStyleManager = codeStyleManager;
}
 
Example #28
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    final PsiClass targetClass = InnerBuilderUtils.getStaticOrTopLevelClass(file, editor);
    if (targetClass == null) {
        return;
    }
    final Set<InnerBuilderOption> options = currentOptions();
    final PsiClass builderClass = findOrCreateBuilderClass(targetClass);
    final PsiType builderType = psiElementFactory.createTypeFromText(BUILDER_CLASS_NAME, null);
    final PsiMethod constructor = generateConstructor(targetClass, builderType);

    addMethod(targetClass, null, constructor, true);
    final Collection<PsiFieldMember> finalFields = new ArrayList<PsiFieldMember>();
    final Collection<PsiFieldMember> nonFinalFields = new ArrayList<PsiFieldMember>();

    PsiElement lastAddedField = null;
    for (final PsiFieldMember fieldMember : selectedFields) {
        lastAddedField = findOrCreateField(builderClass, fieldMember, lastAddedField);
        if (fieldMember.getElement().hasModifierProperty(PsiModifier.FINAL)
                && !options.contains(InnerBuilderOption.FINAL_SETTERS)) {
            finalFields.add(fieldMember);
            PsiUtil.setModifierProperty((PsiField) lastAddedField, PsiModifier.FINAL, true);
        } else {
            nonFinalFields.add(fieldMember);
        }
    }
    if (options.contains(InnerBuilderOption.NEW_BUILDER_METHOD)) {
        final PsiMethod newBuilderMethod = generateNewBuilderMethod(builderType, finalFields, options);
        addMethod(targetClass, null, newBuilderMethod, false);
    }

    // builder constructor, accepting the final fields
    final PsiMethod builderConstructorMethod = generateBuilderConstructor(builderClass, finalFields, options);
    addMethod(builderClass, null, builderConstructorMethod, false);

    // builder copy constructor or static copy method
    if (options.contains(InnerBuilderOption.COPY_CONSTRUCTOR)) {
        if (options.contains(InnerBuilderOption.NEW_BUILDER_METHOD)) {
            final PsiMethod copyBuilderMethod = generateCopyBuilderMethod(targetClass, builderType,
                    nonFinalFields, options);
            addMethod(targetClass, null, copyBuilderMethod, true);
        } else {
            final PsiMethod copyConstructorBuilderMethod = generateCopyConstructor(targetClass, builderType,
                    selectedFields, options);
            addMethod(builderClass, null, copyConstructorBuilderMethod, true);
        }
    }

    // builder methods
    PsiElement lastAddedElement = null;
    for (final PsiFieldMember member : nonFinalFields) {
        final PsiMethod setterMethod = generateBuilderSetter(builderType, member, options);
        lastAddedElement = addMethod(builderClass, lastAddedElement, setterMethod, false);
    }

    // builder.build() method
    final PsiMethod buildMethod = generateBuildMethod(targetClass, options);
    addMethod(builderClass, lastAddedElement, buildMethod, false);

    JavaCodeStyleManager.getInstance(project).shortenClassReferences(file);
    CodeStyleManager.getInstance(project).reformat(builderClass);
}
 
Example #29
Source File: ITypeInterfaceExtend.java    From data-mediator with Apache License 2.0 votes vote down vote up
void makeInterfaceExtend(PsiClass mClass, PsiElementFactory elementFactory, JavaCodeStyleManager styleManager);