public static PsiFile createFromTemplate(
      final PsiDirectory directory,
      final String name,
      String fileName,
      String templateName,
      @NonNls String... parameters)
      throws IncorrectOperationException {
    log.debug("createFromTemplate: dir:" + directory + ", filename: " + fileName);

    final FileTemplate template = FileTemplateManager.getInstance().getTemplate(templateName);

    Properties properties =
        new Properties(FileTemplateManager.getInstance().getDefaultProperties());

    String text;

    try {
      text = template.getText(properties);
    } catch (Exception e) {
      throw new RuntimeException(
          "Unable to load template for "
              + FileTemplateManager.getInstance().internalTemplateToSubject(templateName),
          e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    log.debug("Create file from text");
    final PsiFile file = factory.createFileFromText(fileName, MoonFileType.MOON_FILE_TYPE, text);

    log.debug("Adding file to directory");
    return (PsiFile) directory.add(file);
  }
  private static PsiClass createClassFromTemplate(
      @NotNull PsiDirectory dir, String name, String templateName, boolean askToDefineVariables)
      throws IncorrectOperationException {
    // checkCreateClassOrInterface(dir, name);

    FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);

    Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties();
    Properties properties = new Properties(defaultProperties);
    properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name);

    String ext = StdFileTypes.JAVA.getDefaultExtension();
    String fileName = name + "." + ext;

    PsiElement element;
    try {
      element =
          askToDefineVariables
              ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties)
                  .create()
              : FileTemplateUtil.createFromTemplate(template, fileName, properties, dir);
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
      return null;
    }
    if (element == null) return null;
    final PsiJavaFile file = (PsiJavaFile) element.getContainingFile();
    PsiClass[] classes = file.getClasses();
    if (classes.length < 1) {
      throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
    }
    return classes[0];
  }
 public void initComponent() {
   removeComponent();
   FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
   FileTemplate scalaTemplate = fileTemplateManager.getTemplate(SCALA_FILE_TEMPLATE);
   if (scalaTemplate == null) {
     registerScalaScriptTemplate();
   }
 }
 private void registerScalaScriptTemplate() {
   String templateText = ScalaBundle.message("template.file.text");
   if (FileTemplateManager.getInstance().getTemplate(SCALA_FILE_TEMPLATE) == null) {
     FileTemplate scalaTemplate =
         FileTemplateManager.getInstance()
             .addTemplate(
                 SCALA_FILE_TEMPLATE, ScalaFileType.SCALA_FILE_TYPE.getDefaultExtension());
     ((FileTemplateImpl) scalaTemplate).setInternal(true);
     scalaTemplate.setText(templateText);
   }
 }
 public static PsiElement createFromTemplate(
     final Project project,
     String templateName,
     String fileName,
     @NotNull PsiDirectory directory,
     Properties properties)
     throws Exception {
   FileTemplateManager manager = FileTemplateManager.getInstance(project);
   FileTemplate template = manager.getInternalTemplate(templateName);
   return FileTemplateUtil.createFromTemplate(template, fileName, properties, directory);
 }
 private static String getText(final String templateName, @Nullable Project project)
     throws IOException {
   final FileTemplateManager templateManager =
       project == null
           ? FileTemplateManager.getDefaultInstance()
           : FileTemplateManager.getInstance(project);
   final FileTemplate template = templateManager.getJ2eeTemplate(templateName);
   if (template == null) {
     return "";
   }
   return template.getText(templateManager.getDefaultProperties());
 }
  @Override
  public void setupRootModel(ModifiableRootModel model) throws ConfigurationException {
    String contentPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentPath)) {
      return;
    }
    File contentRootDir = new File(contentPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile vContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (vContentRootDir == null) {
      return;
    }

    model.addContentEntry(vContentRootDir);

    VirtualFile configFile = getExternalProjectConfigFile(vContentRootDir);
    if (configFile != null && myTemplateConfigName != null) {
      FileTemplateManager manager = FileTemplateManager.getInstance();
      FileTemplate template = manager.getInternalTemplate(myTemplateConfigName);
      try {
        VfsUtil.saveText(configFile, template.getText());
      } catch (IOException e) {
        LOG.warn(
            String.format(
                "Unexpected exception on applying template %s config",
                myExternalSystemId.getReadableName()),
            e);
        throw new ConfigurationException(
            e.getMessage(),
            String.format(
                "Can't apply %s template config text", myExternalSystemId.getReadableName()));
      }
    }

    AbstractExternalSystemSettings settings =
        ExternalSystemApiUtil.getSettings(model.getProject(), myExternalSystemId);
    S externalProjectSettings = createSettings();
    if (myExternalProjectSettingsControl != null) {
      String errorMessage = myExternalProjectSettingsControl.apply(externalProjectSettings);
      myExternalProjectSettingsControl.disposeUIResources();
      if (errorMessage != null) {
        throw new ConfigurationException(errorMessage);
      }
    }
    //noinspection unchecked
    settings.linkProject(externalProjectSettings);
  }
  @SuppressWarnings("DialogTitleCapitalization")
  @Nullable
  public static PsiFile createFileFromTemplate(
      @SuppressWarnings("NullableProblems") @NotNull String name,
      @NotNull FileTemplate template,
      @NotNull PsiDirectory dir,
      @Nullable String defaultTemplateProperty) {
    // TODO: Do we *have* to hack the IntelliJ source?
    // This is a roughly a copy/paste then slight adaptation from the IntelliJ definition of this
    // method.
    // We can't override it directly, and more importantly we can't override its call to
    // FileTemplateUtil.createFromTemplate()
    List<String> pathItems = FileUtil.getPathFromSourceRoot(dir.getProject(), dir.getVirtualFile());
    // modulePrefix is the empty string if the module is either in the top
    // level directory or one of the subdirectories start with a lower-case
    // letter.
    final String modulePrefix =
        pathItems == null || invalidPathItems(pathItems) ? "" : StringUtil.join(pathItems, ".");

    // Adapted from super definition.
    CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(name, dir);
    name = mkdirs.newName;
    dir = mkdirs.directory;
    PsiElement element;
    Project project = dir.getProject();
    try {
      // Patch props with custom property.
      Properties props = FileTemplateManager.getInstance().getDefaultProperties(project);
      props.setProperty(
          "HASKELL_MODULE_NAME", modulePrefix.isEmpty() ? name : modulePrefix + '.' + name);
      element = FileTemplateUtil.createFromTemplate(template, name, props, dir);

      final PsiFile psiFile = element.getContainingFile();

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile != null) {
        FileEditorManager.getInstance(project).openFile(virtualFile, true);
        if (defaultTemplateProperty != null) {
          PropertiesComponent.getInstance(project)
              .setValue(defaultTemplateProperty, template.getName());
        }
        return psiFile;
      }
    } catch (ParseException e) {
      Messages.showErrorDialog(
          project,
          "Error parsing Velocity template: " + e.getMessage(),
          "Create File from Template");
      return null;
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
    }

    return null;
  }
 private static void createTestHelper(@NotNull Project project, PsiDirectory projectDir) {
   final FileTemplate template =
       FileTemplateManager.getInstance(project)
           .getInternalTemplate(FileUtil.getNameWithoutExtension(EduNames.TEST_HELPER));
   try {
     FileTemplateUtil.createFromTemplate(template, EduNames.TEST_HELPER, null, projectDir);
   } catch (Exception ignored) {
   }
 }
