Java Code Examples for com.intellij.openapi.util.text.StringUtil#startsWith()

The following examples show how to use com.intellij.openapi.util.text.StringUtil#startsWith() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProjectInfo.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
public LibraryInfo getLibraries(@NotNull String libraryId) {
  if (libraries.containsKey(libraryId) && libraries.get(libraryId).getDefault() != null) {
    return libraries.get(libraryId);
  }
  int versionIndex = libraryId.lastIndexOf(':');
  if (versionIndex == -1) {
    return null;
  }
  final String libraryName = libraryId.substring(0, versionIndex);
  for (Map.Entry<String, LibraryInfo> libIdAndJars : libraries.entrySet()) {
    final String currentLibraryId = libIdAndJars.getKey();
    if (!StringUtil.startsWith(currentLibraryId, libraryName + ":")) {
      continue;
    }
    final LibraryInfo currentInfo = libIdAndJars.getValue();
    if (currentInfo != null) {
      LOG.info("Using " + currentLibraryId + " instead of " + libraryId);
      return currentInfo;
    }
  }
  return null;
}
 
Example 2
Source File: GotoActionItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean processTopHits(String pattern, Processor<? super MatchedValue> consumer, DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  final CollectConsumer<Object> collector = new CollectConsumer<Object>();
  for (SearchTopHitProvider provider : SearchTopHitProvider.EP_NAME.getExtensionList()) {
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider.CoveredByToggleActions) continue;
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider && !((com.intellij.ide.ui.OptionsTopHitProvider)provider).isEnabled(project)) continue;
    if (provider instanceof com.intellij.ide.ui.OptionsTopHitProvider && !StringUtil.startsWith(pattern, "#")) {
      String prefix = "#" + ((com.intellij.ide.ui.OptionsTopHitProvider)provider).getId() + " ";
      provider.consumeTopHits(prefix + pattern, collector, project);
    }
    provider.consumeTopHits(pattern, collector, project);
  }
  final Collection<Object> result = collector.getResult();
  final List<Comparable> c = new ArrayList<Comparable>();
  for (Object o : result) {
    if (o instanceof Comparable) {
      c.add((Comparable)o);
    }
  }
  return processItems(pattern, JBIterable.from(c), consumer);
}
 
Example 3
Source File: Unity3dAssetFileTypeDetector.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public FileType detect(@Nonnull VirtualFile file, @Nonnull ByteSequence firstBytes, @Nullable CharSequence firstCharsIfText)
{
	CharSequence extension = FileUtil.getExtension(file.getNameSequence());

	if(ourAssetExtensions.contains(StringUtil.hashCode(extension)))
	{
		if(firstCharsIfText == null)
		{
			return Unity3dBinaryAssetFileType.INSTANCE;
		}
		if(firstCharsIfText.length() > 5)
		{
			if(StringUtil.startsWith(firstCharsIfText, "%YAML"))
			{
				return Unity3dYMLAssetFileType.INSTANCE;
			}
		}

		return Unity3dBinaryAssetFileType.INSTANCE;
	}
	return null;
}
 
Example 4
Source File: EventLog.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void removeJavaNewLines(Document document, List<RangeMarker> lineSeparators, String indent, boolean hasHtml) {
  CharSequence text = document.getCharsSequence();
  int i = 0;
  while (true) {
    i = StringUtil.indexOf(text, '\n', i);
    if (i < 0) break;
    int j = i + 1;
    if (StringUtil.startsWith(text, j, indent)) {
      j += indent.length();
    }
    document.deleteString(i, j);
    if (!hasHtml) {
      lineSeparators.add(document.createRangeMarker(TextRange.from(i, 0)));
    }
  }
}
 
Example 5
Source File: ModelUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean isBuildMethod(@NotNull Element element) {
  if (element.getName() == null || element.getParameters() == null) {
    return false;
  }
  return StringUtil.equals("build", element.getName()) &&
         StringUtil.startsWith(element.getParameters(), "(BuildContext ");
}
 
