Search in sources :

Example 46 with FileTemplate

use of com.intellij.ide.fileTemplates.FileTemplate in project intellij-community by JetBrains.

the class I18nizeQuickFixDialog method createPropertiesFileIfNotExists.

private boolean createPropertiesFileIfNotExists() {
    if (getPropertiesFile() != null)
        return true;
    final String path = FileUtil.toSystemIndependentName(myPropertiesFile.getText());
    if (StringUtil.isEmptyOrSpaces(path)) {
        String message = CodeInsightBundle.message("i18nize.empty.file.path", myPropertiesFile.getText());
        Messages.showErrorDialog(myProject, message, CodeInsightBundle.message("i18nize.error.creating.properties.file"));
        myPropertiesFile.requestFocusInWindow();
        return false;
    }
    final FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(path);
    if (fileType != StdFileTypes.PROPERTIES && fileType != StdFileTypes.XML) {
        String message = CodeInsightBundle.message("i18nize.cant.create.properties.file.because.its.name.is.associated", myPropertiesFile.getText(), fileType.getDescription());
        Messages.showErrorDialog(myProject, message, CodeInsightBundle.message("i18nize.error.creating.properties.file"));
        myPropertiesFile.requestFocusInWindow();
        return false;
    }
    try {
        final File file = new File(path).getCanonicalFile();
        FileUtil.createParentDirs(file);
        ApplicationManager.getApplication().runWriteAction(new ThrowableComputable<PsiFile, Exception>() {

            @Override
            public PsiFile compute() throws Exception {
                VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file.getParentFile());
                final PsiManager psiManager = PsiManager.getInstance(myProject);
                if (dir == null) {
                    throw new IOException("Error creating directory structure for file '" + path + "'");
                }
                if (fileType == StdFileTypes.PROPERTIES) {
                    return psiManager.findFile(dir.createChildData(this, file.getName()));
                } else {
                    FileTemplate template = FileTemplateManager.getInstance(myProject).getInternalTemplate("XML Properties File.xml");
                    LOG.assertTrue(template != null);
                    return (PsiFile) FileTemplateUtil.createFromTemplate(template, file.getName(), null, psiManager.findDirectory(dir));
                }
            }
        });
    } catch (Exception e) {
        Messages.showErrorDialog(myProject, e.getLocalizedMessage(), CodeInsightBundle.message("i18nize.error.creating.properties.file"));
        return false;
    }
    return true;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileType(com.intellij.openapi.fileTypes.FileType) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) PsiManager(com.intellij.psi.PsiManager) PsiFile(com.intellij.psi.PsiFile) IOException(java.io.IOException) PropertiesFile(com.intellij.lang.properties.psi.PropertiesFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) IOException(java.io.IOException)

Example 47 with FileTemplate

use of com.intellij.ide.fileTemplates.FileTemplate in project intellij-community by JetBrains.

the class GroovyTemplatesFactory method createFromTemplate.

public static PsiFile createFromTemplate(@NotNull final PsiDirectory directory, @NotNull final String name, @NotNull String fileName, @NotNull String templateName, boolean allowReformatting, @NonNls String... parameters) throws IncorrectOperationException {
    final FileTemplate template = FileTemplateManager.getInstance(directory.getProject()).getInternalTemplate(templateName);
    Project project = directory.getProject();
    Properties properties = new Properties(FileTemplateManager.getInstance(project).getDefaultProperties());
    JavaTemplateUtil.setPackageNameAttribute(properties, directory);
    properties.setProperty(NAME_TEMPLATE_PROPERTY, name);
    properties.setProperty(LOW_CASE_NAME_TEMPLATE_PROPERTY, StringUtil.decapitalize(name));
    for (int i = 0; i < parameters.length; i += 2) {
        properties.setProperty(parameters[i], parameters[i + 1]);
    }
    String text;
    try {
        text = template.getText(properties);
    } catch (Exception e) {
        String message = "Unable to load template for " + FileTemplateManager.getInstance(project).internalTemplateToSubject(templateName);
        throw new RuntimeException(message, e);
    }
    final PsiFileFactory factory = PsiFileFactory.getInstance(project);
    PsiFile file = factory.createFileFromText(fileName, GroovyFileType.GROOVY_FILE_TYPE, text);
    file = (PsiFile) directory.add(file);
    if (file != null && allowReformatting && template.isReformatCode()) {
        new ReformatCodeProcessor(project, file, null, false).run();
    }
    return file;
}
Also used : Project(com.intellij.openapi.project.Project) PsiFileFactory(com.intellij.psi.PsiFileFactory) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) PsiFile(com.intellij.psi.PsiFile) ReformatCodeProcessor(com.intellij.codeInsight.actions.ReformatCodeProcessor) Properties(java.util.Properties) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 48 with FileTemplate

