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

The following examples show how to use com.intellij.openapi.util.text.StringUtil#isNotEmpty() . 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: JDOMExternalizer.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void readMap(Element root, Map<String, String> map, @NonNls @Nullable String rootName, @NonNls String entryName) {
  Element mapRoot;
  if (StringUtil.isNotEmpty(rootName)) {
    mapRoot = root.getChild(rootName);
  }
  else {
    mapRoot = root;
  }
  if (mapRoot == null) {
    return;
  }

  for (@NonNls Element element : mapRoot.getChildren(entryName)) {
    String name = element.getAttributeValue("name");
    if (name != null) {
      map.put(name, element.getAttributeValue("value"));
    }
  }
}
 
Example 2
Source File: S3PreSignedUrlProviderImpl.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public String getPreSignedUrl(@NotNull HttpMethod httpMethod, @NotNull String bucketName, @NotNull String objectKey, @NotNull Map<String, String> params) throws IOException {
  try {
    final Callable<String> resolver = getUrlResolver(httpMethod, bucketName, objectKey, params);
    if (httpMethod == HttpMethod.GET) {
      return TeamCityProperties.getBoolean(TEAMCITY_S3_PRESIGNURL_GET_CACHE_ENABLED)
        ? myGetLinksCache.get(getCacheIdentity(params, objectKey, bucketName), resolver)
        : resolver.call();
    } else {
      return resolver.call();
    }
  } catch (Exception e) {
    final Throwable cause = e.getCause();
    final AWSException awsException = cause != null ? new AWSException(cause) : new AWSException(e);
    final String details = awsException.getDetails();
    if (StringUtil.isNotEmpty(details)) {
      final String message = awsException.getMessage() + details;
      LOG.warn(message);
    }
    throw new IOException(String.format(
      "Failed to create pre-signed URL to %s artifact '%s' in bucket '%s': %s",
      httpMethod.name().toLowerCase(), objectKey, bucketName, awsException.getMessage()
    ), awsException);
  }
}
 
Example 3
Source File: DefaultArrangementSettingsSerializer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public Element serialize(@Nonnull ArrangementSectionRule section) {
  final Element sectionElement = new Element(SECTION_ELEMENT_NAME);
  if (StringUtil.isNotEmpty(section.getStartComment())) {
    // or only != null ?
    sectionElement.setAttribute(SECTION_START_ATTRIBUTE, section.getStartComment());
  }
  if (StringUtil.isNotEmpty(section.getEndComment())) {
    sectionElement.setAttribute(SECTION_END_ATTRIBUTE, section.getEndComment());
  }

  //TODO: serialize start & end comment as rule?
  final List<StdArrangementMatchRule> rules = section.getMatchRules();
  for (int i = 0; i < rules.size(); i++) {
    StdArrangementMatchRule rule = rules.get(i);
    if ((i != 0 || StringUtil.isEmpty(section.getStartComment())) &&
        (i != rules.size() - 1 || StringUtil.isEmpty(section.getEndComment()))) {
      sectionElement.addContent(serialize(rule));
    }
  }
  return sectionElement;
}
 
Example 4
Source File: InstalledPackagesPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
                                               final boolean hasFocus, final int row, final int column) {
  final JLabel cell = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
  final String version = (String)table.getValueAt(row, 1);
  final String availableVersion = (String)table.getValueAt(row, 2);
  boolean update = column == 2 &&
                   StringUtil.isNotEmpty(availableVersion) &&
                   isUpdateAvailable(version, availableVersion);
  cell.setIcon(update ? AllIcons.Vcs.Arrow_right : null);
  final Object pyPackage = table.getValueAt(row, 0);
  if (pyPackage instanceof InstalledPackage) {
    cell.setToolTipText(((InstalledPackage) pyPackage).getTooltipText());
  }
  return cell;
}
 
Example 5
Source File: CliBuilder.java    From eslint-plugin with MIT License 6 votes vote down vote up
@NotNull
static GeneralCommandLine createLint(@NotNull ESLintRunner.ESLintSettings settings) {
    GeneralCommandLine commandLine = create(settings);
    // TODO validate arguments (file exist etc)
    commandLine.addParameter(settings.targetFile);
    CLI.addParamIfNotEmpty(commandLine, C, settings.config);
    if (StringUtil.isNotEmpty(settings.rules)) {
        CLI.addParam(commandLine, RULESDIR, "['" + settings.rules + "']");
    }
    if (StringUtil.isNotEmpty(settings.ext)) {
        CLI.addParam(commandLine, EXT, settings.ext);
    }
    if (settings.fix) {
        commandLine.addParameter(FIX);
    }
    if (settings.reportUnused) {
        commandLine.addParameter(REPORT_UNUSED);
    }
    CLI.addParam(commandLine, FORMAT, JSON);
    return commandLine;
}
 