Example 6
Source File: FindInProjectUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static Condition<CharSequence> createFileMaskCondition(@Nullable String filter) throws PatternSyntaxException {
  if (filter == null) {
    return Conditions.alwaysTrue();
  }

  String pattern = "";
  String negativePattern = "";
  final List<String> masks = StringUtil.split(filter, ",");

  for (String mask : masks) {
    mask = mask.trim();
    if (StringUtil.startsWith(mask, "!")) {
      negativePattern += (negativePattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask.substring(1)) + ")";
    }
    else {
      pattern += (pattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask) + ")";
    }
  }

  if (pattern.isEmpty()) pattern = PatternUtil.convertToRegex("*");
  final String finalPattern = pattern;
  final String finalNegativePattern = negativePattern;

  return new Condition<CharSequence>() {
    final Pattern regExp = Pattern.compile(finalPattern, Pattern.CASE_INSENSITIVE);
    final Pattern negativeRegExp = StringUtil.isEmpty(finalNegativePattern) ? null : Pattern.compile(finalNegativePattern, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean value(CharSequence input) {
      return regExp.matcher(input).matches() && (negativeRegExp == null || !negativeRegExp.matcher(input).matches());
    }
  };
}
 
Example 7
Source File: TokenBuffer.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void combineTrailingCRWith(@Nonnull String currentText) {
  if (StringUtil.startsWith(currentText, "\n")) {
    TokenInfo last = tokens.removeLast();
    String lastTextWithNoCR = last.getText().substring(0, last.length() - 1);
    if (!lastTextWithNoCR.isEmpty()) {
      TokenInfo newLast = new TokenInfo(last.contentType, lastTextWithNoCR, last.getHyperlinkInfo());
      tokens.addLast(newLast);
      size--;
    }
    return;
  }
  removeLastLine();
}
 
Example 8
Source File: ExpandMacroToPathMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static int findMacroIndex(String text, String macroName) {
  int i = -1;
  while (true) {
    i = text.indexOf('$', i + 1);
    if (i < 0) {
      return -1;
    }
    if (StringUtil.startsWith(text, i + 1, macroName) && StringUtil.isChar(text, i + macroName.length() + 1, '$')) {
      return i;
    }
  }
}
 
Example 9
Source File: XmlCharsetDetector.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static String extractXmlEncodingFromProlog(@Nonnull CharSequence text) {
  int index = 0;

  index = skipWhiteSpace(index, text);
  if (!StringUtil.startsWith(text, index, XML_PROLOG_START)) return null;
  index += XML_PROLOG_START.length();
  while (index < text.length()) {
    index = skipWhiteSpace(index, text);
    if (StringUtil.startsWith(text, index, XML_PROLOG_END)) return null;
    if (StringUtil.startsWith(text, index, ENCODING)) {
      index += ENCODING.length();
      index = skipWhiteSpace(index, text);
      if (index >= text.length() || text.charAt(index) != '=') continue;
      index++;
      index = skipWhiteSpace(index, text);
      if (index >= text.length()) continue;
      char quote = text.charAt(index);
      if (quote != '\'' && quote != '\"') continue;
      index++;
      StringBuilder encoding = new StringBuilder();
      while (index < text.length()) {
        char c = text.charAt(index);
        if (c == quote) return encoding.toString();
        encoding.append(c);
        index++;
      }
    }
    index++;
  }
  return null;
}
 
Example 10
Source File: ModelUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean isBuildMethod(@NotNull Element element) {
  if (element.getName() == null || element.getParameters() == null) {
    return false;
  }
  return StringUtil.equals("build", element.getName()) &&
         StringUtil.startsWith(element.getParameters(), "(BuildContext ");
}
 
Example 11
Source File: LightPlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isLight(Project project) {
  String creationPlace = project.getUserData(CREATION_PLACE);
  return creationPlace != null && StringUtil.startsWith(creationPlace, LIGHT_PROJECT_MARK);
}
 
Example 12
Source File: WildcardFileNameMatcher.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(final CharSequence filename) {
  return StringUtil.startsWith(filename, myPrefix);
}
 
Example 13
Source File: HttpRequests.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static URLConnection openConnection(RequestBuilderImpl builder) throws IOException {
  String url = builder.myUrl;

  for (int i = 0; i < builder.myRedirectLimit; i++) {
    if (builder.myForceHttps && StringUtil.startsWith(url, "http:")) {
      url = "https:" + url.substring(5);
    }

    if (url.startsWith("https:") && ApplicationManager.getApplication() != null) {
      CertificateManager.getInstance();
    }

    URLConnection connection;
    if (!builder.myUseProxy) {
      connection = new URL(url).openConnection(Proxy.NO_PROXY);
    }
    else if (ApplicationManager.getApplication() == null) {
      connection = new URL(url).openConnection();
    }
    else {
      connection = HttpConfigurable.getInstance().openConnection(url);
    }

    connection.setConnectTimeout(builder.myConnectTimeout);
    connection.setReadTimeout(builder.myTimeout);

    if (builder.myUserAgent != null) {
      connection.setRequestProperty("User-Agent", builder.myUserAgent);
    }

    if (builder.myHostnameVerifier != null && connection instanceof HttpsURLConnection) {
      ((HttpsURLConnection)connection).setHostnameVerifier(builder.myHostnameVerifier);
    }

    if (builder.myGzip) {
      connection.setRequestProperty("Accept-Encoding", "gzip");
    }

    if (builder.myAccept != null) {
      connection.setRequestProperty("Accept", builder.myAccept);
    }

    connection.setUseCaches(false);

    if (builder.myTuner != null) {
      builder.myTuner.tune(connection);
    }

    if (connection instanceof HttpURLConnection) {
      int responseCode = ((HttpURLConnection)connection).getResponseCode();

      if (responseCode < 200 || responseCode >= 300 && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED) {
        ((HttpURLConnection)connection).disconnect();

        if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
          url = connection.getHeaderField("Location");
          if (url != null) {
            continue;
          }
        }

        String message = IdeBundle.message("error.connection.failed.with.http.code.N", responseCode);
        throw new HttpStatusException(message, responseCode, StringUtil.notNullize(url, "Empty URL"));
      }
    }

    return connection;
  }

  throw new IOException(IdeBundle.message("error.connection.failed.redirects"));
}
 
