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;
}
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;
}
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);
}
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();
}
}
}
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);
}
Aggregations