@Override
  public boolean accept(@NotNull HighlightInfo highlightInfo, @Nullable PsiFile file) {
    if (null != file && HighlightSeverity.ERROR.equals(highlightInfo.getSeverity())) {
      final String description = StringUtil.notNullize(highlightInfo.getDescription());

      if (HighlightInfoType.UNHANDLED_EXCEPTION.equals(highlightInfo.type)
          && (StringUtil.startsWith(description, UNHANDLED_EXCEPTION_PREFIX_TEXT)
              || StringUtil.startsWith(description, UNHANDLED_EXCEPTIONS_PREFIX_TEXT)
              || StringUtil.startsWith(
                  description, UNHANDLED_AUTOCLOSABLE_EXCEPTIONS_PREFIX_TEXT))) {
        final String unhandledExceptions =
            description.substring(description.indexOf(':') + 1).trim();
        final String[] exceptionFQNs = unhandledExceptions.split(",");
        if (exceptionFQNs.length > 0) {
          final PsiMethod psiMethod =
              PsiTreeUtil.getParentOfType(
                  file.findElementAt(highlightInfo.getStartOffset()), PsiMethod.class);
          if (null != psiMethod) {
            return !SneakyTrowsExceptionHandler.isExceptionHandled(psiMethod, exceptionFQNs);
          }
        }
      }
    }
    return true;
  }
  @NotNull
  private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) {
    final String userDefined = System.getProperty("gradle.launcher.class");
    if (StringUtil.isNotEmpty(userDefined)) {
      return userDefined;
    }

    VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle");
    if (launcher == null) {
      launcher = gradleHome.findFileByRelativePath("bin/gradle.bat");
    }
    if (launcher != null) {
      try {
        final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher));
        final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text);
        if (matcher.find()) {
          String candidate = matcher.group(1);
          if (StringUtil.isNotEmpty(candidate)) {
            return candidate;
          }
        }
      } catch (IOException ignored) {
      }
    }

    final PsiFile grFile = PsiManager.getInstance(project).findFile(script);
    if (grFile != null
        && JavaPsiFacade.getInstance(project)
                .findClass("org.gradle.BootstrapMain", grFile.getResolveScope())
            != null) {
      return "org.gradle.BootstrapMain";
    }

    return "org.gradle.launcher.GradleMain";
  }
 public static void notifyMessages(
     Project project,
     @Nullable String title,
     @Nullable String description,
     NotificationType type,
     boolean important,
     @Nullable Collection<String> messages) {
   if (title == null) {
     title = "";
   }
   String desc = (description != null ? description.replace("\n", "<br/>") : "");
   if (messages != null && !messages.isEmpty()) {
     desc += "<hr/>" + StringUtil.join(messages, "<br/>");
   }
   if (StringUtil.isEmptyOrSpaces(desc)) {
     desc =
         StringUtil.isEmptyOrSpaces(title)
             ? "Error"
             : title; // description is not allowed to be empty, title is => moving title text to
                      // description
     title = "";
   }
   NotificationGroup group =
       important ? GitVcs.IMPORTANT_ERROR_NOTIFICATION : GitVcs.NOTIFICATION_GROUP_ID;
   group.createNotification(title, desc, type, null).notify(project.isDefault() ? null : project);
 }
 @Nullable
 public static SemVer parseFromText(@NotNull String text) {
   int majorEndInd = text.indexOf('.');
   if (majorEndInd < 0) {
     return null;
   }
   int major = StringUtil.parseInt(text.substring(0, majorEndInd), -1);
   int minorEndInd = text.indexOf('.', majorEndInd + 1);
   if (minorEndInd < 0) {
     return null;
   }
   int minor = StringUtil.parseInt(text.substring(majorEndInd + 1, minorEndInd), -1);
   final String patchStr;
   int dashInd = text.indexOf('-', minorEndInd + 1);
   if (dashInd >= 0) {
     patchStr = text.substring(minorEndInd + 1, dashInd);
   } else {
     patchStr = text.substring(minorEndInd + 1);
   }
   int patch = StringUtil.parseInt(patchStr, -1);
   if (major >= 0 && minor >= 0 && patch >= 0) {
     return new SemVer(text, major, minor, patch);
   }
   return null;
 }
  @NotNull
  private static Pair<VcsLogTextFilter, VcsLogHashFilter> getFiltersFromTextArea(
      @Nullable VcsLogTextFilter filter) {
    if (filter == null) {
      return Pair.empty();
    }
    String text = filter.getText().trim();
    if (StringUtil.isEmptyOrSpaces(text)) {
      return Pair.empty();
    }
    List<String> hashes = ContainerUtil.newArrayList();
    for (String word : StringUtil.split(text, " ")) {
      if (!StringUtil.isEmptyOrSpaces(word) && word.matches(HASH_PATTERN)) {
        hashes.add(word);
      } else {
        break;
      }
    }

    VcsLogTextFilter textFilter;
    VcsLogHashFilterImpl hashFilter;
    if (!hashes.isEmpty()) { // text is ignored if there are hashes in the text
      textFilter = null;
      hashFilter = new VcsLogHashFilterImpl(hashes);
    } else {
      textFilter = new VcsLogTextFilterImpl(text);
      hashFilter = null;
    }
    return Pair.<VcsLogTextFilter, VcsLogHashFilter>create(textFilter, hashFilter);
  }
  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 Notification(
      @NotNull String groupDisplayId,
      @NotNull Icon icon,
      @Nullable String title,
      @Nullable String subtitle,
      @Nullable String content,
      @NotNull NotificationType type,
      @Nullable NotificationListener listener) {
    myGroupId = groupDisplayId;
    myTitle = StringUtil.notNullize(title);
    myContent = StringUtil.notNullize(content);
    myType = type;
    myListener = listener;
    myTimestamp = System.currentTimeMillis();

    myIcon = icon;
    mySubtitle = subtitle;

    LOG.assertTrue(
        isTitle() || isContent(),
        "Notification should have title: "
            + title
            + " and/or subtitle and/or content groupId: "
            + myGroupId);

    id =
        String.valueOf(System.currentTimeMillis())
            + "."
            + String.valueOf(System.identityHashCode(this));
  }
  private void onStateChangedToSuccess(final AuthenticationRequest obj) {
    myCopiesPassiveResults.put(getKey(obj), true);
    myVcs.invokeRefreshSvnRoots(false);

    final List<SVNURL> outdatedRequests = new LinkedList<SVNURL>();
    final Collection<SVNURL> keys = getAllCurrentKeys();
    for (SVNURL key : keys) {
      final SVNURL commonURLAncestor = SVNURLUtil.getCommonURLAncestor(key, obj.getUrl());
      if ((commonURLAncestor != null)
          && (!StringUtil.isEmptyOrSpaces(commonURLAncestor.getHost()))
          && (!StringUtil.isEmptyOrSpaces(commonURLAncestor.getPath()))) {
        // final AuthenticationRequest currObj = getObj(key);
        // if ((currObj != null) && passiveValidation(myVcs.getProject(), key, true,
        // currObj.getRealm(), currObj.getKind())) {
        outdatedRequests.add(key);
        // }
      }
    }
    log("on state changed ");
    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              public void run() {
                for (SVNURL key : outdatedRequests) {
                  removeLazyNotificationByKey(key);
                }
              }
            },
            ModalityState.NON_MODAL);
  }
  @Override
  public void renderElement(LookupElementPresentation presentation) {
    final Object object = getObject();
    if (object instanceof PsiClass) {
      JavaPsiClassReferenceElement.renderClassItem(
          presentation, this, (PsiClass) object, myDiamond, myLocationString, mySubstitutor);
    } else {
      assert object instanceof PsiType;

      if (!(object instanceof PsiPrimitiveType)) {
        presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(this, presentation.isReal()));
      }

      presentation.setItemText(((PsiType) object).getCanonicalText());
      presentation.setItemTextBold(object instanceof PsiPrimitiveType);
      if (isAddArrayInitializer()) {
        presentation.setTailText("{...}");
      }
    }
    if (myBracketsCount > 0) {
      presentation.setTailText(
          StringUtil.repeat("[]", myBracketsCount)
              + StringUtil.notNullize(presentation.getTailText()),
          true);
    }
  }