示例#10
0
  @Override
  protected void buildDialog(
      final Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
        .setTitle(JavaCoreBundle.message("action.create.new.class"))
        .addKind("Class", PlatformIcons.CLASS_ICON, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME)
        .addKind(
            "Interface",
            PlatformIcons.INTERFACE_ICON,
            JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME);

    Module module = ModuleUtilCore.findModuleForPsiElement(directory);
    assert module != null;
    JavaModuleExtensionImpl moduleExtension =
        ModuleRootManager.getInstance(module).getExtension(JavaModuleExtensionImpl.class);

    assert moduleExtension != null;
    if (moduleExtension.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) {
      builder.addKind(
          "Enum", PlatformIcons.ENUM_ICON, JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME);
      builder.addKind(
          "Annotation",
          PlatformIcons.ANNOTATION_TYPE_ICON,
          JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME);
    }

    for (FileTemplate template : FileTemplateManager.getInstance().getAllTemplates()) {
      final JavaCreateFromTemplateHandler handler = new JavaCreateFromTemplateHandler();
      if (handler.handlesTemplate(template) && JavaCreateFromTemplateHandler.canCreate(directory)) {
        builder.addKind(template.getName(), JavaFileType.INSTANCE.getIcon(), template.getName());
      }
    }

    builder.setValidator(
        new InputValidatorEx() {
          @Override
          public String getErrorText(String inputString) {
            if (inputString.length() > 0
                && !JavaPsiFacade.getInstance(project)
                    .getNameHelper()
                    .isQualifiedName(inputString)) {
              return "This is not a valid Java qualified name";
            }
            return null;
          }

          @Override
          public boolean checkInput(String inputString) {
            return true;
          }

          @Override
          public boolean canClose(String inputString) {
            return !StringUtil.isEmptyOrSpaces(inputString) && getErrorText(inputString) == null;
          }
        });
  }
 @Nullable
 public static VirtualFile createFileFromTemplate(
     final String templateName, final VirtualFile parent, final String fileName) {
   parent.refresh(false, false);
   final FileTemplate template = FileTemplateManager.getInstance().getJ2eeTemplate(templateName);
   try {
     final String text =
         template.getText(FileTemplateManager.getInstance().getDefaultProperties());
     VirtualFile file = parent.findChild(fileName);
     if (file == null) {
       file = parent.createChildData(AppEngineSupportProvider.class, fileName);
     }
     VfsUtil.saveText(file, text);
     return file;
   } catch (IOException e) {
     LOG.error(e);
     return null;
   }
 }
