@WrapInCommand
  public void testReimportConflictingClasses() throws Exception {
    configureByFile(BASE_PATH + "/x/Usage.java", BASE_PATH);
    assertEmpty(highlightErrors());

    CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).clone();
    settings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 2;
    CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(settings);
    try {
      new WriteCommandAction.Simple(getProject()) {
        @Override
        protected void run() throws Throwable {
          JavaCodeStyleManager.getInstance(getProject()).optimizeImports(getFile());
        }
      }.execute().throwException();
    } finally {
      CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings();
    }

    @NonNls String fullPath = getTestDataPath() + BASE_PATH + "/x/Usage_afterOptimize.txt";
    final VirtualFile vFile =
        LocalFileSystem.getInstance().findFileByPath(fullPath.replace(File.separatorChar, '/'));
    String text = LoadTextUtil.loadText(vFile).toString();
    assertEquals(text, getFile().getText());
  }
  @Nullable
  public ProblemDescriptor[] checkFile(
      @NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file))
      return null;
    if (ArrayUtil.find(file.getPsiRoots(), file) != 0) return null;
    if (!file.isPhysical()) return null;
    VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return null;
    if (virtualFile.getFileSystem() != LocalFileSystem.getInstance()
        // tests
        && virtualFile.getFileSystem() != TempFileSystem.getInstance()) return null;
    String text = file.getText();
    Charset charset =
        LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);

    // no sense in checking transparently decoded file: all characters there are already safely
    // encoded
    if (charset instanceof Native2AsciiCharset) return null;

    List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>();
    checkIfCharactersWillBeLostAfterSave(file, manager, isOnTheFly, text, charset, descriptors);
    checkFileLoadedInWrongEncoding(file, manager, isOnTheFly, virtualFile, charset, descriptors);

    return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
  }
 @Nullable
 public String convert(final VirtualFilePointer pointer) {
   if (pointer == null) return null;
   final String path = pointer.getPresentableUrl();
   final ByteContent byteContent =
       myLabel.getByteContent(FileUtil.toSystemIndependentName(path));
   if (byteContent == null || byteContent.isDirectory() || byteContent.getBytes() == null) {
     return null;
   }
   final VirtualFile vf = pointer.getFile();
   if (vf == null) {
     return LoadTextUtil.getTextByBinaryPresentation(
             byteContent.getBytes(), EncodingManager.getInstance().getDefaultCharset())
         .toString();
   } else {
     return LoadTextUtil.getTextByBinaryPresentation(byteContent.getBytes(), vf).toString();
   }
 }
  public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore)
      throws IOException {
    try {
      assertJarFilesEqual(
          VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore));
    } catch (IOException e) {
      FileDocumentManager manager = FileDocumentManager.getInstance();

      Document docBefore = manager.getDocument(fileBefore);
      boolean canLoadBeforeText =
          !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
      String textB =
          docBefore != null
              ? docBefore.getText()
              : !canLoadBeforeText
                  ? null
                  : LoadTextUtil.getTextByBinaryPresentation(
                          fileBefore.contentsToByteArray(false), fileBefore)
                      .toString();

      Document docAfter = manager.getDocument(fileAfter);
      boolean canLoadAfterText =
          !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN;
      String textA =
          docAfter != null
              ? docAfter.getText()
              : !canLoadAfterText
                  ? null
                  : LoadTextUtil.getTextByBinaryPresentation(
                          fileAfter.contentsToByteArray(false), fileAfter)
                      .toString();

      if (textA != null && textB != null) {
        assertEquals(fileAfter.getPath(), textA, textB);
      } else {
        Assert.assertArrayEquals(
            fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray());
      }
    }
  }
    @Override
    public CharSequence getText() {
      final VirtualFile virtualFile = getVirtualFile();
      if (virtualFile instanceof LightVirtualFile) {
        Document doc = getCachedDocument();
        if (doc != null) return doc.getCharsSequence();
        return ((LightVirtualFile) virtualFile).getContent();
      }

      final Document document = getDocument();
      if (document == null) {
        return LoadTextUtil.loadText(virtualFile);
      } else {
        return document.getCharsSequence();
      }
    }
 @NotNull
 @Override
 public CharSequence getContentAsText() {
   if (myFileType.isBinary()) {
     throw new IllegalDataException(
         "Cannot obtain text for binary file type : " + myFileType.getDescription());
   }
   final CharSequence content = getUserData(IndexingDataKeys.FILE_TEXT_CONTENT_KEY);
   if (content != null) {
     return content;
   }
   if (myContentAsText == null) {
     if (myContent != null) {
       myContentAsText = LoadTextUtil.getTextByBinaryPresentation(myContent, myCharset);
       myContent = null; // help gc, indices are expected to use bytes or chars but not both
     }
   }
   return myContentAsText;
 }
  @Override
  public void actionPerformed(AnActionEvent event) {
    final Project project = event.getData(CommonDataKeys.PROJECT);

    LOG.assertTrue(project != null);

    final FileChooserDescriptor descriptor =
        new FileChooserDescriptor(false, true, false, false, false, false) {
          @Override
          public Icon getIcon(VirtualFile file) {
            if (file.isDirectory()) {
              if (file.findChild(
                      InspectionApplication.DESCRIPTIONS
                          + "."
                          + StdFileTypes.XML.getDefaultExtension())
                  != null) {
                return AllIcons.Nodes.InspectionResults;
              }
            }
            return super.getIcon(file);
          }
        };
    descriptor.setTitle("Select Path");
    descriptor.setDescription("Select directory which contains exported inspections results");
    final VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
    if (virtualFile == null || !virtualFile.isDirectory()) return;

    final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap = new HashMap<>();
    final String[] profileName = new String[1];
    final Runnable process =
        () -> {
          final VirtualFile[] files = virtualFile.getChildren();
          try {
            for (final VirtualFile inspectionFile : files) {
              if (inspectionFile.isDirectory()) continue;
              final String shortName = inspectionFile.getNameWithoutExtension();
              final String extension = inspectionFile.getExtension();
              if (shortName.equals(InspectionApplication.DESCRIPTIONS)) {
                profileName[0] =
                    ApplicationManager.getApplication()
                        .runReadAction(
                            (Computable<String>)
                                () ->
                                    OfflineViewParseUtil.parseProfileName(
                                        LoadTextUtil.loadText(inspectionFile).toString()));
              } else if (XML_EXTENSION.equals(extension)) {
                resMap.put(
                    shortName,
                    ApplicationManager.getApplication()
                        .runReadAction(
                            new Computable<Map<String, Set<OfflineProblemDescriptor>>>() {
                              @Override
                              public Map<String, Set<OfflineProblemDescriptor>> compute() {
                                return OfflineViewParseUtil.parse(
                                    LoadTextUtil.loadText(inspectionFile).toString());
                              }
                            }));
              }
            }
          } catch (final Exception e) { // all parse exceptions
            SwingUtilities.invokeLater(
                () ->
                    Messages.showInfoMessage(
                        e.getMessage(),
                        InspectionsBundle.message("offline.view.parse.exception.title")));
            throw new ProcessCanceledException(); // cancel process
          }
        };
    ProgressManager.getInstance()
        .runProcessWithProgressAsynchronously(
            project,
            InspectionsBundle.message("parsing.inspections.dump.progress.title"),
            process,
            () ->
                SwingUtilities.invokeLater(
                    () -> {
                      final String name = profileName[0];
                      showOfflineView(
                          project,
                          name,
                          resMap,
                          InspectionsBundle.message("offline.view.title")
                              + " ("
                              + (name != null
                                  ? name
                                  : InspectionsBundle.message("offline.view.editor.settings.title"))
                              + ")");
                    }),
            null,
            new PerformAnalysisInBackgroundOption(project));
  }
 public static PatchReader create(final VirtualFile virtualFile) throws IOException {
   final byte[] patchContents = virtualFile.contentsToByteArray();
   final CharSequence patchText =
       LoadTextUtil.getTextByBinaryPresentation(patchContents, virtualFile);
   return new PatchReader(patchText);
 }
 @NotNull
 private static String[] getCoveredLines(@NotNull byte[] oldContent, VirtualFile vFile) {
   final String text =
       LoadTextUtil.getTextByBinaryPresentation(oldContent, vFile, false, false).toString();
   return LineTokenizer.tokenize(text, false);
 }
 public FileContentImpl(@NotNull final VirtualFile file, @NotNull final byte[] content) {
   this(file, null, content, LoadTextUtil.detectCharsetAndSetBOM(file, content), -1);
 }