use of com.intellij.ide.fileTemplates.FileTemplate in project intellij-community by JetBrains.

the class IntentionUtils method createTemplateForMethod.

public static void createTemplateForMethod(PsiType[] argTypes, ChooseTypeExpression[] paramTypesExpressions, PsiMethod method, PsiClass owner, TypeConstraint[] constraints, boolean isConstructor, @NotNull final PsiElement context) {
    final Project project = owner.getProject();
    PsiTypeElement typeElement = method.getReturnTypeElement();
    ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), context.getResolveScope(), method.getLanguage() == GroovyLanguage.INSTANCE);
    TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
    if (!isConstructor) {
        assert typeElement != null;
        builder.replaceElement(typeElement, expr);
    }
    PsiParameter[] parameters = method.getParameterList().getParameters();
    assert parameters.length == argTypes.length;
    for (int i = 0; i < parameters.length; i++) {
        PsiParameter parameter = parameters[i];
        PsiTypeElement parameterTypeElement = parameter.getTypeElement();
        builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]);
        builder.replaceElement(parameter.getNameIdentifier(), new ParameterNameExpression(null));
    }
    PsiCodeBlock body = method.getBody();
    if (body != null) {
        PsiElement lbrace = body.getLBrace();
        assert lbrace != null;
        builder.setEndVariableAfter(lbrace);
    } else {
        builder.setEndVariableAfter(method.getParameterList());
    }
    method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
    Template template = builder.buildTemplate();
    final PsiFile targetFile = owner.getContainingFile();
    final Editor newEditor = positionCursor(project, targetFile, method);
    TextRange range = method.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    TemplateEditingListener templateListener = new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
                final int offset = newEditor.getCaretModel().getOffset();
                PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
                if (context instanceof PsiMethod) {
                    final PsiTypeParameter[] typeParameters = ((PsiMethod) context).getTypeParameters();
                    if (typeParameters.length > 0) {
                        for (PsiTypeParameter typeParameter : typeParameters) {
                            if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) {
                                final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject());
                                PsiTypeParameterList list = method1.getTypeParameterList();
                                if (list == null) {
                                    PsiTypeParameterList newList = factory.createTypeParameterList();
                                    list = (PsiTypeParameterList) method1.addAfter(newList, method1.getModifierList());
                                }
                                list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes()));
                            }
                        }
                    }
                }
                if (method1 != null) {
                    try {
                        final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod;
                        if (hasNoReturnType) {
                            ((GrMethod) method1).setReturnType(PsiType.VOID);
                        }
                        if (method1.getBody() != null) {
                            FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
                            FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY);
                            PsiClass containingClass = method1.getContainingClass();
                            LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up");
                            CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate);
                        }
                        if (hasNoReturnType) {
                            ((GrMethod) method1).setReturnType(null);
                        }
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                    CreateFromUsageUtils.setupEditor(method1, newEditor);
                }
            });
        }
    };
    manager.startTemplate(newEditor, template, templateListener);
}
Also used : FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) TextRange(com.intellij.openapi.util.TextRange) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) ParameterNameExpression(org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression)

Example 49 with FileTemplate

use of com.intellij.ide.fileTemplates.FileTemplate in project intellij-community by JetBrains.

the class MavenUtil method runOrApplyFileTemplate.

