com.intellij.ide.highlighter.JavaFileType Java Examples

The following examples show how to use com.intellij.ide.highlighter.JavaFileType. 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: SettingsPanel.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
private void createUIComponents() {
    final EditorFactory editorFactory = EditorFactory.getInstance();
    previewDocument = editorFactory.createDocument(EMPTY_TEXT);
    previewEditor = editorFactory.createEditor(previewDocument, null, JavaFileType.INSTANCE, true);

    final EditorSettings settings = previewEditor.getSettings();
    settings.setWhitespacesShown(true);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setLineNumbersShown(false);
    settings.setFoldingOutlineShown(false);
    settings.setRightMarginShown(false);
    settings.setVirtualSpace(false);
    settings.setWheelFontChangeEnabled(false);
    settings.setUseSoftWraps(false);
    settings.setAdditionalColumnsCount(0);
    settings.setAdditionalLinesCount(1);

    previewPanel = (JPanel) previewEditor.getComponent();
    previewPanel.setName(PREVIEW_PANEL_NAME);
    previewPanel.setPreferredSize(new Dimension(PREFERRED_PREVIEW_WIDTH, PREFERRED_PREVIEW_HEIGHT));
}
 
Example #2
Source File: NewClassCommandAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(@NotNull Result<PsiFile> result) throws Throwable {
    final PsiPackage packageElement = directoryService.getPackage(directory);
    if (packageElement == null) {
        throw new InvalidDirectoryException("Target directory does not provide a package");
    }

    final String fileName = Extensions.append(name, StdFileTypes.JAVA);
    final PsiFile found = directory.findFile(fileName);
    if (found != null) {
        throw new ClassAlreadyExistsException("Class '" + name + "'already exists in " + packageElement.getName());
    }

    final String packageName = packageElement.getQualifiedName();
    final String className = Extensions.remove(this.name, StdFileTypes.JAVA);
    try {
        final String java = converter.convert(packageName, className, json);
        final PsiFile classFile = fileFactory.createFileFromText(fileName, JavaFileType.INSTANCE, java);
        CodeStyleManager.getInstance(classFile.getProject()).reformat(classFile);
        JavaCodeStyleManager.getInstance(classFile.getProject()).optimizeImports(classFile);
        final PsiFile created = (PsiFile) directory.add(classFile);
        result.setResult(created);
    } catch (IOException e) {
        throw new ClassCreationException("Failed to create new class from JSON", e);
    }
}
 
Example #3
Source File: CamelDocumentationProviderTestIT.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
public void testGenerateDoc() throws Exception {
    myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestDataWithCursorAfterQuestionMark());

    PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
    String componentName = "file";
    String lookup = componentName + ":inbox?delete";
    PsiManager manager = myFixture.getPsiManager();

    PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);

    String doc = new CamelDocumentationProvider().generateDoc(docInfo, null);
    assertEquals(readExpectedFile(), doc);

    String documentation = new CamelDocumentationProvider().generateDoc(element, null);
    assertNotNull(documentation);
    assertTrue(documentation.startsWith("<b>File Component</b><br/>The file component is used for reading or writing files.<br/>"));
}
 
Example #4
Source File: PropertyProcessor.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
private PsiClass createJavaFile(String javaFileName, @NonNls String text) {
    PsiJavaFile psiJavaFile = (PsiJavaFile) PsiFileFactory.getInstance(mPsiClass.getProject()).createFileFromText(
            javaFileName + "." + JavaFileType.INSTANCE.getDefaultExtension(),
            JavaFileType.INSTANCE, text);
    PsiClass[] classes = psiJavaFile.getClasses();
    if (classes.length != 1) {
        throw new IncorrectOperationException("Incorrect class '" + text + "'");
    } else {
        PsiClass pc = classes[0];
        if (pc == null) {
            throw new IllegalStateException(String.format("@NotNull method %s.%s must not return null",
                    "com/intellij/psi/impl/PsiJavaParserFacadeImpl", "createJavaFile"));
        } else {
            return pc;
        }
    }
}
 
