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 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());
 }
 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 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);
  }
 @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;
   }
 }
Ejemplo n.º 7
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());
    }
  }
  @Override
  public void reset() {
    final String text = (myTemplate == null) ? "" : myTemplate.getText();
    String name = (myTemplate == null) ? "" : myTemplate.getName();
    String extension = (myTemplate == null) ? "" : myTemplate.getExtension();
    String description = (myTemplate == null) ? "" : myTemplate.getDescription();

    if ((description.length() == 0) && (myDefaultDescriptionUrl != null)) {
      try {
        description = UrlUtil.loadText(myDefaultDescriptionUrl);
      } catch (IOException e) {
        LOG.error(e);
      }
    }

    EditorFactory.getInstance().releaseEditor(myTemplateEditor);
    myFile = createFile(text, name);
    myTemplateEditor = createEditor();

    boolean adjust = (myTemplate != null) && myTemplate.isReformatCode();
    myNameField.setText(name);
    myExtensionField.setText(extension);
    myAdjustBox.setSelected(adjust);
    String desc = description.length() > 0 ? description : EMPTY_HTML;

    // [myakovlev] do not delete these stupid lines! Or you get Exception!
    myDescriptionComponent.setContentType(CONTENT_TYPE_PLAIN);
    myDescriptionComponent.setEditable(true);
    myDescriptionComponent.setText(desc);
    myDescriptionComponent.setContentType(UIUtil.HTML_MIME);
    myDescriptionComponent.setText(desc);
    myDescriptionComponent.setCaretPosition(0);
    myDescriptionComponent.setEditable(false);

    myDescriptionPanel.setVisible(StringUtil.isNotEmpty(description));

    myNameField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
    myExtensionField.setEditable((myTemplate != null) && (!myTemplate.isDefault()));
    myModified = false;
  }
  private Editor createEditor() {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document doc =
        myFile == null
            ? editorFactory.createDocument(myTemplate == null ? "" : myTemplate.getText())
            : PsiDocumentManager.getInstance(myFile.getProject()).getDocument(myFile);
    Editor editor =
        myProject == null
            ? editorFactory.createEditor(doc)
            : editorFactory.createEditor(doc, myProject);

    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setVirtualSpace(false);
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setLineNumbersShown(false);
    editorSettings.setFoldingOutlineShown(false);
    editorSettings.setAdditionalColumnsCount(3);
    editorSettings.setAdditionalLinesCount(3);

    EditorColorsScheme scheme = editor.getColorsScheme();
    scheme.setColor(EditorColors.CARET_ROW_COLOR, null);

    editor
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              public void documentChanged(DocumentEvent e) {
                onTextChanged();
              }
            });

    ((EditorEx) editor).setHighlighter(createHighlighter());
    mySplitter.setFirstComponent(editor.getComponent());
    return editor;
  }