private static void runOrApplyFileTemplate(Project project, VirtualFile file, String templateName, Properties properties, Properties conditions, boolean interactive) throws IOException {
    FileTemplateManager manager = FileTemplateManager.getInstance(project);
    FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
    Properties allProperties = manager.getDefaultProperties();
    if (!interactive) {
        allProperties.putAll(properties);
    }
    allProperties.putAll(conditions);
    String text = fileTemplate.getText(allProperties);
    Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
    Matcher matcher = pattern.matcher(text);
    StringBuffer builder = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(builder, "\\$" + matcher.group(1).toUpperCase() + "\\$");
    }
    matcher.appendTail(builder);
    text = builder.toString();
    TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(project).createTemplate("", "", text);
    for (int i = 0; i < template.getSegmentsCount(); i++) {
        if (i == template.getEndSegmentNumber())
            continue;
        String name = template.getSegmentName(i);
        String value = "\"" + properties.getProperty(name, "") + "\"";
        template.addVariable(name, value, value, true);
    }
    if (interactive) {
        OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
        Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
        editor.getDocument().setText("");
        TemplateManager.getInstance(project).startTemplate(editor, template);
    } else {
        VfsUtil.saveText(file, template.getTemplateText());
        PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
        if (psiFile != null) {
            new ReformatCodeProcessor(project, psiFile, null, false).run();
        }
    }
}
Also used : TemplateImpl(com.intellij.codeInsight.template.impl.TemplateImpl) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ReformatCodeProcessor(com.intellij.codeInsight.actions.ReformatCodeProcessor) SystemProperties(com.intellij.util.SystemProperties) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor) PsiFile(com.intellij.psi.PsiFile) Editor(com.intellij.openapi.editor.Editor)

Example 50 with FileTemplate

use of com.intellij.ide.fileTemplates.FileTemplate in project intellij-community by JetBrains.

the class TestNGDataProviderInspection method createMethodFix.

private static CreateMethodQuickFix createMethodFix(PsiAnnotationMemberValue provider, @NotNull PsiClass providerClass, PsiClass topLevelClass) {
    final String name = StringUtil.unquoteString(provider.getText());
    FileTemplateDescriptor templateDesc = new TestNGFramework().getParametersMethodFileTemplateDescriptor();
    assert templateDesc != null;
    final FileTemplate fileTemplate = FileTemplateManager.getInstance(provider.getProject()).getCodeTemplate(templateDesc.getFileName());
    String body = "";
    try {
        final Properties attributes = new Properties();
        attributes.put(FileTemplate.ATTRIBUTE_NAME, name);
        body = fileTemplate.getText(attributes);
        body = body.replace("${BODY}\n", "");
        final PsiMethod methodFromTemplate = JavaPsiFacade.getElementFactory(providerClass.getProject()).createMethodFromText(body, providerClass);
        final PsiCodeBlock methodBody = methodFromTemplate.getBody();
        if (methodBody != null) {
            body = StringUtil.trimEnd(StringUtil.trimStart(methodBody.getText(), "{"), "}");
        } else {
            body = "";
        }
    } catch (Exception ignored) {
    }
    if (StringUtil.isEmptyOrSpaces(body)) {
        body = "return new Object[][]{};";
    }
    String signature = "@" + DataProvider.class.getName() + " public ";
    if (providerClass == topLevelClass) {
        signature += "static ";
    }
    signature += "Object[][] " + name + "()";
    return CreateMethodQuickFix.createFix(providerClass, signature, body);
}
Also used : TestNGFramework(com.theoryinpractice.testng.TestNGFramework) FileTemplateDescriptor(com.intellij.ide.fileTemplates.FileTemplateDescriptor) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) Properties(java.util.Properties) IOException(java.io.IOException)

Aggregations

FileTemplate (com.intellij.ide.fileTemplates.FileTemplate)66 FileTemplateManager (com.intellij.ide.fileTemplates.FileTemplateManager)20 Project (com.intellij.openapi.project.Project)13 IOException (java.io.IOException)12 PsiFile (com.intellij.psi.PsiFile)10 Properties (java.util.Properties)10 VirtualFile (com.intellij.openapi.vfs.VirtualFile)8 IncorrectOperationException (com.intellij.util.IncorrectOperationException)8 PsiDirectory (com.intellij.psi.PsiDirectory)7 NotNull (org.jetbrains.annotations.NotNull)7 PsiElement (com.intellij.psi.PsiElement)6 Module (com.intellij.openapi.module.Module)5 File (java.io.File)5 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)5 Nullable (org.jetbrains.annotations.Nullable)4 Editor (com.intellij.openapi.editor.Editor)3 ConfigurationException (com.intellij.openapi.options.ConfigurationException)3 ArrayList (java.util.ArrayList)3 Pattern (java.util.regex.Pattern)3 ReformatCodeProcessor (com.intellij.codeInsight.actions.ReformatCodeProcessor)2