Example #5
Source File: OttoProjectHandler.java    From otto-intellij-plugin with Apache License 2.0 5 votes vote down vote up
private void maybeRecomputeEventClasses() {
  List<VirtualFile> myFilesToScan;
  synchronized (filesToScan) {
    if (filesToScan.isEmpty()) return;

    myFilesToScan = new ArrayList<VirtualFile>(filesToScan);
    filesToScan.clear();
  }

  for (VirtualFile virtualFile : myFilesToScan) {
    synchronized (fileToEventClasses) {
      getEventClasses(virtualFile).clear();
    }
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
    if (psiFile == null) throw new IllegalStateException("huh? " + virtualFile);
    if (psiFile.getFileType() instanceof JavaFileType) {

      final long startTime = System.currentTimeMillis();
      psiFile.accept(new PsiRecursiveElementVisitor() {
        @Override public void visitElement(PsiElement element) {
          if (element instanceof PsiMethod
              && SubscriberMetadata.isAnnotatedWithSubscriber((PsiMethod) element)) {
            maybeAddSubscriberMethod((PsiMethod) element);
          } else {
            super.visitElement(element);
          }
        }
      });
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Searched for @Subscribe in %s in %dms",
            virtualFile, System.currentTimeMillis() - startTime));
      }
    }
  }

  optimizeEventClassIndex();
}
 
Example #6
Source File: GodClassPreviewResultDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
private void createTablePanel() {
    treeTable.setRootVisible(false);
    treeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    treeTable.getTree().addTreeSelectionListener((ElementSelectionListener) this::updateDiff);
    scrollPane = ScrollPaneFactory.createScrollPane(treeTable);
    myChain.setContent2(diffContentFactory.create(project, getTextAndReformat(previewProcessor.getExtractedClass().getPsiClass()), JavaFileType.INSTANCE));
}
 
Example #7
Source File: ExtractConceptActionTest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHideExtractToConceptActionWhenNotGaugeFile() {
    when(dataContext.getData(CommonDataKeys.VIRTUAL_FILE.getName())).thenReturn(vFile);
    when(dataContext.getData(CommonDataKeys.PROJECT.getName())).thenReturn(project);
    when(vFile.getFileType()).thenReturn(JavaFileType.INSTANCE);
    when(event.getPresentation()).thenReturn(presentation);
    when(event.getDataContext()).thenReturn(dataContext);
    when(helper.isGaugeModule(vFile, project)).thenReturn(true);

    new ExtractConceptAction(helper).update(event);

    assertFalse(presentation.isEnabled());
}
 
Example #8
Source File: CustomRenameHandlerTest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldNotRenameInNonGaugeFile() throws Exception {
    PsiElement element = mock(SpecStepImpl.class);

    when(virtualFile.getFileType()).thenReturn(JavaFileType.INSTANCE);
    when(dataContext.getData(CommonDataKeys.PSI_ELEMENT.getName())).thenReturn(element);
    when(dataContext.getData(CommonDataKeys.VIRTUAL_FILE.getName())).thenReturn(virtualFile);
    when(dataContext.getData(CommonDataKeys.EDITOR.getName())).thenReturn(editor);
    when(dataContext.getData(CommonDataKeys.PROJECT.getName())).thenReturn(project);

    assertFalse("Should rename in non gauge file. Expected: false, Actual: true", new CustomRenameHandler().isAvailableOnDataContext(dataContext));
}
 
Example #9
Source File: FileManager.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
public static List<PsiFile> getAllJavaFiles(Module module) {
    Collection<VirtualFile> javaVirtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, moduleScope(module));
    List<PsiFile> javaFiles = new ArrayList<>();

    for (VirtualFile javaVFile : javaVirtualFiles) {
        PsiFile file = PsiManager.getInstance(module.getProject()).findFile(javaVFile);
        if (file != null && PsiTreeUtil.findChildrenOfType(file, PsiClass.class).size() > 0) {
            javaFiles.add(file);
        }
    }
    Collections.sort(javaFiles, (o1, o2) -> FileManager.getJavaFileName(o1).compareToIgnoreCase(FileManager.getJavaFileName(o2)));
    return javaFiles;
}
 
Example #10
Source File: NoPolAction.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method is responsible to add the current test case, if the current file is, otherwise it
 * it will send a empty array of String in that way nopol will run all tests cases
 * @param project
 * @param editor
 * @param currentFile
 * @return
 */