Example 6
Source File: LiveTemplateLookupElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void renderElement(LookupElementPresentation presentation) {
  super.renderElement(presentation);
  char shortcut = getTemplateShortcut();
  presentation.setItemText(getItemText());
  if (sudden) {
    presentation.setItemTextBold(true);
    if (!presentation.isReal() || !((RealLookupElementPresentation)presentation).isLookupSelectionTouched()) {
      if (shortcut == TemplateSettings.DEFAULT_CHAR) {
        shortcut = TemplateSettings.getInstance().getDefaultShortcutChar();
      }
      presentation.setTypeText("  [" + KeyEvent.getKeyText(shortcut) + "] ");
    }
    if (StringUtil.isNotEmpty(myDescription)) {
      presentation.setTailText(" (" + myDescription + ")", true);
    }
  }
  else {
    presentation.setTypeText(myDescription);
  }
}
 
Example 7
Source File: UIUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void getAllTextsRecursivelyImpl(Component component, StringBuilder builder) {
  String candidate = "";
  if (component instanceof JLabel) candidate = ((JLabel)component).getText();
  if (component instanceof JTextComponent) candidate = ((JTextComponent)component).getText();
  if (component instanceof AbstractButton) candidate = ((AbstractButton)component).getText();
  if (StringUtil.isNotEmpty(candidate)) {
    candidate = candidate.replaceAll("<a href=\"#inspection/[^)]+\\)", "");
    if (builder.length() > 0) builder.append(' ');
    builder.append(StringHtmlUtil.removeHtmlTags(candidate).trim());
  }
  if (component instanceof Container) {
    Component[] components = ((Container)component).getComponents();
    for (Component child : components) {
      getAllTextsRecursivelyImpl(child, builder);
    }
  }
}
 
Example 8
Source File: HaxeLookupElement.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void renderElement(LookupElementPresentation presentation) {
  final ItemPresentation myComponentNamePresentation = myComponentName.getPresentation();
  if (myComponentNamePresentation == null) {
    presentation.setItemText(getLookupString());
    return;
  }

  String presentableText = myComponentNamePresentation.getPresentableText();

  // Check for members: methods and fields
  HaxeBaseMemberModel model = HaxeBaseMemberModel.fromPsi(myComponentName);

  if (model != null) {
    // TODO: Specialization support required
    presentableText = model.getPresentableText(context);

    // Check deprecated modifiers
    if (model instanceof HaxeMemberModel && ((HaxeMemberModel)model).getModifiers().hasModifier(HaxePsiModifier.DEPRECATED)) {
      presentation.setStrikeout(true);
    }

    // Check for non-inherited members to highlight them as intellij-java does
    // @TODO: Self members should be displayed first!
    if (leftReference != null) {
      if (model.getDeclaringClass().getPsi() == leftReference.getHaxeClass()) {
        presentation.setItemTextBold(true);
      }
    }
  }

  presentation.setItemText(presentableText);
  presentation.setIcon(myComponentNamePresentation.getIcon(true));
  final String pkg = myComponentNamePresentation.getLocationString();
  if (StringUtil.isNotEmpty(pkg)) {
    presentation.setTailText(" " + pkg, true);
  }
}
 
Example 9
Source File: PhpTypeProviderUtil.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
/**
 * Creates a signature for PhpType implementation which must be resolved inside 'getBySignature'
 *
 * eg. foo(MyClass::class) => "#F\\foo|#K#C\\Foo.class"
 *
 * foo($this->foo), foo('foobar')
 */
@Nullable
public static String getReferenceSignatureByFirstParameter(@NotNull FunctionReference functionReference, char trimKey) {
    String refSignature = functionReference.getSignature();
    if(StringUtil.isEmpty(refSignature)) {
        return null;
    }

    PsiElement[] parameters = functionReference.getParameters();
    if(parameters.length == 0) {
        return null;
    }

    PsiElement parameter = parameters[0];

    // we already have a string value
    if ((parameter instanceof StringLiteralExpression)) {
        String param = ((StringLiteralExpression)parameter).getContents();
        if (StringUtil.isNotEmpty(param)) {
            return refSignature + trimKey + param;
        }

        return null;
    }

    // whitelist here; we can also provide some more but think of performance
    // Service::NAME, $this->name and Entity::CLASS;
    if (parameter instanceof ClassConstantReference || parameter instanceof FieldReference) {
        String signature = ((PhpReference) parameter).getSignature();
        if (StringUtil.isNotEmpty(signature)) {
            return refSignature + trimKey + signature;
        }
    }

    return null;
}
 