示例#12
0
  private static void runOrApplyFileTemplate(
      Project project,
      VirtualFile file,
      String templateName,
      Properties properties,
      Properties conditions,
      boolean interactive)
      throws IOException {
    FileTemplateManager manager = FileTemplateManager.getInstance();
    FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
    Properties allProperties = manager.getDefaultProperties(project);
    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());
    }
  }
 private static void saveFile(
     @NotNull VirtualFile file, @NotNull String templateName, @Nullable Map templateAttributes)
     throws ConfigurationException {
   FileTemplateManager manager = FileTemplateManager.getInstance();
   FileTemplate template = manager.getInternalTemplate(templateName);
   try {
     VfsUtil.saveText(
         file,
         templateAttributes != null ? template.getText(templateAttributes) : template.getText());
   } catch (IOException e) {
     LOG.warn(
         String.format(
             "Unexpected exception on applying template %s config",
             GradleConstants.SYSTEM_ID.getReadableName()),
         e);
     throw new ConfigurationException(
         e.getMessage(),
         String.format(
             "Can't apply %s template config text", GradleConstants.SYSTEM_ID.getReadableName()));
   }
 }
 public void testSurroundWithTryCatchProperties() {
   FileTemplate template =
       FileTemplateManager.getInstance(getProject())
           .getCodeTemplate(JavaTemplateUtil.TEMPLATE_CATCH_BODY);
   String old = template.getText();
   template.setText("// ${DS} \n" + "${EXCEPTION}.printStackTrace();");
   try {
     doTest(new JavaWithTryCatchSurrounder());
   } finally {
     template.setText(old);
   }
 }
 @Override
 public void update(AnActionEvent event) {
   super.update(event);
   Presentation presentation = event.getPresentation();
   FileTemplate[] allTemplates = FileTemplateManager.getInstance().getAllTemplates();
   for (FileTemplate template : allTemplates) {
     if (canCreateFromTemplate(event, template)) {
       presentation.setEnabled(true);
       return;
     }
   }
   presentation.setEnabled(false);
 }
 @Nullable
 public static PsiElement createFromTemplate(
     @NotNull Project project,
     @NotNull VirtualFile rootDir,
     @NotNull String templateName,
     @NotNull String fileName)
     throws Exception {
   return createFromTemplate(
       project,
       rootDir,
       templateName,
       fileName,
       FileTemplateManager.getInstance(project).getDefaultProperties());
 }
  @Nullable
  private PsiFile createFile(final String text, final String name) {
    if (myTemplate == null || myProject == null) return null;

    final FileType fileType = myVelocityFileType;
    if (fileType == FileTypes.UNKNOWN) return null;

    final PsiFile file =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText(name + ".txt.ft", fileType, text, 0, true);
    file.getViewProvider()
        .putUserData(
            FileTemplateManager.DEFAULT_TEMPLATE_PROPERTIES,
            FileTemplateManager.getInstance().getDefaultProperties(myProject));
    return file;
  }
 private static String getIncorrectTemplateMessage(String templateName) {
   return PsiBundle.message(
       "psi.error.incorroect.class.template.message",
       FileTemplateManager.getInstance().internalTemplateToSubject(templateName),
       templateName);
 }