Example 14
Source File: HttpRequestUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isRegularBrowser(HttpRequest request) {
  String userAgent = getUserAgent(request);
  return userAgent != null && StringUtil.startsWith(userAgent, "Mozilla/5.0");
}
 
Example 15
Source File: FileReferenceSet.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected int findSeparatorLength(@Nonnull CharSequence sequence, int atOffset) {
  return StringUtil.startsWith(sequence, atOffset, getSeparatorString()) ? getSeparatorString().length() : 0;
}
 
Example 16
Source File: ExternalSystemApiUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isExternalSystemLibrary(@Nonnull Library library, @Nonnull ProjectSystemId externalSystemId) {
  return library.getName() != null && StringUtil.startsWith(library.getName(), externalSystemId.getReadableName() + ": ");
}
 
Example 17
Source File: UnityExternalDocumentationProvider.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
private static String getFileName(PsiElement element)
{
	if(!(element instanceof DotNetTypeDeclaration) && !(element instanceof DotNetLikeMethodDeclaration) && !(element instanceof DotNetFieldDeclaration) && !(element instanceof
			DotNetPropertyDeclaration))
	{
		return null;
	}

	Unity3dRootModuleExtension rootModuleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(element.getProject());
	if(rootModuleExtension == null)
	{
		return null;
	}

	DotNetTypeDeclaration typeDeclaration = PsiTreeUtil.getParentOfType(element, DotNetTypeDeclaration.class, false);
	if(typeDeclaration == null)
	{
		return null;
	}

	String qName = typeDeclaration.getPresentableQName();
	if(qName == null)
	{
		return null;
	}

	if(!StringUtil.startsWith(qName, UnityEnginePrefix))
	{
		return null;
	}

	StringBuilder builder = new StringBuilder();
	builder.append(StringUtil.trimStart(qName, UnityEnginePrefix));

	if(element != typeDeclaration)
	{
		builder.append("-");
		builder.append(StringUtil.toLowerCase(((PsiNamedElement) element).getName()));
	}
	return builder.toString();
}
 
