private static boolean isAcceptedByPattern(
      @NotNull PsiClass element,
      String qualifiedName,
      ClassPattern pattern,
      Set<PsiClass> visited) {
    if (qualifiedName == null) {
      return false;
    }

    if (qualifiedName.equals(pattern.pattern)) {
      return true;
    }

    if (pattern.pattern.endsWith(PATTERN_SUFFIX)
        && qualifiedName.startsWith(StringUtil.trimEnd(pattern.pattern, PATTERN_SUFFIX))) {
      return true;
    }

    if (pattern.hierarchically) {
      for (PsiClass superClass : element.getSupers()) {
        final String superClassQualifiedName = superClass.getQualifiedName();
        if (visited.add(superClass)
            && isAcceptedByPattern(superClass, superClassQualifiedName, pattern, visited)) {
          return true;
        }
      }
    }
    return false;
  }
 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;
 }
 private static String stripTrailingPathSeparator(String path, String protocol) {
   while (path.endsWith("/")
       && !(protocol.equals(JarFileSystem.PROTOCOL)
           && path.endsWith(JarFileSystem.JAR_SEPARATOR))) {
     path = StringUtil.trimEnd(path, "/");
   }
   return path;
 }
 public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
   final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
   if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
     String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
     if (StringUtil.isNotEmpty(path)) {
       params.addEnv("JAVA_HOME", FileUtil.toSystemDependentName(path));
     }
   }
 }
  private static GrExpression genRefForGetter(GrMethodCall call, String accessorName) {
    String name = GroovyPropertyUtils.getPropertyNameByGetterName(accessorName, true);
    GrReferenceExpression refExpr = (GrReferenceExpression) call.getInvokedExpression();
    String oldNameStr = refExpr.getReferenceNameElement().getText();
    String newRefExpr = StringUtil.trimEnd(refExpr.getText(), oldNameStr) + name;

    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(call.getProject());
    return factory.createExpressionFromText(newRefExpr, call);
  }
 @NotNull
 private static String composeSimpleUrl(@NonNls @NotNull String packageName, @NotNull String rep) {
   String suffix = "";
   final String repository = StringUtil.trimEnd(rep, "/");
   if (!repository.endsWith("+simple") && !repository.endsWith("/simple")) {
     suffix = "/+simple";
   }
   suffix += "/" + packageName;
   return repository + suffix;
 }
  private static void assertOrder(PsiJavaFile file, @NonNls String... expectedOrder) {
    PsiImportStatementBase[] statements = file.getImportList().getAllImportStatements();

    assertEquals(expectedOrder.length, statements.length);
    for (int i = 0; i < statements.length; i++) {
      PsiImportStatementBase statement = statements[i];
      String text = StringUtil.trimEnd(StringUtil.trimStart(statement.getText(), "import "), ";");
      assertEquals(expectedOrder[i], text);
    }
  }
 @NotNull
 private static String stripTrailingPathSeparator(
     @NotNull String path, @NotNull String protocol, IVirtualFileSystem fileSystem) {
   while (!path.isEmpty()
       && path.charAt(path.length() - 1) == '/'
       && !(fileSystem instanceof ArchiveFileSystem)
       && path.endsWith(ArchiveFileSystem.ARCHIVE_SEPARATOR)) {
     path = StringUtil.trimEnd(path, "/");
   }
   return path;
 }
 private static List<String> convertToLocalPaths(VirtualFile[] files) {
   final List<String> paths = new ArrayList<String>();
   for (VirtualFile file : files) {
     if (file.isValid()) {
       paths.add(
           StringUtil.trimEnd(
               FileUtil.toSystemIndependentName(file.getPath()), JarFileSystem.JAR_SEPARATOR));
     }
   }
   return paths;
 }
  @Nullable
  public static List<String> findTestDataFiles(@NotNull DataContext context) {
    final PsiMethod method = findTargetMethod(context);
    if (method == null) {
      return null;
    }
    final String name = method.getName();

    if (name.startsWith("test")) {
      String testDataPath =
          TestDataLineMarkerProvider.getTestDataBasePath(method.getContainingClass());
      final TestDataReferenceCollector collector =
          new TestDataReferenceCollector(testDataPath, name.substring(4));
      return collector.collectTestDataReferences(method);
    }

    final Location<?> location = Location.DATA_KEY.getData(context);
    if (location instanceof PsiMemberParameterizedLocation) {
      PsiClass containingClass = ((PsiMemberParameterizedLocation) location).getContainingClass();
      if (containingClass == null) {
        containingClass =
            PsiTreeUtil.getParentOfType(location.getPsiElement(), PsiClass.class, false);
      }
      if (containingClass != null) {
        final PsiAnnotation annotation =
            AnnotationUtil.findAnnotationInHierarchy(
                containingClass, Collections.singleton(JUnitUtil.RUN_WITH));
        if (annotation != null) {
          final PsiAnnotationMemberValue memberValue = annotation.findAttributeValue("value");
          if (memberValue instanceof PsiClassObjectAccessExpression) {
            final PsiTypeElement operand =
                ((PsiClassObjectAccessExpression) memberValue).getOperand();
            if (operand.getType().equalsToText(Parameterized.class.getName())) {
              final String testDataPath =
                  TestDataLineMarkerProvider.getTestDataBasePath(containingClass);
              final String paramSetName =
                  ((PsiMemberParameterizedLocation) location).getParamSetName();
              final String baseFileName =
                  StringUtil.trimEnd(StringUtil.trimStart(paramSetName, "["), "]");
              final ProjectFileIndex fileIndex =
                  ProjectRootManager.getInstance(containingClass.getProject()).getFileIndex();
              return TestDataGuessByExistingFilesUtil.suggestTestDataFiles(
                  fileIndex, baseFileName, testDataPath, containingClass);
            }
          }
        }
      }
    }

    return null;
  }