示例#19
0
 public NewKotlinFileAction() {
   super(FileTemplateManager.getInstance().getInternalTemplate("Kotlin File"));
 }
示例#20
0
 private void removeComponent() {
   FileTemplate scalaTemplate = FileTemplateManager.getInstance().getTemplate(SCALA_FILE_TEMPLATE);
   if (scalaTemplate != null)
     FileTemplateManager.getInstance().removeTemplate(scalaTemplate, false);
 }
 private static FileTemplate getInternalTemplateByName(
     @NotNull final Project project, String name) {
   return FileTemplateManager.getInstance(project).getInternalTemplate(name);
 }
  @Override
  @NotNull
  public AnAction[] getChildren(@Nullable AnActionEvent e) {
    FileTemplateManager manager = FileTemplateManager.getInstance();
    FileTemplate[] templates = manager.getAllTemplates();

    boolean showAll = templates.length <= FileTemplateManager.RECENT_TEMPLATES_SIZE;
    if (!showAll) {
      Collection<String> recentNames = manager.getRecentNames();
      templates = new FileTemplate[recentNames.size()];
      int i = 0;
      for (String name : recentNames) {
        templates[i] = FileTemplateManager.getInstance().getTemplate(name);
        i++;
      }
    }

    Arrays.sort(
        templates,
        new Comparator<FileTemplate>() {
          @Override
          public int compare(FileTemplate template1, FileTemplate template2) {
            // java first
            if (template1.isTemplateOfType(InternalStdFileTypes.JAVA)
                && !template2.isTemplateOfType(InternalStdFileTypes.JAVA)) {
              return -1;
            }
            if (template2.isTemplateOfType(InternalStdFileTypes.JAVA)
                && !template1.isTemplateOfType(InternalStdFileTypes.JAVA)) {
              return 1;
            }

            // group by type
            int i = template1.getExtension().compareTo(template2.getExtension());
            if (i != 0) {
              return i;
            }

            // group by name if same type
            return template1.getName().compareTo(template2.getName());
          }
        });
    List<AnAction> result = new ArrayList<AnAction>();

    for (FileTemplate template : templates) {
      if (canCreateFromTemplate(e, template)) {
        AnAction action = replaceAction(template);
        if (action == null) {
          action = new CreateFromTemplateAction(template);
        }
        result.add(action);
      }
    }

    if (!result.isEmpty()) {
      if (!showAll) {
        result.add(new CreateFromTemplatesAction(IdeBundle.message("action.from.file.template")));
      }

      result.add(AnSeparator.getInstance());
      result.add(new EditFileTemplatesAction(IdeBundle.message("action.edit.file.templates")));
    }

    return result.toArray(new AnAction[result.size()]);
  }