예제 #11
0
  private void update() {
    if (update.isDisposed()) return;

    update.cancelAllRequests();
    update.addRequest(
        () -> {
          if (isDisposed()) return;

          VirtualFile file = getSelectedFile();
          actionEnabled = false;
          String charsetName = null;
          Pair<Charset, String> check = null;

          if (file != null) {
            check = EncodingUtil.checkSomeActionEnabled(file);
            Charset charset = null;

            if (LoadTextUtil.wasCharsetDetectedFromBytes(file) != null) {
              charset = cachedCharsetFromContent(file);
            }

            if (charset == null) {
              charset = file.getCharset();
            }

            actionEnabled = check == null || check.second == null;

            if (!actionEnabled) {
              charset = check.first;
            }

            if (charset != null) {
              charsetName = charset.displayName();
            }
          }

          if (charsetName == null) {
            charsetName = "n/a";
          }

          String toolTipText;

          if (actionEnabled) {
            toolTipText = String.format("File Encoding%n%s", charsetName);

            myComponent.setForeground(UIUtil.getActiveTextColor());
            myComponent.setTextAlignment(Component.LEFT_ALIGNMENT);
          } else {
            String failReason = check == null ? "" : check.second;
            toolTipText = String.format("File encoding is disabled%n%s", failReason);

            myComponent.setForeground(UIUtil.getInactiveTextColor());
            myComponent.setTextAlignment(Component.CENTER_ALIGNMENT);
          }

          myComponent.setToolTipText(toolTipText);
          myComponent.setText(charsetName);

          if (myStatusBar != null) {
            myStatusBar.updateWidget(ID());
          }
        },
        200,
        ModalityState.any());
  }
 @Override
 public void visitFile(PsiFile file) {
   super.visitFile(file);
   if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)
       || !file.isPhysical()) {
     return;
   }
   final VirtualFile virtualFile = file.getVirtualFile();
   final String text = file.getText();
   final Charset charset =
       LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);
   final CharsetEncoder encoder =
       charset.newEncoder().onUnmappableCharacter(CodingErrorAction.REPORT);
   final CharBuffer charBuffer = CharBuffer.allocate(1);
   final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
   final int length = text.length();
   for (int i = 0; i < length; i++) {
     final char c = text.charAt(i);
     if (c != '\\') {
       continue;
     }
     boolean isEscape = true;
     int previousChar = i - 1;
     while (previousChar >= 0 && text.charAt(previousChar) == '\\') {
       isEscape = !isEscape;
       previousChar--;
     }
     if (!isEscape) {
       continue;
     }
     int nextChar = i;
     do {
       nextChar++;
       if (nextChar >= length) {
         break;
       }
     } while (text.charAt(nextChar) == 'u'); // \uuuu0061 is a legal unicode escape
     if (nextChar == i + 1 || nextChar + 3 >= length) {
       continue;
     }
     if (StringUtil.isHexDigit(text.charAt(nextChar))
         && StringUtil.isHexDigit(text.charAt(nextChar + 1))
         && StringUtil.isHexDigit(text.charAt(nextChar + 2))
         && StringUtil.isHexDigit(text.charAt(nextChar + 3))) {
       final int escapeEnd = nextChar + 4;
       final char d = (char) Integer.parseInt(text.substring(nextChar, escapeEnd), 16);
       if (Character.isISOControl(d)) {
         continue;
       }
       byteBuffer.clear();
       charBuffer.clear();
       charBuffer.put(d).rewind();
       final CoderResult coderResult = encoder.encode(charBuffer, byteBuffer, true);
       if (!coderResult.isUnmappable()) {
         final PsiElement element = file.findElementAt(i);
         if (element != null && isSuppressedFor(element)) {
           return;
         }
         registerErrorAtOffset(file, i, escapeEnd - i, Character.valueOf(d));
       }
     }
   }
 }