Example 18
Source File: UnityPluginFileValidator.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
private static void notifyAboutPluginFile(@Nonnull final Project project)
{
	Unity3dRootModuleExtension moduleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(project);
	if(moduleExtension == null)
	{
		return;
	}

	Unity3dDefineByVersion unity3dDefineByVersion = Unity3dProjectImportUtil.getUnity3dDefineByVersion(moduleExtension.getSdk());
	final String pluginFileName = unity3dDefineByVersion.getPluginFileName();
	if(pluginFileName == null)
	{
		return;
	}

	File pluginPath = PluginManager.getPluginPath(UnityPluginFileValidator.class);

	final File unityPluginFile = new File(pluginPath, "UnityEditorConsuloPlugin/" + pluginFileName);
	if(!unityPluginFile.exists())
	{
		return;
	}

	VirtualFile baseDir = project.getBaseDir();
	if(baseDir == null)
	{
		return;
	}

	DotNetTypeDeclaration consuloIntegration = DotNetPsiSearcher.getInstance(project).findType("Consulo.Internal.UnityEditor.ConsuloIntegration", GlobalSearchScope.allScope(project));
	if(consuloIntegration != null)
	{
		return;
	}

	List<VirtualFile> targetFiles = new SmartList<>();

	VirtualFile fileByRelativePath = baseDir.findFileByRelativePath(ourPath);
	if(fileByRelativePath != null)
	{
		VirtualFile[] children = fileByRelativePath.getChildren();
		for(VirtualFile child : children)
		{
			CharSequence nameSequence = child.getNameSequence();
			if(StringUtil.startsWith(nameSequence, "UnityEditorConsuloPlugin") && child.getFileType() == DotNetModuleFileType.INSTANCE)
			{
				targetFiles.add(child);
			}
		}
	}

	if(targetFiles.isEmpty())
	{
		showNotify(project, pluginFileName, unityPluginFile, "Consulo plugin for UnityEditor is missing<br><a href=\"update\">Install</a>", Collections.emptyList());
	}
	else
	{
		VirtualFile firstItem = targetFiles.size() == 1 ? targetFiles.get(0) : null;
		if(firstItem != null && VfsUtilCore.virtualToIoFile(firstItem).lastModified() == unityPluginFile.lastModified())
		{
			return;
		}

		String title = "Outdated Consulo plugin(s) for UnityEditor can create <a href=\"info\">issues</a>. <a href=\"update\">Update</a> are recommended";

		showNotify(project, pluginFileName, unityPluginFile, title, targetFiles);
	}
}
 
Example 19
Source File: PantsCreateModulesExtension.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void resolve(
  @NotNull ProjectInfo projectInfo,
  @NotNull PantsCompileOptionsExecutor executor,
  @NotNull DataNode<ProjectData> projectDataNode,
  @NotNull Map<String, DataNode<ModuleData>> modules,
  @NotNull Optional<BuildGraph> buildGraph
) {
  Set<TargetInfo> targetInfoWithinLevel = null;
  if (buildGraph.isPresent()) {
    final int maxDepth = buildGraph.get().getMaxDepth();
    depthToInclude = executor.getIncrementalImportDepth().orElse(null);
    if (depthToInclude == null) {
      throw new PantsException("Task cancelled");
    }
    logger.info(String.format("TargetInfo level %s", depthToInclude));
    targetInfoWithinLevel = buildGraph
      .get()
      .getNodesUpToLevel(depthToInclude)
      .stream()
      .map(BuildGraphNode::getTargetInfo)
      .collect(Collectors.toSet());
  }

  for (Map.Entry<String, TargetInfo> entry : projectInfo.getSortedTargets()) {
    if (targetInfoWithinLevel != null && !targetInfoWithinLevel.contains(entry.getValue())) {
      continue;
    }
    final String targetName = entry.getKey();
    if (StringUtil.startsWith(targetName, ":scala-library")) {
      // we already have it in libs
      continue;
    }
    final TargetInfo targetInfo = entry.getValue();
    if (targetInfo.isEmpty()) {
      LOG.debug("Skipping " + targetName + " because it is empty");
      continue;
    }
    final DataNode<ModuleData> moduleData =
      createModuleData(
        projectDataNode,
        targetName,
        targetInfo,
        executor
      );
    modules.put(targetName, moduleData);
  }
}
 
Example 20
Source File: Utils.java    From idea-gitignore with MIT License 2 votes vote down vote up
/**
 * Checks if file is in project directory.
 *
 * @param file    file
 * @param project project
 * @return file is under directory
 */
public static boolean isInProject(@NotNull final VirtualFile file, @NotNull final Project project) {
    return getModuleForFile(file, project) != null || StringUtil.startsWith(file.getUrl(), "temp://");
}