Beispiel #11
0
  public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
    final Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class);
    if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
      String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
      if (StringUtil.isNotEmpty(path)) {
        Map<String, String> env = params.getEnv();
        if (env == null) {
          env = new HashMap<String, String>();
          params.setEnv(env);
        }

        env.put("JAVA_HOME", FileUtil.toSystemDependentName(path));
      }
    }
  }
 private TemplateResource getDefaultTemplate(
     String selfSuffix, String oppositeSuffix, TemplateResource defaultTemplate) {
   final String fileName = defaultTemplate.getFileName();
   if (fileName.endsWith(selfSuffix)) {
     return defaultTemplate;
   }
   final String equalsTemplateName = StringUtil.trimEnd(fileName, oppositeSuffix) + selfSuffix;
   for (TemplateResource resource : getAllTemplates()) {
     if (equalsTemplateName.equals(resource.getFileName())) {
       return resource;
     }
   }
   assert false : selfSuffix + " template for " + fileName + " not found";
   return null;
 }
 // minimum sequence of text replacement operations for each host range
 // result[i] == null means no change
 // result[i] == "" means delete
 // result[i] == string means replace
 public String[] calculateMinEditSequence(String newText) {
   synchronized (myLock) {
     String[] result = new String[myShreds.size()];
     String hostText = myDelegate.getText();
     calculateMinEditSequence(hostText, newText, result, 0, result.length - 1);
     for (int i = 0; i < result.length; i++) {
       String change = result[i];
       if (change == null) continue;
       String prefix = myShreds.get(i).getPrefix();
       String suffix = myShreds.get(i).getSuffix();
       assert change.startsWith(prefix) : change + "/" + prefix;
       assert change.endsWith(suffix) : change + "/" + suffix;
       result[i] = StringUtil.trimEnd(StringUtil.trimStart(change, prefix), suffix);
     }
     return result;
   }
 }
  // null means we were unable to get roots, so do not check access
  @Nullable
  @TestOnly
  private static Set<String> allowedRoots() {
    if (insideGettingRoots) return null;

    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    if (openProjects.length == 0) return null;

    final Set<String> allowed = new THashSet<String>();
    allowed.add(FileUtil.toSystemIndependentName(PathManager.getHomePath()));

    try {
      URL outUrl = Application.class.getResource("/");
      String output = new File(outUrl.toURI()).getParentFile().getParentFile().getPath();
      allowed.add(FileUtil.toSystemIndependentName(output));
    } catch (URISyntaxException ignored) {
    }

    allowed.add(FileUtil.toSystemIndependentName(SystemProperties.getJavaHome()));
    allowed.add(
        FileUtil.toSystemIndependentName(new File(FileUtil.getTempDirectory()).getParent()));
    allowed.add(FileUtil.toSystemIndependentName(System.getProperty("java.io.tmpdir")));
    allowed.add(FileUtil.toSystemIndependentName(SystemProperties.getUserHome()));

    for (Project project : openProjects) {
      if (!project.isInitialized()) {
        return null; // all is allowed
      }
      for (VirtualFile root : ProjectRootManager.getInstance(project).getContentRoots()) {
        allowed.add(root.getPath());
      }
      for (VirtualFile root : getAllRoots(project)) {
        allowed.add(StringUtil.trimEnd(root.getPath(), JarFileSystem.JAR_SEPARATOR));
      }
      String location = project.getBasePath();
      assert location != null : project;
      allowed.add(FileUtil.toSystemIndependentName(location));
    }

    allowed.addAll(ourAdditionalRoots);

    return allowed;
  }
