@Nullable
 private String expandMacroSet(
     String str, boolean firstQueueExpand, DataContext dataContext, Iterator<Macro> macros)
     throws Macro.ExecutionCancelledException {
   if (str == null) return null;
   while (macros.hasNext()) {
     Macro macro = macros.next();
     if (macro instanceof SecondQueueExpandMacro && firstQueueExpand) continue;
     String name = "$" + macro.getName() + "$";
     String macroNameWithParamStart = "$" + macro.getName() + "(";
     if (str.contains(name)) {
       String expanded = macro.expand(dataContext);
       // if (dataContext instanceof DataManagerImpl.MyDataContext) {
       //  // hack: macro.expand() can cause UI events such as showing dialogs ('Prompt' macro)
       // which may 'invalidate' the datacontext
       //  // since we know exactly that context is valid, we need to update its event count
       //
       // ((DataManagerImpl.MyDataContext)dataContext).setEventCount(IdeEventQueue.getInstance().getEventCount());
       // }
       if (expanded == null) {
         expanded = "";
       }
       str = StringUtil.replace(str, name, expanded);
     } else if (str.contains(macroNameWithParamStart)) {
       String macroNameWithParamEnd = ")$";
       Map<String, String> toReplace = null;
       int i = str.indexOf(macroNameWithParamStart);
       while (i != -1) {
         int j = str.indexOf(macroNameWithParamEnd, i + macroNameWithParamStart.length());
         if (j > i) {
           String param = str.substring(i + macroNameWithParamStart.length(), j);
           if (toReplace == null) toReplace = new THashMap<String, String>();
           String expanded = macro.expand(dataContext, param);
           if (expanded == null) {
             expanded = "";
           }
           toReplace.put(macroNameWithParamStart + param + macroNameWithParamEnd, expanded);
           i = j + macroNameWithParamEnd.length();
         } else {
           break;
         }
       }
       if (toReplace != null) {
         for (Map.Entry<String, String> entry : toReplace.entrySet()) {
           str = StringUtil.replace(str, entry.getKey(), entry.getValue());
         }
       }
     }
   }
   return str;
 }