示例#10
0
 @Override
 protected void previewRefactoring(@NotNull final UsageInfo[] usages) {
   MigrationPanel panel = new MigrationPanel(myRoot, myLabeler, myProject, isPreviewUsages());
   String name;
   if (myRoot.length == 1) {
     String fromType =
         assertNotNull(TypeMigrationLabeler.getElementType(myRoot[0])).getPresentableText();
     String toType = myRootTypes.fun(myRoot[0]).getPresentableText();
     String text;
     text = getPresentation(myRoot[0]);
     name = "Migrate Type of " + text + " from \'" + fromType + "\' to \'" + toType + "\'";
   } else {
     final int rootsInPresentationCount =
         myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION
             ? MAX_ROOT_IN_PREVIEW_PRESENTATION
             : myRoot.length;
     String[] rootsPresentation = new String[rootsInPresentationCount];
     for (int i = 0; i < rootsInPresentationCount; i++) {
       final PsiElement root = myRoot[i];
       rootsPresentation[i] =
           root instanceof PsiNamedElement ? ((PsiNamedElement) root).getName() : root.getText();
     }
     rootsPresentation = StringUtil.surround(rootsPresentation, "\'", "\'");
     name = "Migrate Type of " + StringUtil.join(rootsPresentation, ", ");
     if (myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION) {
       name += "...";
     }
   }
   Content content =
       UsageViewManager.getInstance(myProject).addContent(name, false, panel, true, true);
   panel.setContent(content);
   ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND).activate(null);
 }
  public static void apply(
      final String functionName,
      @NotNull final FunctionReference reference,
      final String modifiers,
      final String pattern,
      @NotNull final ProblemsHolder holder) {
    if (reference.getParameters().length >= 2 && !StringUtil.isEmpty(pattern)) {
      Matcher regexMatcher = regexTextSearch.matcher(pattern);
      if (regexMatcher.find()) {
        final boolean ignoreCase = !StringUtil.isEmpty(modifiers) && modifiers.indexOf('i') >= 0;
        final boolean startWith = !StringUtil.isEmpty(regexMatcher.group(1));

        /* analyse if pattern is the one strategy targeting */
        String strProblemDescription = null;
        if (functionName.equals("preg_match") && startWith) {
          strProblemDescription = ignoreCase ? strProblemStartIgnoreCase : strProblemStartTreatCase;
        }
        if (functionName.equals("preg_match") && !startWith) {
          strProblemDescription =
              ignoreCase ? strProblemContainsIgnoreCase : strProblemContainsTreatCase;
        }
        if (functionName.equals("preg_replace") && !startWith) {
          strProblemDescription =
              ignoreCase ? strProblemReplaceIgnoreCase : strProblemReplaceTreatCase;
        }

        if (null != strProblemDescription) {
          String strError = strProblemDescription.replace("%t%", regexMatcher.group(2));
          holder.registerProblem(
              reference, strError, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
        }
      }
    }
  }
  private void setupPanels(@Nullable ProjectTemplate template) {

    restorePanel(myNamePathComponent, 4);
    restorePanel(myModulePanel, myWizardContext.isCreatingNewProject() ? 8 : 6);
    restorePanel(myExpertPanel, myWizardContext.isCreatingNewProject() ? 1 : 0);
    mySettingsStep = myModuleBuilder == null ? null : myModuleBuilder.modifySettingsStep(this);

    String description = null;
    if (template != null) {
      description = template.getDescription();
      if (StringUtil.isNotEmpty(description)) {
        StringBuilder sb = new StringBuilder("<html><body><font ");
        sb.append(SystemInfo.isMac ? "" : "face=\"Verdana\" size=\"-1\"").append('>');
        sb.append(description).append("</font></body></html>");
        description = sb.toString();
        myDescriptionPane.setText(description);
      }
    }

    myExpertPlaceholder.setVisible(
        !(myModuleBuilder instanceof TemplateModuleBuilder)
            && myExpertPanel.getComponentCount() > 0);
    for (int i = 0; i < 6; i++) {
      myModulePanel.getComponent(i).setVisible(!(myModuleBuilder instanceof EmptyModuleBuilder));
    }
    myDescriptionPanel.setVisible(StringUtil.isNotEmpty(description));

    mySettingsPanel.revalidate();
    mySettingsPanel.repaint();
  }
示例#13
0
  private static String[] createArgumentsForJsCompiler(
      File outputFile, List<File> sourceFiles, Set<String> libraryFiles) {
    List<String> args = new ArrayList<String>();

    Collections.addAll(args, "-tags", "-verbose", "-version", "-sourcemap");

    String separator = ",";
    String sourceFilesAsString =
        StringUtil.join(
            sourceFiles,
            new Function<File, String>() {
              @Override
              public String fun(File file) {
                return file.getPath();
              }
            },
            separator);

    args.add("-sourceFiles");
    args.add(sourceFilesAsString);

    args.add("-output");
    args.add(outputFile.getPath());

    args.add("-libraryFiles");
    args.add(StringUtil.join(libraryFiles, separator));

    return ArrayUtil.toStringArray(args);
  }
示例#14
0
 @Override
 public String getCanonicalName() {
   if (myPrecise) {
     return "list("
         + StringUtil.join(
             myPositionalTypes,
             new Function<TypeDescriptor, String>() {
               @Override
               public String fun(TypeDescriptor descriptor) {
                 String typeName = descriptor.myType.getName();
                 String name = descriptor.myName;
                 return (name == null) ? typeName : name + ": " + typeName;
               }
             },
             ", ")
         + ")";
   } else {
     return "list{"
         + StringUtil.join(
             myFields.entrySet(),
             new Function<Map.Entry<String, RType>, String>() {
               @Override
               public String fun(Map.Entry<String, RType> entry) {
                 return entry.getKey() + ": " + entry.getValue().getName();
               }
             },
             ", ")
         + "}";
   }
 }
  @Nullable
  private static GithubFullPath findRepositoryByUser(
      @NotNull Project project,
      @NotNull String user,
      @NotNull Set<GithubFullPath> forks,
      @NotNull GithubAuthData auth,
      @NotNull GithubRepo source) {
    for (GithubFullPath path : forks) {
      if (StringUtil.equalsIgnoreCase(user, path.getUser())) {
        return path;
      }
    }

    try {
      GithubRepoDetailed target = GithubApiUtil.getDetailedRepoInfo(auth, user, source.getName());
      if (target.getSource() != null
          && StringUtil.equals(target.getSource().getUserName(), source.getUserName())) {
        return target.getFullPath();
      }
    } catch (IOException ignore) {
      // such repo may not exist
    }

    try {
      GithubRepo fork =
          GithubApiUtil.findForkByUser(auth, source.getUserName(), source.getName(), user);
      if (fork != null) {
        return fork.getFullPath();
      }
    } catch (IOException e) {
      GithubNotifications.showError(project, CANNOT_CREATE_PULL_REQUEST, e);
    }

    return null;
  }
  private JavaParameters createJavaParameters() throws ExecutionException {
    JavaParameters parameters = new JavaParameters();
    Sdk sdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
    if (sdk == null) {
      throw new ExecutionException("No Java SDK available.");
    }
    parameters.setJdk(sdk);
    parameters.setMainClass(AbstractPaxBasedFrameworkRunner.PaxRunnerMainClass);
    PathsList classpath = parameters.getClassPath();
    for (VirtualFile libraryFile : AbstractPaxBasedFrameworkRunner.getPaxLibraries()) {
      classpath.add(libraryFile);
    }

    ParametersList parametersList = parameters.getProgramParametersList();
    parametersList.add("--p=" + myFrameworkType);
    if (!StringUtil.isEmpty(myVersion)) {
      parametersList.add("--v=" + myVersion);
    }
    parametersList.add("--nologo=true");
    parametersList.add("--executor=noop");
    parametersList.add("--workingDirectory=" + myTargetFolder);
    if (myClearDownloadFolder) {
      parametersList.add("--clean");
    }
    if (!StringUtil.isEmpty(myProfiles)) {
      parametersList.add("--profiles=" + myProfiles);
    }
    return parameters;
  }
  @SuppressWarnings("HardCodedStringLiteral")
  @NotNull
  public List<File> getClassPath() {
    if (myPath.isDirectory()) {
      final List<File> result = new ArrayList<File>();
      final File classesDir = new File(myPath, "classes");

      if (classesDir.exists()) {
        result.add(classesDir);
      }

      final File[] files = new File(myPath, "lib").listFiles();
      if (files != null && files.length > 0) {
        for (final File f : files) {
          if (f.isFile()) {
            final String name = f.getName();
            if (StringUtil.endsWithIgnoreCase(name, ".jar")
                || StringUtil.endsWithIgnoreCase(name, ".zip")) {
              result.add(f);
            }
          } else {
            result.add(f);
          }
        }
      }

      return result;
    } else {
      return Collections.singletonList(myPath);
    }
  }
  @NotNull
  private int[] fixRanges(@NotNull DocumentEvent e, int line1, int line2) {
    CharSequence document = myDocument.getCharsSequence();
    int offset = e.getOffset();

    if (e.getOldLength() == 0 && e.getNewLength() != 0) {
      if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
        return new int[] {line1, line2 - 1};
      }
      if (StringUtil.startsWithChar(e.getNewFragment(), '\n')
          && isNewline(offset + e.getNewLength(), document)) {
        return new int[] {line1 + 1, line2};
      }
    }
    if (e.getOldLength() != 0 && e.getNewLength() == 0) {
      if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
        return new int[] {line1, line2 - 1};
      }
      if (StringUtil.startsWithChar(e.getOldFragment(), '\n')
          && isNewline(offset + e.getNewLength(), document)) {
        return new int[] {line1 + 1, line2};
      }
    }

    return new int[] {line1, line2};
  }
 private static int subSequenceHashCode(
     @NotNull CharSequence sequence, int startOffset, int endOffset) {
   if (startOffset == 0 && endOffset == sequence.length()) {
     return StringUtil.stringHashCode(sequence);
   }
   return StringUtil.stringHashCode(sequence, startOffset, endOffset);
 }