private VirtualFile buildTestProject(Project project, Editor editor, PsiFile currentFile) {
	VirtualFile file = PsiUtilBase.getPsiFileInEditor(editor, project).getVirtualFile();
	String fullQualifiedNameOfCurrentFile = ((PsiJavaFile) currentFile).getPackageName() + "." + currentFile.getName();
	fullQualifiedNameOfCurrentFile = fullQualifiedNameOfCurrentFile.substring(0, fullQualifiedNameOfCurrentFile.length() - JavaFileType.DEFAULT_EXTENSION.length() - 1);
	if (ProjectRootManager.getInstance(project).getFileIndex().isInTestSourceContent(file)) {
		nopolContext.setProjectTests(fullQualifiedNameOfCurrentFile.split(" "));
	} else {
		nopolContext.setProjectTests(new String[0]);// we will hit all the test case in the project
	}
	return file;
}
 
Example #11
Source File: NoPolAction.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
	Project project = event.getData(PlatformDataKeys.PROJECT);
	Editor editor = event.getData(PlatformDataKeys.EDITOR);
	PsiFile currentFile = PsiUtilBase.getPsiFileInEditor(editor, project);

	if (JavaFileType.INSTANCE != currentFile.getFileType())
		return;

	try {
		File outputZip = File.createTempFile(project.getName(), ".zip");
		VirtualFile file = buildTestProject(project, editor, currentFile);
		Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(file);
		Ziper ziper = new Ziper(outputZip.getAbsolutePath(), project);

		//sources folder
		buildSources(ziper, module);

		//Classpath
		buildClasspath(ziper, module);

		ProgressManager.getInstance().run(new NoPolTask(project, "NoPol is Fixing", outputZip.getAbsolutePath()));
		ziper.close();
		this.parent.close(0);
	} catch (IOException e1) {
		throw new RuntimeException(e1);
	}
}
 
Example #12
Source File: CamelDocumentationProviderTestIT.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public void testHandleExternalLink() {
    myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestDataWithCursorBeforeColon());

    PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);

    CamelDocumentationProvider provider = new CamelDocumentationProvider();
    boolean externalLink = provider.handleExternalLink(null, "http://bennet-schulz.com", element);
    assertFalse(externalLink);
}
 
Example #13
Source File: CamelDocumentationProviderTestIT.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public void testJavaClassQuickNavigateInfo() throws Exception {
    myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestWithCursorBeforeCamelComponent());

    PsiClass psiClass = getTestClass();
    PsiReference referenceElement = myFixture.getReferenceAtCaretPosition();
    assertNotNull(referenceElement);

    String docInfo = new CamelDocumentationProvider().getQuickNavigateInfo(psiClass, referenceElement.getElement());
    assertNotNull(docInfo);
    assertEquals(exampleHtmlFileText(getTestName(true)), docInfo);
}
 
Example #14
Source File: CamelSmartCompletionMultiValuePrefixDocumentationTestIT.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public void testSmartCompletionDocumentation() throws Exception {
    myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestData());

    PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
    String componentName = "file";
    String lookup = componentName + ":inbox?scheduler.";
    PsiManager manager = myFixture.getPsiManager();

    PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);

    CamelDocumentationProvider.DocumentationElement de = (CamelDocumentationProvider.DocumentationElement) docInfo;
    assertEquals(componentName, de.getComponentName());
    assertEquals("schedulerProperties", de.getText());
    assertEquals("schedulerProperties", de.getEndpointOption());
}
 
Example #15
Source File: CamelSmartCompletionDocumentationTestIT.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public void testSmartCompletionDocumentation() throws Exception {
    myFixture.configureByText(JavaFileType.INSTANCE, getJavaTestData());

    PsiElement element = myFixture.findElementByText("\"file:inbox?\"", PsiLiteralExpression.class);
    String componentName = "file";
    String lookup = componentName + ":inbox?delete";
    PsiManager manager = myFixture.getPsiManager();

    PsiElement docInfo = new CamelDocumentationProvider().getDocumentationElementForLookupItem(manager, lookup, element);

    CamelDocumentationProvider.DocumentationElement de = (CamelDocumentationProvider.DocumentationElement) docInfo;
    assertEquals(componentName, de.getComponentName());
    assertEquals("delete", de.getText());
    assertEquals("delete", de.getEndpointOption());
}
 