Exemplo n.º 2
0
  public static List<String> readInput(String filePath) {
    String content;
    try {
      content = StringUtil.convertLineSeparators(FileUtil.loadFile(new File(filePath)));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    Assert.assertNotNull(content);

    List<String> input = new ArrayList<String>();

    int separatorIndex;
    content = StringUtil.replace(content, "\r", ""); // for MACs

    // Adding input  before -----
    while ((separatorIndex = content.indexOf("-----")) >= 0) {
      input.add(content.substring(0, separatorIndex - 1));
      content = content.substring(separatorIndex);
      while (StringUtil.startsWithChar(content, '-')) {
        content = content.substring(1);
      }
      if (StringUtil.startsWithChar(content, '\n')) {
        content = content.substring(1);
      }
    }
    input.add(content);

    Assert.assertTrue("No data found in source file", input.size() > 0);
    Assert.assertNotNull("Test output points to null", input.size() > 1);

    return input;
  }
 public void addSparedChars(
     CompletionProgressIndicator indicator,
     LookupElement item,
     InsertionContext context,
     char completionChar) {
   String textInserted;
   if (context.getStartOffset() >= 0 && context.getTailOffset() >= context.getStartOffset()) {
     textInserted =
         context
             .getDocument()
             .getText()
             .substring(context.getStartOffset(), context.getTailOffset());
   } else {
     textInserted = item.getLookupString();
   }
   String withoutSpaces =
       StringUtil.replace(
           textInserted, new String[] {" ", "\t", "\n"}, new String[] {"", "", ""});
   int spared = withoutSpaces.length() - indicator.getLookup().itemPattern(item).length();
   if (!LookupEvent.isSpecialCompletionChar(completionChar)
       && withoutSpaces.contains(String.valueOf(completionChar))) {
     spared--;
   }
   if (spared > 0) {
     mySpared += spared;
   }
 }
 public static String applyMiddleMatching(String prefix) {
   if (Registry.is("ide.completion.middle.matching")
       && !prefix.isEmpty()
       && !ourForceStartMatching) {
     return "*" + StringUtil.replace(prefix, ".", ". ").trim();
   }
   return prefix;
 }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrClosableBlock block = expression.getClosureArguments()[0];
    final GrParameterList parameterList = block.getParameterList();
    final GrParameter[] parameters = parameterList.getParameters();

    String var;
    if (parameters.length == 1) {
      var = parameters[0].getText();
      var = StringUtil.replace(var, GrModifier.DEF, "");
    } else {
      var = "it";
    }

    final GrExpression invokedExpression = expression.getInvokedExpression();
    GrExpression qualifier = ((GrReferenceExpression) invokedExpression).getQualifierExpression();
    final GroovyPsiElementFactory elementFactory =
        GroovyPsiElementFactory.getInstance(element.getProject());
    if (qualifier == null) {
      qualifier = elementFactory.createExpressionFromText("this");
    }

    StringBuilder builder = new StringBuilder();
    builder.append("for (").append(var).append(" in ").append(qualifier.getText()).append(") {\n");
    String text = block.getText();
    final PsiElement blockArrow = block.getArrow();
    int index;
    if (blockArrow != null) {
      index = blockArrow.getStartOffsetInParent() + blockArrow.getTextLength();
    } else {
      index = 1;
    }
    while (index < text.length() && Character.isWhitespace(text.charAt(index))) index++;
    text = text.substring(index, text.length() - 1);
    builder.append(text);
    builder.append("}");

    final GrStatement statement = elementFactory.createStatementFromText(builder.toString());
    GrForStatement forStatement = (GrForStatement) expression.replaceWithStatement(statement);
    final GrForClause clause = forStatement.getClause();
    GrVariable variable = clause.getDeclaredVariable();

    forStatement = updateReturnStatements(forStatement);

    if (variable == null) return;

    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document doc = documentManager.getDocument(element.getContainingFile());
    if (doc == null) return;

    documentManager.doPostponedOperationsAndUnblockDocument(doc);
    editor.getCaretModel().moveToOffset(variable.getTextOffset());
    new VariableInplaceRenamer(variable, editor).performInplaceRename();
  }
 public String expandMacros(String text) {
   final Map<String, String> macroMap = getMacroMap();
   final Set<String> set = macroMap.keySet();
   for (final String from : set) {
     final String to = macroMap.get(from);
     text = StringUtil.replace(text, from, to, true);
   }
   return text;
 }
 public void appendLink(
     @NotNull final String fragment,
     @NotNull final SimpleTextAttributes attributes,
     @NotNull final String url) {
   if (fragment.length() > 0) {
     myText.append("<a href=\"").append(StringUtil.replace(url, "\"", "%22")).append("\" ");
     formatStyle(myText, attributes);
     myText.append('>').append(StringUtil.escapeXml(fragment)).append("</a>");
   }
 }