示例#20
0
 @NotNull
 public static String getPropertyNameByGetter(PsiMethod getterMethod) {
   @NonNls String methodName = getterMethod.getName();
   return methodName.startsWith("get")
       ? StringUtil.decapitalize(methodName.substring(3))
       : StringUtil.decapitalize(methodName.substring(2));
 }
  @Override
  public void reset(@NotNull HttpConfigurable settings) {
    myNoProxyRb.setSelected(true); // default
    myAutoDetectProxyRb.setSelected(settings.USE_PROXY_PAC);
    myPacUrlCheckBox.setSelected(settings.USE_PAC_URL);
    myPacUrlTextField.setText(settings.PAC_URL);
    myUseHTTPProxyRb.setSelected(settings.USE_HTTP_PROXY);
    myProxyAuthCheckBox.setSelected(settings.PROXY_AUTHENTICATION);

    enableProxy(settings.USE_HTTP_PROXY);

    myProxyLoginTextField.setText(settings.getProxyLogin());
    myProxyPasswordTextField.setText(settings.getPlainProxyPassword());

    myProxyPortTextField.setNumber(settings.PROXY_PORT);
    myProxyHostTextField.setText(settings.PROXY_HOST);
    myProxyExceptions.setText(StringUtil.notNullize(settings.PROXY_EXCEPTIONS));

    myRememberProxyPasswordCheckBox.setSelected(settings.KEEP_PROXY_PASSWORD);
    mySocks.setSelected(settings.PROXY_TYPE_IS_SOCKS);
    myHTTP.setSelected(!settings.PROXY_TYPE_IS_SOCKS);

    boolean showError = !StringUtil.isEmptyOrSpaces(settings.LAST_ERROR);
    myErrorLabel.setVisible(showError);
    myErrorLabel.setText(showError ? errorText(settings.LAST_ERROR) : null);

    final String oldStyleText =
        CommonProxy.getMessageFromProps(CommonProxy.getOldStyleProperties());
    myOtherWarning.setVisible(oldStyleText != null);
    if (oldStyleText != null) {
      myOtherWarning.setText(oldStyleText);
      myOtherWarning.setIcon(Messages.getWarningIcon());
    }
  }
 private static String trimTrailingSeparators(@NotNull String path, boolean isJar) {
   while (StringUtil.endsWithChar(path, '/')
       && !(isJar && path.endsWith(JarFileSystem.JAR_SEPARATOR))) {
     path = StringUtil.trimEnd(path, "/");
   }
   return path;
 }