Beispiel #15
0
  @SuppressWarnings("UseOfSystemOutOrSystemErr")
  private static synchronized void printOrder(Loader loader, String url, Resource resource) {
    if (!ourDumpOrder) return;
    if (!ourOrderedUrls.add(url)) return;

    String home = FileUtil.toSystemIndependentName(PathManager.getHomePath());
    try {
      ourOrderSize += resource.getContentLength();
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }

    if (ourOrder == null) {
      final File orderFile = new File(PathManager.getBinPath() + File.separator + "order.txt");
      try {
        if (!FileUtil.ensureCanCreateFile(orderFile)) return;
        ourOrder = new PrintStream(new FileOutputStream(orderFile, true));
        ShutDownTracker.getInstance()
            .registerShutdownTask(
                new Runnable() {
                  public void run() {
                    ourOrder.close();
                    System.out.println(ourOrderSize);
                  }
                });
      } catch (IOException e) {
        return;
      }
    }

    if (ourOrder != null) {
      String jarURL = FileUtil.toSystemIndependentName(loader.getBaseURL().getFile());
      jarURL = StringUtil.trimStart(jarURL, "file:/");
      if (jarURL.startsWith(home)) {
        jarURL = jarURL.replaceFirst(home, "");
        jarURL = StringUtil.trimEnd(jarURL, "!/");
        ourOrder.println(url + ":" + jarURL);
      }
    }
  }
  private static GrStatement[] createTupleDeclaration(
      final VariableInfo[] infos, GrMethodCallExpression callExpression, final Project project) {
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);

    StringBuilder tuple = new StringBuilder();
    tuple.append("def (");
    for (VariableInfo info : infos) {
      final PsiType type = info.getType();
      if (type != null) {
        final PsiType unboxed = TypesUtil.unboxPrimitiveTypeWrapper(type);
        tuple.append(unboxed.getCanonicalText());
        tuple.append(' ');
      }
      tuple.append(info.getName());
      tuple.append(",");
    }
    StringUtil.trimEnd(tuple, ",");
    tuple.append(")=");
    tuple.append(callExpression.getText());

    return new GrStatement[] {factory.createStatementFromText(tuple)};
  }
 public MinusculeMatcher(
     @NotNull String pattern, @NotNull NameUtil.MatchingCaseSensitivity options) {
   myOptions = options;
   myPattern = StringUtil.trimEnd(pattern, "* ").toCharArray();
   isLowerCase = new boolean[myPattern.length];
   isUpperCase = new boolean[myPattern.length];
   isWordSeparator = new boolean[myPattern.length];
   toUpperCase = new char[myPattern.length];
   toLowerCase = new char[myPattern.length];
   for (int k = 0; k < myPattern.length; k++) {
     char c = myPattern[k];
     isLowerCase[k] = Character.isLowerCase(c);
     isUpperCase[k] = Character.isUpperCase(c);
     isWordSeparator[k] = isWordSeparator(c);
     toUpperCase[k] = StringUtil.toUpperCase(c);
     toLowerCase[k] = StringUtil.toLowerCase(c);
   }
   int i = 0;
   while (isWildcard(i)) i++;
   myHasHumps = hasFlag(i + 1, isUpperCase) && hasFlag(i, isLowerCase);
   myHasSeparators = hasFlag(i, isWordSeparator);
   myHasDots = hasDots(i);
   myHasWildCards = hasWildCards();
 }
 public String getHomePath() {
   final String homePath =
       FileUtil.toSystemDependentName(myHomePath == null ? myDelegate.getHomePath() : myHomePath);
   return StringUtil.trimEnd(homePath, File.separator);
 }
 @NotNull
 public static String getLocalPath(@NotNull String path) {
   return FileUtil.toSystemDependentName(StringUtil.trimEnd(path, URLUtil.JAR_SEPARATOR));
 }
 private static String moduleNameByFileName(@NotNull String fileName) {
   return StringUtil.trimEnd(fileName, ModuleFileType.DOT_DEFAULT_EXTENSION);
 }
 // copy of ApplicationInfoProperties.shortenCompanyName
 @VisibleForTesting
 static String shortenCompanyName(String name) {
   return StringUtil.trimEnd(StringUtil.trimEnd(name, " s.r.o."), " Inc.");
 }
 private static String trimSlash(String s) {
   return StringUtil.trimEnd(s, "/");
 }
 @NotNull
 public static String toAbsolute(@NotNull VirtualFile root, @NotNull String relativePath) {
   return StringUtil.trimEnd(root.getPath(), "/") + "/" + StringUtil.trimStart(relativePath, "/");
 }
  @Override
  @Nullable
  public String generateDoc(PsiElement element, PsiElement originalElement) {
    if (element instanceof CustomMembersGenerator.GdslNamedParameter) {
      CustomMembersGenerator.GdslNamedParameter parameter =
          (CustomMembersGenerator.GdslNamedParameter) element;
      String result = "<pre><b>" + parameter.getName() + "</b>";
      if (parameter.myParameterTypeText != null) {
        result += ": " + parameter.myParameterTypeText;
      }
      result += "</pre>";
      if (parameter.docString != null) {
        result += "<p>" + parameter.docString;
      }
      return result;
    }

    if (element instanceof GrReferenceExpression) {
      return getMethodCandidateInfo((GrReferenceExpression) element);
    }

    element = getDocumentationElement(element, originalElement);

    if (element == null) return null;

    String standard =
        element.getNavigationElement() instanceof PsiDocCommentOwner
            ? JavaDocumentationProvider.generateExternalJavadoc(element)
            : null;

    if (element instanceof GrVariable
        && ((GrVariable) element).getTypeElementGroovy() == null
        && standard != null) {
      final String truncated = StringUtil.trimEnd(standard, BODY_HTML);

      StringBuilder buffer = new StringBuilder(truncated);
      buffer.append("<p>");
      if (originalElement != null) {
        appendInferredType(originalElement, (GrVariable) element, buffer);
      } else if (element.getParent() instanceof GrVariableDeclaration) {
        appendInferredType(element.getParent(), (GrVariable) element, buffer);
      }

      if (!truncated.equals(standard)) {
        buffer.append(BODY_HTML);
      }
      standard = buffer.toString();
    }

    String gdslDoc = element.getUserData(NonCodeMembersHolder.DOCUMENTATION);
    if (gdslDoc != null) {
      if (standard != null) {
        String truncated = StringUtil.trimEnd(standard, BODY_HTML);
        String appended = truncated + "<p>" + gdslDoc;
        if (truncated.equals(standard)) {
          return appended;
        }
        return appended + BODY_HTML;
      }
      return gdslDoc;
    }

    return standard;
  }