Exemplo n.º 8
0
 public String getToolTip() {
   String toolTip = this.toolTip;
   String description = this.description;
   if (toolTip == null || description == null || !toolTip.contains(DESCRIPTION_PLACEHOLDER))
     return toolTip;
   String decoded =
       StringUtil.replace(
           toolTip, DESCRIPTION_PLACEHOLDER, XmlStringUtil.escapeString(description));
   return XmlStringUtil.wrapInHtml(decoded);
 }
  protected DebuggerSession createRemoteProcess(
      final int transport, final boolean serverMode, JavaParameters javaParameters)
      throws ExecutionException, InterruptedException, InvocationTargetException {
    boolean useSockets = transport == DebuggerSettings.SOCKET_TRANSPORT;

    RemoteConnection remoteConnection =
        new RemoteConnection(useSockets, "127.0.0.1", String.valueOf(DEFAULT_ADDRESS), serverMode);

    String launchCommandLine = remoteConnection.getLaunchCommandLine();

    launchCommandLine = StringUtil.replace(launchCommandLine, RemoteConnection.ONTHROW, "");
    launchCommandLine = StringUtil.replace(launchCommandLine, RemoteConnection.ONUNCAUGHT, "");

    launchCommandLine = StringUtil.replace(launchCommandLine, "suspend=n", "suspend=y");

    println(launchCommandLine, ProcessOutputTypes.SYSTEM);

    for (StringTokenizer tokenizer = new StringTokenizer(launchCommandLine);
        tokenizer.hasMoreTokens(); ) {
      String token = tokenizer.nextToken();
      javaParameters.getVMParametersList().add(token);
    }

    GeneralCommandLine commandLine = CommandLineBuilder.createFromJavaParameters(javaParameters);

    DebuggerSession debuggerSession;

    if (serverMode) {
      debuggerSession = attachVM(remoteConnection, false);
      commandLine.createProcess();
    } else {
      commandLine.createProcess();
      debuggerSession = attachVM(remoteConnection, true);
    }

    ProcessHandler processHandler = debuggerSession.getProcess().getProcessHandler();
    DebugProcessImpl process =
        (DebugProcessImpl)
            DebuggerManagerEx.getInstanceEx(myProject).getDebugProcess(processHandler);

    assertNotNull(process);
    return debuggerSession;
  }
 static void formatLink(
     @NotNull StringBuilder builder,
     @NotNull String fragment,
     @NotNull SimpleTextAttributes attributes,
     @NotNull String url) {
   if (!fragment.isEmpty()) {
     builder.append("<a href=\"").append(StringUtil.replace(url, "\"", "%22")).append("\"");
     formatStyle(builder, attributes);
     builder.append('>').append(convertFragment(fragment)).append("</a>");
   }
 }
 @Override
 public void insertString(final int offset, @NotNull CharSequence s) {
   synchronized (myLock) {
     LOG.assertTrue(offset >= myShreds.get(0).getPrefix().length(), myShreds.get(0).getPrefix());
     LOG.assertTrue(
         offset <= getTextLength() - myShreds.get(myShreds.size() - 1).getSuffix().length(),
         myShreds.get(myShreds.size() - 1).getSuffix());
   }
   if (isOneLine()) {
     s = StringUtil.replace(s.toString(), "\n", "");
   }
   myDelegate.insertString(injectedToHost(offset), s);
 }
  private static String getTokenText(Lexer lexer) {
    final IElementType tokenType = lexer.getTokenType();
    if (tokenType instanceof TokenWrapper) {
      return ((TokenWrapper) tokenType).getValue();
    }

    String text =
        lexer
            .getBufferSequence()
            .subSequence(lexer.getTokenStart(), lexer.getTokenEnd())
            .toString();
    text = StringUtil.replace(text, "\n", "\\n");
    return text;
  }
Exemplo n.º 13
0
  private static String encodeTooltip(String toolTip, String description) {
    if (toolTip == null || description == null) return toolTip;
    String unescaped = StringUtil.unescapeXml(XmlStringUtil.stripHtml(toolTip));

    String encoded =
        description.isEmpty()
            ? unescaped
            : StringUtil.replace(unescaped, description, DESCRIPTION_PLACEHOLDER);
    //noinspection StringEquality
    if (encoded == unescaped) {
      return toolTip;
    }
    if (encoded.equals(DESCRIPTION_PLACEHOLDER)) encoded = DESCRIPTION_PLACEHOLDER;
    return encoded;
  }
  @Nullable
  static IdeaPluginDescriptorImpl loadDescriptorFromJar(File file, @NonNls String fileName) {
    try {
      URI fileURL = file.toURI();
      URL jarURL =
          new URL(
              "jar:"
                  + StringUtil.replace(fileURL.toASCIIString(), "!", "%21")
                  + "!/META-INF/"
                  + fileName);

      IdeaPluginDescriptorImpl descriptor = new IdeaPluginDescriptorImpl(file);
      FileInputStream in = new FileInputStream(file);
      ZipInputStream zipStream = new ZipInputStream(in);
      try {
        ZipEntry entry = zipStream.getNextEntry();
        if (entry.getName().equals(JarMemoryLoader.SIZE_ENTRY)) {
          entry = zipStream.getNextEntry();
          if (entry.getName().equals("META-INF/" + fileName)) {
            byte[] content = FileUtil.loadBytes(zipStream, (int) entry.getSize());
            Document document = JDOMUtil.loadDocument(new ByteArrayInputStream(content));
            descriptor.readExternal(document, jarURL);
            return descriptor;
          }
        }
      } finally {
        zipStream.close();
        in.close();
      }

      descriptor.readExternal(jarURL);
      return descriptor;
    } catch (XmlSerializationException e) {
      getLogger().info("Cannot load " + file, e);
      prepareLoadingPluginsErrorMessage(
          "Plugin file " + file.getName() + " contains invalid plugin descriptor file.");
    } catch (FileNotFoundException e) {
      return null;
    } catch (Exception e) {
      getLogger().info("Cannot load " + file, e);
    } catch (Throwable e) {
      getLogger().info("Cannot load " + file, e);
    }

    return null;
  }