示例#23
0
  @NotNull
  private static String getMultilineDocCommentText(final @NotNull DartDocComment docComment) {
    final StringBuilder buf = new StringBuilder();
    boolean afterAsterisk = false;

    for (PsiElement child = docComment.getFirstChild();
        child != null;
        child = child.getNextSibling()) {
      final IElementType elementType = child.getNode().getElementType();
      final String text = child.getText();

      if (elementType != DartTokenTypesSets.MULTI_LINE_DOC_COMMENT_START
          && elementType != DartTokenTypesSets.DOC_COMMENT_LEADING_ASTERISK
          && elementType != DartTokenTypesSets.MULTI_LINE_COMMENT_END) {
        int newLinesCount;
        if (child instanceof PsiWhiteSpace
            && (newLinesCount = StringUtil.countNewLines(text)) > 0) {
          buf.append(StringUtil.repeatSymbol('\n', newLinesCount));
        } else {
          if (afterAsterisk && text.startsWith(" ")) {
            buf.append(text.substring(1));
          } else {
            buf.append(text);
          }
        }
      }

      afterAsterisk = elementType == DartTokenTypesSets.DOC_COMMENT_LEADING_ASTERISK;
    }

    return buf.toString();
  }
  public static boolean putProxyCredentialsIntoServerFile(
      @NotNull final File configDir,
      @NotNull final String host,
      @NotNull final PasswordAuthentication authentication) {
    final IdeaSVNConfigFile configFile =
        new IdeaSVNConfigFile(new File(configDir, SERVERS_FILE_NAME));
    configFile.updateGroups();

    String groupName = SvnAuthenticationManager.getGroupForHost(host, configFile);
    // no proxy defined in group -> no sense in password
    if (StringUtil.isEmptyOrSpaces(groupName)) return false;
    final Map<String, String> properties = configFile.getAllGroups().get(groupName).getProperties();
    if (StringUtil.isEmptyOrSpaces(properties.get(SvnAuthenticationManager.HTTP_PROXY_HOST)))
      return false;
    if (StringUtil.isEmptyOrSpaces(properties.get(SvnAuthenticationManager.HTTP_PROXY_PORT)))
      return false;

    configFile.setValue(
        groupName, SvnAuthenticationManager.HTTP_PROXY_USERNAME, authentication.getUserName());
    configFile.setValue(
        groupName,
        SvnAuthenticationManager.HTTP_PROXY_PASSWORD,
        String.valueOf(authentication.getPassword()));
    configFile.save();
    return true;
  }
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
  @Nullable
  private static URI resolveUriFromSimpleExpression(@Nullable GrExpression expression) {
    if (expression == null) return null;

    try {
      if (expression instanceof PsiLiteral) {
        URI uri = new URI(String.valueOf(PsiLiteral.class.cast(expression).getValue()));
        if (uri.getScheme() != null && StringUtil.startsWith(uri.getScheme(), "http")) return uri;
      }
    } catch (URISyntaxException ignored) {
      // ignore it
    }

    try {
      PsiReference reference = expression.getReference();
      if (reference == null) return null;
      PsiElement element = reference.resolve();
      if (element instanceof GrVariable) {
        List<GrLiteral> grLiterals = PsiTreeUtil.getChildrenOfTypeAsList(element, GrLiteral.class);
        if (grLiterals.isEmpty()) return null;
        URI uri = new URI(String.valueOf(grLiterals.get(0).getValue()));
        if (uri.getScheme() != null && StringUtil.startsWith("http", uri.getScheme())) return uri;
      }
    } catch (URISyntaxException ignored) {
      // ignore it
    }

    return null;
  }
 static void log(
     ProgressIndicator progressIndicator,
     TextEditorHighlightingPass pass,
     @NonNls @NotNull Object... info) {
   if (LOG.isDebugEnabled()) {
     CharSequence docText =
         pass == null || pass.getDocument() == null
             ? ""
             : ": '" + StringUtil.first(pass.getDocument().getCharsSequence(), 10, true) + "'";
     synchronized (PassExecutorService.class) {
       String infos = StringUtil.join(info, Functions.TO_STRING(), " ");
       String message =
           StringUtil.repeatSymbol(' ', getThreadNum() * 4)
               + " "
               + pass
               + " "
               + infos
               + "; progress="
               + (progressIndicator == null ? null : progressIndicator.hashCode())
               + " "
               + (progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V")
               + docText;
       LOG.debug(message);
       // System.out.println(message);
     }
   }
 }
  private void addRslInfo(final Element rootElement, final Map<String, String> libNameToRslInfo) {
    if (libNameToRslInfo.isEmpty()) return;

    // RSL order is important!
    for (final String libName : LIB_ORDER) {
      final String rslInfo = libNameToRslInfo.remove(libName);
      if (rslInfo != null) {
        final CompilerOptionInfo option =
            StringUtil.split(rslInfo, CompilerOptionInfo.LIST_ENTRY_PARTS_SEPARATOR, true, false)
                        .size()
                    == 3
                ? CompilerOptionInfo.RSL_ONE_URL_PATH_INFO
                : CompilerOptionInfo.RSL_TWO_URLS_PATH_INFO;
        addOption(rootElement, option, rslInfo);
      }
    }

    // now add other in random order, though up to Flex SDK 4.5.1 the map should be empty at this
    // stage
    for (final String rslInfo : libNameToRslInfo.values()) {
      final CompilerOptionInfo option =
          StringUtil.split(rslInfo, CompilerOptionInfo.LIST_ENTRY_PARTS_SEPARATOR, true, false)
                      .size()
                  == 3
              ? CompilerOptionInfo.RSL_ONE_URL_PATH_INFO
              : CompilerOptionInfo.RSL_TWO_URLS_PATH_INFO;
      addOption(rootElement, option, rslInfo);
    }
  }
  public void loadState(final Element element) {
    List groups = element.getChildren(GROUP_TAG);

    for (Object group : groups) {
      Element groupElement = (Element) group;
      String groupName = groupElement.getAttributeValue(GROUP_NAME_ATTR);

      final GroupDescriptor groupDescriptor = GroupDescriptor.create(groupName);

      List projectsList = groupElement.getChildren(PROJECT_TAG);
      for (Object project : projectsList) {
        Element projectElement = (Element) project;
        String projectId = projectElement.getAttributeValue(PROJECT_ID_ATTR);
        String frameworks = projectElement.getAttributeValue(VALUES_ATTR);
        if (!StringUtil.isEmptyOrSpaces(projectId) && !StringUtil.isEmptyOrSpaces(frameworks)) {
          Set<UsageDescriptor> frameworkDescriptors = new HashSet<UsageDescriptor>();
          for (String key : StringUtil.split(frameworks, TOKENIZER)) {
            final UsageDescriptor descriptor = getUsageDescriptor(key);
            if (descriptor != null) frameworkDescriptors.add(descriptor);
          }
          getApplicationData(groupDescriptor).put(projectId, frameworkDescriptors);
        }
      }
    }
  }
示例#30
0
  public static void assertEqualsToFile(
      @NotNull File expectedFile,
      @NotNull String actual,
      @NotNull Function1<String, String> sanitizer) {
    try {
      String actualText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(actual.trim()));

      if (!expectedFile.exists()) {
        FileUtil.writeToFile(expectedFile, actualText);
        Assert.fail("Expected data file did not exist. Generating: " + expectedFile);
      }
      String expected = FileUtil.loadFile(expectedFile, CharsetToolkit.UTF8, true);

      String expectedText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(expected.trim()));

      if (!Comparing.equal(sanitizer.invoke(expectedText), sanitizer.invoke(actualText))) {
        throw new FileComparisonFailure(
            "Actual data differs from file content: " + expectedFile.getName(),
            expected,
            actual,
            expectedFile.getAbsolutePath());
      }
    } catch (IOException e) {
      throw ExceptionUtilsKt.rethrow(e);
    }
  }