public abstract class BaseInspection extends GroovySuppressableInspectionTool {

  private final String m_shortName = StringUtil.trimEnd(getClass().getSimpleName(), "Inspection");

  public static final String ASSIGNMENT_ISSUES = "Assignment issues";
  public static final String CONFUSING_CODE_CONSTRUCTS = "Potentially confusing code constructs";
  public static final String CONTROL_FLOW = "Control Flow";
  public static final String PROBABLE_BUGS = "Probable bugs";
  public static final String ERROR_HANDLING = "Error handling";
  public static final String GPATH = "GPath inspections";
  public static final String METHOD_METRICS = "Method Metrics";
  public static final String THREADING_ISSUES = "Threading issues";
  public static final String VALIDITY_ISSUES = "Validity issues";
  public static final String ANNOTATIONS_ISSUES = "Annotations verifying";

  @NotNull
  @Override
  public String[] getGroupPath() {
    return new String[] {"Groovy", getGroupDisplayName()};
  }

  @NotNull
  public String getShortName() {
    return m_shortName;
  }

  @Nullable
  BaseInspectionVisitor buildGroovyVisitor(
      @NotNull ProblemsHolder problemsHolder, boolean onTheFly) {
    final BaseInspectionVisitor visitor = buildVisitor();
    visitor.setProblemsHolder(problemsHolder);
    visitor.setOnTheFly(onTheFly);
    visitor.setInspection(this);
    return visitor;
  }