Exemplo n.º 15
0
  public String substitute(String text, boolean caseSensitive) {
    if (text == null) {
      //noinspection ConstantConditions
      return null;
    }

    for (Map.Entry<String, String> entry : myPlainMap.entrySet()) {
      // when replacing macros with actual paths the replace utility may be used as always
      // 'case-sensitive'
      // for case-insensitive file systems there will be no unnecessary toLowerCase() transforms.
      text = StringUtil.replace(text, entry.getKey(), entry.getValue(), false);
    }

    for (Map.Entry<String, String> entry : myMacroExpands.entrySet()) {
      text = replaceMacro(text, entry.getKey(), entry.getValue());
    }

    return text;
  }
 private RemoveInvalidElementsDialog(
     final String title,
     ConfigurationErrorType type,
     String invalidElements,
     final Project project,
     List<ConfigurationErrorDescription> errors) {
   super(project, true);
   setTitle(title);
   myDescriptionLabel.setText(
       ProjectBundle.message(
           type.canIgnore()
               ? "label.text.0.cannot.be.loaded.ignore"
               : "label.text.0.cannot.be.loaded.remove",
           invalidElements));
   myContentPanel.setLayout(new VerticalFlowLayout());
   for (ConfigurationErrorDescription error : errors) {
     JCheckBox checkBox = new JCheckBox(error.getElementName() + ".");
     checkBox.setSelected(true);
     myCheckboxes.put(checkBox, error);
     JPanel panel = new JPanel(new GridBagLayout());
     GridBagConstraints constraints = new GridBagConstraints();
     constraints.anchor = GridBagConstraints.NORTHWEST;
     constraints.ipadx = 5;
     panel.add(checkBox, constraints);
     constraints.anchor = GridBagConstraints.NORTHWEST;
     constraints.insets.top = 5;
     panel.add(
         new JLabel(
             "<html><body>"
                 + StringUtil.replace(error.getDescription(), "\n", "<br>")
                 + "</body></html>"),
         constraints);
     constraints.weightx = 1;
     panel.add(new JPanel(), constraints);
     myContentPanel.add(panel);
   }
   init();
   setOKButtonText(
       ProjectBundle.message(
           type.canIgnore() ? "button.text.ignore.selected" : "button.text.remove.selected"));
   setCancelButtonText(ProjectBundle.message("button.text.keep.all"));
 }
  @Override
  public void replaceString(int startOffset, int endOffset, @NotNull CharSequence s) {
    if (isOneLine()) {
      s = StringUtil.replace(s.toString(), "\n", "");
    }

    final CharSequence chars = getCharsSequence();
    CharSequence toDelete = chars.subSequence(startOffset, endOffset);

    int perfixLength = StringUtil.commonPrefixLength(s, toDelete);
    int suffixLength =
        StringUtil.commonSuffixLength(
            toDelete.subSequence(perfixLength, toDelete.length()),
            s.subSequence(perfixLength, s.length()));
    startOffset += perfixLength;
    endOffset -= suffixLength;
    s = s.subSequence(perfixLength, s.length() - suffixLength);

    doReplaceString(startOffset, endOffset, s);
  }
 @Override
 public void setText(@NotNull CharSequence text) {
   synchronized (myLock) {
     LOG.assertTrue(text.toString().startsWith(myShreds.get(0).getPrefix()));
     LOG.assertTrue(text.toString().endsWith(myShreds.get(myShreds.size() - 1).getSuffix()));
     if (isOneLine()) {
       text = StringUtil.replace(text.toString(), "\n", "");
     }
     String[] changes = calculateMinEditSequence(text.toString());
     assert changes.length == myShreds.size();
     for (int i = 0; i < changes.length; i++) {
       String change = changes[i];
       if (change != null) {
         Segment hostRange = myShreds.get(i).getHostRangeMarker();
         if (hostRange == null) continue;
         myDelegate.replaceString(hostRange.getStartOffset(), hostRange.getEndOffset(), change);
       }
     }
   }
 }
  // please keep an implementation in sync with [junit-rt] ProcessBuilder.createProcess()
  @NotNull
  public static List<String> toCommandLine(
      @NotNull String command, @NotNull List<String> parameters, @NotNull Platform platform) {
    List<String> commandLine = ContainerUtil.newArrayListWithExpectedSize(parameters.size() + 1);

    commandLine.add(FileUtilRt.toSystemDependentName(command, platform.fileSeparator));

    boolean isWindows = platform == Platform.WINDOWS;
    boolean winShell =
        isWindows
            && ("cmd".equalsIgnoreCase(command) || "cmd.exe".equalsIgnoreCase(command))
            && parameters.size() > 1
            && "/c".equalsIgnoreCase(parameters.get(0));

    for (String parameter : parameters) {
      if (isWindows) {
        if (parameter.contains("\"")) {
          parameter = StringUtil.replace(parameter, "\"", "\\\"");
        } else if (parameter.isEmpty()) {
          parameter = "\"\"";
        }
      }

      if (winShell && StringUtil.containsAnyChar(parameter, WIN_SHELL_SPECIALS)) {
        parameter = quote(parameter, SPECIAL_QUOTE);
      }

      if (isQuoted(parameter, SPECIAL_QUOTE)) {
        parameter = quote(parameter.substring(1, parameter.length() - 1), '"');
      }

      commandLine.add(parameter);
    }

    return commandLine;
  }