Example #16
Source File: DefaultProviderImpl.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){

    VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
    velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
    // $!dateFormatUtils.format($!now,'yyyy-MM-dd')
    velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
    if (extraMap != null && extraMap.size() > 0) {
        for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }
    }

    String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
    String subPath = VelocityUtil.evaluate(velocityContext, template.getSubPath());
    String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());

    WriteCommandAction.runWriteCommandAction(this.project, () -> {
        try {
            VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
            PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
            PsiDirectory directory = subDirectory(psiDirectory, subPath, template.getResources());
            // TODO: 这里干啥用的, 没用的话是不是可以删除了
            if (JavaFileType.INSTANCE == this.languageFileType) {
                PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
                if (psiPackage != null && !StringUtils.isEmpty(psiPackage.getQualifiedName())) {
                    extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
                }
            }
            createFile(project, directory, fileName + "." + this.languageFileType.getDefaultExtension(), temp, this.languageFileType);
        } catch (Exception e) {
            LOGGER.error(StringUtils.getStackTraceAsString(e));
        }
    });
}
 
Example #17
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void appendShouldAppendExtensionWhenAnotherExtensionExists() throws Exception {
    // exercise
    final String actual = Extensions.append("foo.tmp", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo.tmp.java");
}
 
Example #18
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void appendShouldNotAppendExtensionWhenExtensionExists() throws Exception {
    // exercise
    final String actual = Extensions.append("foo.java", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo.java");
}
 
Example #19
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void appendShouldAppendExtension() throws Exception {
    // exercise
    final String actual = Extensions.append("foo", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo.java");
}
 
Example #20
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void removeShouldReturnFileNameWhenExtensionDoesNotExist() throws Exception {
    // exercise
    final String actual = Extensions.remove("foo", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo");
}
 
Example #21
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void removeShouldNotRemoveExtensionWhenNotMatch() throws Exception {
    // exercise
    final String actual = Extensions.remove("foo.java.tmp", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo.java.tmp");
}
 
Example #22
Source File: ExtensionsTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void removeShouldRemoveExtension() throws Exception {
    // exercise
    final String actual = Extensions.remove("foo.java", JavaFileType.INSTANCE);

    // verify
    assertThat(actual)
            .isEqualTo("foo");
}
 
Example #23
Source File: BuilderFactory.java    From OkHttpParamsGet with Apache License 2.0 5 votes vote down vote up
@Nullable
public static IBuilder getParamsBuilder(int type, PsiFile psiFile) {
    if (psiFile == null) return null;
    if (psiFile.getFileType() instanceof JavaFileType) {
        return getJavaBuilder(type);
    } else if (psiFile.getFileType() instanceof KotlinFileType) {
        return getKotlinBuilder(type);
    }
    return null;
}
 
Example #24
Source File: LithoPluginIntellijTest.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * Converts list of class names to the list of psi classes.
 *
 * @param handler calling class should pass handler for the psi classes. Passes null if
 *     conversion was unsuccessful at any step.
 * @param clsNames names of the classes to found in the test root directory (MyClass.java)
 */
public void getPsiClass(Function<List<PsiClass>, Boolean> handler, String... clsNames) {
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            List<PsiClass> psiClasses =
                Stream.of(clsNames)
                    .filter(Objects::nonNull)
                    .map(
                        clsName -> {
                          String content = getContentOrNull(clsName);
                          if (content != null) {
                            return PsiFileFactory.getInstance(fixture.getProject())
                                .createFileFromText(clsName, JavaFileType.INSTANCE, content);
                          }
                          return null;
                        })
                    .filter(PsiJavaFile.class::isInstance)
                    .map(PsiJavaFile.class::cast)
                    .map(PsiClassOwner::getClasses)
                    .filter(fileClasses -> fileClasses.length > 0)
                    .map(fileClasses -> fileClasses[0])
                    .collect(Collectors.toList());
            if (psiClasses.isEmpty()) {
              handler.apply(null);
            } else {
              handler.apply(psiClasses);
            }
          });
}
 
Example #25
Source File: AtMappingModel.java    From NutzCodeInsight with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
protected FileType filterValueFor(NavigationItem navigationItem) {
    return JavaFileType.INSTANCE;
}