Example 10
Source File: PackageDirectoryCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private PackageInfo getPackageInfo(@Nonnull final String packageName) {
  PackageInfo info = myDirectoriesByPackageNameCache.get(packageName);
  if (info == null) {
    if (myNonExistentPackages.contains(packageName)) return null;

    if (packageName.length() > Registry.intValue("java.max.package.name.length") || StringUtil.containsAnyChar(packageName, ";[/")) {
      return null;
    }

    List<VirtualFile> result = ContainerUtil.newSmartList();

    if (StringUtil.isNotEmpty(packageName) && !StringUtil.startsWithChar(packageName, '.')) {
      int i = packageName.lastIndexOf('.');
      while (true) {
        PackageInfo parentInfo = getPackageInfo(i > 0 ? packageName.substring(0, i) : "");
        if (parentInfo != null) {
          result.addAll(parentInfo.getSubPackageDirectories(packageName.substring(i + 1)));
        }
        if (i < 0) break;
        i = packageName.lastIndexOf('.', i - 1);
        ProgressManager.checkCanceled();
      }
    }

    for (VirtualFile file : myRootsByPackagePrefix.get(packageName)) {
      if (file.isDirectory()) {
        result.add(file);
      }
    }

    if (!result.isEmpty()) {
      myDirectoriesByPackageNameCache.put(packageName, info = new PackageInfo(packageName, result));
    } else {
      myNonExistentPackages.add(packageName);
    }
  }

  return info;
}
 
Example 11
Source File: PhpTypeProviderUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Creates a signature for PhpType implementation which must be resolved inside 'getBySignature'
 *
 * eg. foo(MyClass::class) => "#F\\foo|#K#C\\Foo.class"
 * 
 * foo($this->foo), foo('foobar')
 */
@Nullable
public static String getReferenceSignatureByFirstParameter(@NotNull FunctionReference functionReference, char trimKey) {
    String refSignature = functionReference.getSignature();
    if(StringUtil.isEmpty(refSignature)) {
        return null;
    }

    PsiElement[] parameters = functionReference.getParameters();
    if(parameters.length == 0) {
        return null;
    }

    PsiElement parameter = parameters[0];

    // we already have a string value
    if ((parameter instanceof StringLiteralExpression)) {
        String param = ((StringLiteralExpression)parameter).getContents();
        if (StringUtil.isNotEmpty(param)) {
            return refSignature + trimKey + param;
        }

        return null;
    }

    // whitelist here; we can also provide some more but think of performance
    // Service::NAME, $this->name and Entity::CLASS;
    if (parameter instanceof PhpReference && (parameter instanceof ClassConstantReference || parameter instanceof FieldReference)) {
        String signature = ((PhpReference) parameter).getSignature();
        if (StringUtil.isNotEmpty(signature)) {
            return refSignature + trimKey + signature;
        }
    }

    return null;
}
 
Example 12
Source File: PhpHeaderDocumentationProvider.java    From idea-php-advanced-autocomplete with MIT License 5 votes vote down vote up
@NotNull
private static Map<String, String> readHeaderDescriptions() {
    Map<String, String> result = ContainerUtil.newHashMap();

    // Re-use docs from JB HTTP Client plugin
    InputStream stream = PhpHeaderDocumentationProvider.class.getResourceAsStream(HEADERS_DOC_JSON);

    try {
        String file = stream != null ? FileUtil.loadTextAndClose(stream) : "";
        if (StringUtil.isNotEmpty(file)) {
            JsonElement root = (new JsonParser()).parse(file);
            if (root.isJsonArray()) {
                JsonArray array = root.getAsJsonArray();

                for (JsonElement element : array) {
                    if (element.isJsonObject()) {
                        JsonObject obj = element.getAsJsonObject();
                        String name = getAsString(obj, "name");
                        if (!StringUtil.isNotEmpty(name)) {
                            continue;
                        }
                        String description = getAsString(obj, "descr");
                        if (!StringUtil.isNotEmpty(description)) {
                            continue;
                        }
                        result.put(name, description);
                    }
                }
            }
        }
    } catch (IOException ignored) {
    }

    return result;
}
 