Exemplo n.º 20
0
 private static File getArtifactDirectory(
     File localRepository, String groupId, String artifactId) {
   String relativePath =
       StringUtil.replace(groupId, ".", File.separator) + File.separator + artifactId;
   return new File(localRepository, relativePath);
 }
 @SuppressWarnings("deprecation")
 private static String decodeUrl(String file) {
   String quotePluses = StringUtil.replace(file, "+", "%2B");
   return URLDecoder.decode(quotePluses);
 }
Exemplo n.º 22
0
 private static String decodeSpecialNames(String str) {
   String decodedObjectNames =
       StringUtil.replace(str, CLASS_OBJECT_REPLACE_GUARD, JvmAbi.CLASS_OBJECT_CLASS_NAME);
   return StringUtil.replace(
       decodedObjectNames, TRAIT_IMPL_REPLACE_GUARD, JvmAbi.TRAIT_IMPL_CLASS_NAME);
 }
  public ChooseResourceDialog(
      @NotNull Module module,
      @NotNull ResourceType[] types,
      @Nullable String value,
      @Nullable XmlTag tag,
      ResourceNameVisibility resourceNameVisibility,
      @Nullable String colorName) {
    super(module.getProject());
    myModule = module;
    myTag = tag;
    myResourceNameVisibility = resourceNameVisibility;

    setTitle("Resources");

    AndroidFacet facet = AndroidFacet.getInstance(module);
    myProjectPanel = new ResourcePanel(facet, types, false);
    mySystemPanel = new ResourcePanel(facet, types, true);

    myContentPanel = new JBTabbedPane();
    myContentPanel.addTab("Project", myProjectPanel.myComponent);
    myContentPanel.addTab("System", mySystemPanel.myComponent);

    myProjectPanel.myTreeBuilder.expandAll(null);
    mySystemPanel.myTreeBuilder.expandAll(null);

    boolean doSelection = value != null;

    if (types == COLOR_TYPES) {
      Color color = ResourceHelper.parseColor(value);
      myColorPicker =
          new ColorPicker(
              myDisposable,
              color,
              true,
              new ColorPickerListener() {
                @Override
                public void colorChanged(Color color) {
                  notifyResourcePickerListeners(ResourceHelper.colorToString(color));
                }

                @Override
                public void closed(@Nullable Color color) {}
              });
      myColorPicker.pickARGB();

      JPanel colorPickerContent = new JPanel(new BorderLayout());
      myColorPickerPanel = new JBScrollPane(colorPickerContent);
      myColorPickerPanel.setBorder(null);
      colorPickerContent.add(myColorPicker);
      myContentPanel.addTab("Color", myColorPickerPanel);

      if (myResourceNameVisibility != ResourceNameVisibility.HIDE) {
        ResourceDialogSouthPanel resourceDialogSouthPanel = new ResourceDialogSouthPanel();
        myResourceNameField = resourceDialogSouthPanel.getResourceNameField();
        myResourceNameField.getDocument().addDocumentListener(new ValidatingDocumentListener());
        if (colorName != null) {
          myResourceNameField.setText(colorName);
        }
        myResourceNameMessage = resourceDialogSouthPanel.getResourceNameMessage();
        Color backgroundColor =
            EditorColorsManager.getInstance()
                .getGlobalScheme()
                .getColor(EditorColors.NOTIFICATION_BACKGROUND);
        myResourceNameMessage.setBackground(
            backgroundColor == null ? JBColor.YELLOW : backgroundColor);
        colorPickerContent.add(resourceDialogSouthPanel.getFullPanel(), BorderLayout.SOUTH);
        updateResourceNameStatus();
      }

      if (color != null) {
        myContentPanel.setSelectedIndex(2);
        doSelection = false;
      }
      myValidator =
          ResourceNameValidator.create(
              false,
              AppResourceRepository.getAppResources(module, true),
              ResourceType.COLOR,
              false);
    }
    if (doSelection && value.startsWith("@")) {
      value = StringUtil.replace(value, "+", "");
      int index = value.indexOf('/');
      if (index != -1) {
        ResourcePanel panel;
        String type;
        String name = value.substring(index + 1);
        if (value.startsWith(ANDROID)) {
          panel = mySystemPanel;
          type = value.substring(ANDROID.length(), index);
        } else {
          panel = myProjectPanel;
          type = value.substring(1, index);
        }
        myContentPanel.setSelectedComponent(panel.myComponent);
        panel.select(type, name);
      }
    }

    myContentPanel.addChangeListener(
        new ChangeListener() {
          @Override
          public void stateChanged(ChangeEvent e) {
            valueChanged(null);
          }
        });

    valueChanged(null);
    init();
  }
  @NotNull
  private static UsageViewPresentation createPresentation(
      @NotNull UsageViewDescriptor descriptor, @NotNull Usage[] usages) {
    UsageViewPresentation presentation = new UsageViewPresentation();
    presentation.setTabText(RefactoringBundle.message("usageView.tabText"));
    presentation.setTargetsNodeText(descriptor.getProcessedElementsHeader());
    presentation.setShowReadOnlyStatusAsRed(true);
    presentation.setShowCancelButton(true);
    presentation.setUsagesString(RefactoringBundle.message("usageView.usagesText"));
    int codeUsageCount = 0;
    int nonCodeUsageCount = 0;
    int dynamicUsagesCount = 0;
    Set<PsiFile> codeFiles = new HashSet<>();
    Set<PsiFile> nonCodeFiles = new HashSet<>();
    Set<PsiFile> dynamicUsagesCodeFiles = new HashSet<>();

    for (Usage usage : usages) {
      if (usage instanceof PsiElementUsage) {
        final PsiElementUsage elementUsage = (PsiElementUsage) usage;
        final PsiElement element = elementUsage.getElement();
        if (element == null) continue;
        final PsiFile containingFile = element.getContainingFile();
        if (elementUsage.isNonCodeUsage()) {
          nonCodeUsageCount++;
          nonCodeFiles.add(containingFile);
        } else {
          codeUsageCount++;
          codeFiles.add(containingFile);
        }
        if (usage instanceof UsageInfo2UsageAdapter) {
          final UsageInfo usageInfo = ((UsageInfo2UsageAdapter) usage).getUsageInfo();
          if (usageInfo instanceof MoveRenameUsageInfo && usageInfo.isDynamicUsage()) {
            dynamicUsagesCount++;
            dynamicUsagesCodeFiles.add(containingFile);
          }
        }
      }
    }
    codeFiles.remove(null);
    nonCodeFiles.remove(null);
    dynamicUsagesCodeFiles.remove(null);

    String codeReferencesText = descriptor.getCodeReferencesText(codeUsageCount, codeFiles.size());
    presentation.setCodeUsagesString(codeReferencesText);
    final String commentReferencesText =
        descriptor.getCommentReferencesText(nonCodeUsageCount, nonCodeFiles.size());
    if (commentReferencesText != null) {
      presentation.setNonCodeUsagesString(commentReferencesText);
    }
    presentation.setDynamicUsagesString(
        "Dynamic "
            + StringUtil.decapitalize(
                descriptor.getCodeReferencesText(
                    dynamicUsagesCount, dynamicUsagesCodeFiles.size())));
    String generatedCodeString;
    if (codeReferencesText.contains("in code")) {
      generatedCodeString = StringUtil.replace(codeReferencesText, "in code", "in generated code");
    } else {
      generatedCodeString = codeReferencesText + " in generated code";
    }
    presentation.setUsagesInGeneratedCodeString(generatedCodeString);
    return presentation;
  }
  private void exportResults(
      @NotNull final CommonProblemDescriptor[] descriptors,
      @NotNull RefEntity refEntity,
      @NotNull Element parentNode) {
    for (CommonProblemDescriptor descriptor : descriptors) {
      @NonNls final String template = descriptor.getDescriptionTemplate();
      int line =
          descriptor instanceof ProblemDescriptor
              ? ((ProblemDescriptor) descriptor).getLineNumber()
              : -1;
      final PsiElement psiElement =
          descriptor instanceof ProblemDescriptor
              ? ((ProblemDescriptor) descriptor).getPsiElement()
              : null;
      @NonNls
      String problemText =
          StringUtil.replace(
              StringUtil.replace(
                  template,
                  "#ref",
                  psiElement != null
                      ? ProblemDescriptorUtil.extractHighlightedText(descriptor, psiElement)
                      : ""),
              " #loc ",
              " ");

      Element element = refEntity.getRefManager().export(refEntity, parentNode, line);
      if (element == null) return;
      @NonNls
      Element problemClassElement =
          new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag"));
      problemClassElement.addContent(myToolWrapper.getDisplayName());

      final HighlightSeverity severity;
      if (refEntity instanceof RefElement) {
        final RefElement refElement = (RefElement) refEntity;
        severity = getSeverity(refElement);
      } else {
        final InspectionProfile profile =
            InspectionProjectProfileManager.getInstance(getContext().getProject())
                .getInspectionProfile();
        final HighlightDisplayLevel level =
            profile.getErrorLevel(
                HighlightDisplayKey.find(myToolWrapper.getShortName()), psiElement);
        severity = level.getSeverity();
      }

      if (severity != null) {
        ProblemHighlightType problemHighlightType =
            descriptor instanceof ProblemDescriptor
                ? ((ProblemDescriptor) descriptor).getHighlightType()
                : ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
        final String attributeKey =
            getTextAttributeKey(getRefManager().getProject(), severity, problemHighlightType);
        problemClassElement.setAttribute("severity", severity.myName);
        problemClassElement.setAttribute("attribute_key", attributeKey);
      }

      element.addContent(problemClassElement);
      if (myToolWrapper instanceof GlobalInspectionToolWrapper) {
        final GlobalInspectionTool globalInspectionTool =
            ((GlobalInspectionToolWrapper) myToolWrapper).getTool();
        final QuickFix[] fixes = descriptor.getFixes();
        if (fixes != null) {
          @NonNls Element hintsElement = new Element("hints");
          for (QuickFix fix : fixes) {
            final String hint = globalInspectionTool.getHint(fix);
            if (hint != null) {
              @NonNls Element hintElement = new Element("hint");
              hintElement.setAttribute("value", hint);
              hintsElement.addContent(hintElement);
            }
          }
          element.addContent(hintsElement);
        }
      }
      try {
        Element descriptionElement =
            new Element(InspectionsBundle.message("inspection.export.results.description.tag"));
        descriptionElement.addContent(problemText);
        element.addContent(descriptionElement);
      } catch (IllegalDataException e) {
        //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr
        System.out.println(
            "Cannot save results for "
                + refEntity.getName()
                + ", inspection which caused problem: "
                + myToolWrapper.getShortName());
      }
    }
  }