Java Code Examples for com.intellij.psi.codeStyle.JavaCodeStyleManager#shortenClassReferences()

The following examples show how to use com.intellij.psi.codeStyle.JavaCodeStyleManager#shortenClassReferences() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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;
}