Example 13
Source File: PsalmValidatorConfigurationProvider.java    From idea-php-generics-plugin with MIT License 5 votes vote down vote up
protected void fillSettingsByDefaultValue(@NotNull PsalmValidatorConfiguration settings, @NotNull PsalmValidatorConfiguration localConfiguration, @NotNull NullableFunction<String, String> preparePath) {
    super.fillSettingsByDefaultValue(settings, localConfiguration, preparePath);

    String toolPath = preparePath.fun(localConfiguration.getToolPath());
    if (StringUtil.isNotEmpty(toolPath)) {
        settings.setToolPath(toolPath);
    }

    settings.setTimeout(localConfiguration.getTimeout());
}
 
Example 14
Source File: TipUIUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void openTipInBrowser(String tipFileName, JEditorPane browser, Class providerClass) {
  TipAndTrickBean tip = TipAndTrickBean.findByFileName(tipFileName);
  if (tip == null && StringUtil.isNotEmpty(tipFileName)) {
    tip = new TipAndTrickBean();
    tip.fileName = tipFileName;
  }
  openTipInBrowser(tip, browser);
}
 
Example 15
Source File: RecentLocationsRenderer.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static SimpleColoredComponent createTitleTextComponent(@Nonnull Project project,
                                                               @Nonnull JList<? extends RecentLocationItem> list,
                                                               @Nonnull SpeedSearch speedSearch,
                                                               @Nonnull IdeDocumentHistoryImpl.PlaceInfo placeInfo,
                                                               @Nonnull EditorColorsScheme colorsScheme,
                                                               @Nullable String breadcrumbText,
                                                               boolean selected) {
  SimpleColoredComponent titleTextComponent = new SimpleColoredComponent();

  String fileName = placeInfo.getFile().getName();
  String text = fileName;
  titleTextComponent.append(fileName, createFileNameTextAttributes(colorsScheme, selected));

  if (StringUtil.isNotEmpty(breadcrumbText) && !StringUtil.equals(breadcrumbText, fileName)) {
    text += " " + breadcrumbText;
    titleTextComponent.append("  ");
    titleTextComponent.append(breadcrumbText, createBreadcrumbsTextAttributes(colorsScheme, selected));
  }

  Image icon = fetchIcon(project, placeInfo);

  if (icon != null) {
    titleTextComponent.setIcon(icon);
    titleTextComponent.setIconTextGap(4);
  }

  titleTextComponent.setBorder(JBUI.Borders.empty());

  if (!SystemInfo.isWindows) {
    titleTextComponent.setFont(FontUtil.minusOne(UIUtil.getLabelFont()));
  }

  if (speedSearch.matchingFragments(text) != null) {
    SpeedSearchUtil.applySpeedSearchHighlighting(list, titleTextComponent, false, selected);
  }

  long timeStamp = placeInfo.getTimeStamp();
  if (UISettings.getInstance().getShowInplaceComments() && Registry.is("show.last.visited.timestamps") && timeStamp != -1) {
    titleTextComponent.append(" " + DateFormatUtil.formatPrettyDateTime(timeStamp), SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES);
  }

  return titleTextComponent;
}
 
Example 16
Source File: CustomizableActionsPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected boolean doSetIcon(DefaultMutableTreeNode node, @Nullable String path, Component component) {
  if (StringUtil.isNotEmpty(path) && !new File(path).isFile()) {
    Messages
      .showErrorDialog(component, IdeBundle.message("error.file.not.found.message", path), IdeBundle.message("title.choose.action.icon"));
    return false;
  }

  String actionId = getActionId(node);
  if (actionId == null) return false;

  final AnAction action = ActionManager.getInstance().getAction(actionId);
  if (action != null && action.getTemplatePresentation() != null) {
    if (StringUtil.isNotEmpty(path)) {
      Image image = null;
      try {
        image = ImageLoader.loadFromStream(VfsUtil.convertToURL(VfsUtil.pathToUrl(path.replace(File.separatorChar,
                                                                                               '/'))).openStream());
      }
      catch (IOException e) {
        LOG.debug(e);
      }
      Icon icon = new File(path).exists() ? IconLoader.getIcon(image) : null;
      if (icon != null) {
        if (icon.getIconWidth() >  EmptyIcon.ICON_18.getIconWidth() || icon.getIconHeight() > EmptyIcon.ICON_18.getIconHeight()) {
          Messages.showErrorDialog(component, IdeBundle.message("custom.icon.validation.message"), IdeBundle.message("title.choose.action.icon"));
          return false;
        }
        node.setUserObject(Pair.create(actionId, icon));
        mySelectedSchema.addIconCustomization(actionId, path);
      }
    }
    else {
      node.setUserObject(Pair.create(actionId, null));
      mySelectedSchema.removeIconCustomization(actionId);
      final DefaultMutableTreeNode nodeOnToolbar = findNodeOnToolbar(actionId);
      if (nodeOnToolbar != null){
        editToolbarIcon(actionId, nodeOnToolbar);
        node.setUserObject(nodeOnToolbar.getUserObject());
      }
    }
    return true;
  }
  return false;
}
 