  @Nullable
  protected String buildErrorString(Object... args) {
    return null;
  }

  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
    return false;
  }

  @Nullable
  protected GroovyFix buildFix(PsiElement location) {
    return null;
  }

  @Nullable
  protected GroovyFix[] buildFixes(PsiElement location) {
    return null;
  }

  @Nullable
  public ProblemDescriptor[] checkFile(
      @NotNull PsiFile psiFile, @NotNull InspectionManager inspectionManager, boolean isOnTheFly) {
    if (!(psiFile instanceof GroovyFileBase)) {
      return super.checkFile(psiFile, inspectionManager, isOnTheFly);
    }
    final GroovyFileBase groovyFile = (GroovyFileBase) psiFile;

    final ProblemsHolder problemsHolder =
        new ProblemsHolder(inspectionManager, psiFile, isOnTheFly);
    final BaseInspectionVisitor visitor = buildGroovyVisitor(problemsHolder, isOnTheFly);
    groovyFile.accept(visitor);
    final List<ProblemDescriptor> problems = problemsHolder.getResults();
    return problems.toArray(new ProblemDescriptor[problems.size()]);
  }

  protected abstract BaseInspectionVisitor buildVisitor();
}
 @NotNull
 public static String getTemplateBaseName(TemplateResource resource) {
   return StringUtil.trimEnd(
           StringUtil.trimEnd(resource.getFileName(), EQUALS_SUFFIX), HASH_CODE_SUFFIX)
       .trim();
 }
Beispiel #27
0
 public static String toDefXmlTagName(String tname) {
   String xmlName = tname;
   xmlName = StringUtil.trimEnd(xmlName, TYPE_SUFFIX);
   return xmlName;
 }
 @NotNull
 @Override
 public String getName() {
   return StringUtil.trimEnd(PathUtil.getFileName(myPath), ModuleFileType.DOT_DEFAULT_EXTENSION);
 }