Example 17
Source File: VagrantBasedCredentialsHolder.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void save(Element element) {
  element.setAttribute(VAGRANT_FOLDER, getVagrantFolder());
  if (StringUtil.isNotEmpty(getMachineName())) {
    element.setAttribute(MACHINE_NAME, getMachineName());
  }
}
 
Example 18
Source File: ExportTestResultsForm.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean shouldOpenInBrowser(String filename) {
  return StringUtil.isNotEmpty(filename) && (filename.endsWith(".html") || filename.endsWith(".htm"));
}
 
Example 19
Source File: ConsoleHistoryController.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String fixNullPersistenceId(@Nullable String persistenceId, @Nonnull LanguageConsoleView console) {
  if (StringUtil.isNotEmpty(persistenceId)) return persistenceId;
  String url = console.getProject().getPresentableUrl();
  return StringUtil.isNotEmpty(url) ? url : "default";
}
 
Example 20
Source File: LaunchState.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected RunContentDescriptor launch(@NotNull ExecutionEnvironment env) throws ExecutionException {
  FileDocumentManager.getInstance().saveAllDocuments();

  // Set our FlutterLaunchMode up in the ExecutionEnvironment.
  if (RunMode.fromEnv(env).isProfiling()) {
    FlutterLaunchMode.addToEnvironment(env, FlutterLaunchMode.PROFILE);
  }

  final Project project = getEnvironment().getProject();
  @Nullable final FlutterDevice device = DeviceService.getInstance(project).getSelectedDevice();
  if (device == null) {
    showNoDeviceConnectedMessage(project);
    return null;
  }

  final FlutterApp app = myCreateAppCallback.createApp(device);

  // Cache for use in console configuration.
  FlutterApp.addToEnvironment(env, app);

  // Remember the run configuration that started this process.
  app.getProcessHandler().putUserData(FLUTTER_RUN_CONFIG_KEY, runConfig);

  final ExecutionResult result = setUpConsoleAndActions(app);

  // For Bazel run configurations, where the console is not null, and we find the expected
  // process handler type, print the command line command to the console.
  if (runConfig instanceof BazelRunConfig &&
      app.getConsole() != null &&
      app.getProcessHandler() instanceof OSProcessHandler) {
    final String commandLineString = ((OSProcessHandler)app.getProcessHandler()).getCommandLine().trim();
    if (StringUtil.isNotEmpty(commandLineString)) {
      app.getConsole().print(commandLineString + "\n", ConsoleViewContentType.NORMAL_OUTPUT);
    }
  }

  device.bringToFront();

  // Check for and display any analysis errors when we launch an app.
  if (env.getRunProfile() instanceof SdkRunConfig) {
    final Class dartExecutionHelper = classForName("com.jetbrains.lang.dart.ide.runner.DartExecutionHelper");
    if (dartExecutionHelper != null) {
      final String message = ("<a href='open.dart.analysis'>Analysis issues</a> may affect " +
                              "the execution of '" + env.getRunProfile().getName() + "'.");
      final SdkRunConfig config = (SdkRunConfig)env.getRunProfile();
      final SdkFields sdkFields = config.getFields();
      final MainFile mainFile = MainFile.verify(sdkFields.getFilePath(), env.getProject()).get();

      DartExecutionHelper.displayIssues(project, mainFile.getFile(), message, env.getRunProfile().getIcon());
    }
  }

  final FlutterLaunchMode launchMode = FlutterLaunchMode.fromEnv(env);
  if (launchMode.supportsDebugConnection()) {
    return createDebugSession(env, app, result).getRunContentDescriptor();
  }
  else {
    return new RunContentBuilder(result, env).showRunContent(env.getContentToReuse());
  }
}