Java 类com.intellij.openapi.util.text.StringUtil 实例源码

项目:AppleScript-IDEA    文件:AppleScriptGeneratedParserUtil.java   
/**
   * If inside tell (only in a tell?) compound statement - first check it's terms
   */
  public static boolean parseExpression(PsiBuilder b, int l, String dictionaryTermToken, Parser expression) {
    if (!recursion_guard_(b, l, "parseExpression")) return false;
    if (!nextTokenIsFast(b, dictionaryTermToken)) return false;
    boolean r;

    //check application terms first
    if (b.getUserData(PARSING_TELL_COMPOUND_STATEMENT) == Boolean.TRUE) {
      String toldAppName = peekTargetApplicationName(b);
      if (!StringUtil.isEmpty(toldAppName)) {
        StringHolder parsedName = new StringHolder();
        PsiBuilder.Marker mComName = enter_section_(b, l, _AND_, "<parse Expression>");
        r = parseCommandNameForApplication(b, l + 1, parsedName, toldAppName, true);
        exit_section_(b, l, mComName, null, r, false, null);
        if (r) return false;
        if (ParsableScriptSuiteRegistryHelper.isPropertyWithPrefixExist(toldAppName, dictionaryTermToken)) {
          return false;
//          PsiBuilder.Marker m = enter_section_(b, l, _AND_, null, "<dictionary constant>");
//          r = parseDictionaryConstant(b, l + 1);
//          exit_section_(b, l, m, r, false, null);
//          if (r) return false;
        }
      }
    }
    return expression.parse(b, l + 1);
  }
项目:AppleScript-IDEA    文件:SDEF_Parser.java   
public static void parse(@NotNull XmlFile file, @NotNull ApplicationDictionary parsedDictionary) {
  System.out.println("Start parsing xml file --- " + file.toString() + " ---");
  LOG.debug("Start parsing xml file --- " + file.toString() + " ---");

  if (parsedDictionary.getRootTag() == null) {
    parsedDictionary.setRootTag(file.getRootTag());
  }
  final XmlDocument document = file.getDocument();
  if (document != null) {
    final XmlTag rootTag = document.getRootTag();
    if (rootTag != null) {
      XmlAttribute attr = rootTag.getAttribute("title");
      if ("dictionary".equals(rootTag.getName()) && attr != null) {
        String dicTitle = attr.getValue();
        if (!StringUtil.isEmpty(dicTitle)) {
          parsedDictionary.setName(dicTitle);
        }
      }
      parseRootTag(parsedDictionary, rootTag);
    }
  }
  System.out.println("parsing completed for file.");
  LOG.debug("parsing completed for file.");
}
项目:AppleScript-IDEA    文件:SDEF_Parser.java   
@NotNull
private static List<AppleScriptPropertyDefinition> getPropertiesFromTags(@NotNull DictionaryComponent classOrRecord,
                                                                         @NotNull XmlTag[] propertyTags) {
  if (!(classOrRecord instanceof AppleScriptClass) && !(classOrRecord instanceof DictionaryRecord))
    return new ArrayList<>(0);

  List<AppleScriptPropertyDefinition> properties = new ArrayList<>(propertyTags.length);
  for (XmlTag propTag : propertyTags) {
    AppleScriptPropertyDefinition property;
    String pName = propTag.getAttributeValue("name");
    String pCode = propTag.getAttributeValue("code");
    String pDescription = propTag.getAttributeValue("description");
    String pType = propTag.getAttributeValue("type");
    if (StringUtil.isEmpty(pType)) {
      XmlTag tType = propTag.findFirstSubTag("type");
      pType = tType != null ? tType.getAttributeValue("type") : null;
    }
    String pAccessType = propTag.getAttributeValue("access");
    AccessType accessType = "r".equals(pAccessType) ? AccessType.R : AccessType.RW;
    if (pName != null && pCode != null && pType != null) {
      property = new DictionaryPropertyImpl(classOrRecord, pName, pCode, pType, pDescription, propTag, accessType);
      properties.add(property);
    }
  }
  return properties;
}
项目:AppleScript-IDEA    文件:DictionaryClass.java   
public DictionaryClass(@NotNull Suite suite, @NotNull String name, @NotNull String code,
                       @NotNull XmlTag xmlTagClass, @Nullable String parentClassName,
                       @Nullable List<String> elementNames, @Nullable List<String> respondingCommandNames,
                       @Nullable String pluralClassName) {
  super(suite, name, code, xmlTagClass, null);
  this.parentClassName = parentClassName;
  this.pluralClassName = StringUtil.isEmpty(pluralClassName) ? name + "s" : pluralClassName;
  if (elementNames != null) {
    this.elementNames = elementNames;
  } else {
    this.elementNames = new ArrayList<>();
  }
  if (respondingCommandNames != null) {
    this.respondingCommandNames = respondingCommandNames;
  } else {
    this.respondingCommandNames = new ArrayList<>();
  }
}
项目:AppleScript-IDEA    文件:AppleScriptLineMarkerProvider.java   
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element,
                                        @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
  if (element instanceof AppleScriptApplicationReference) {
    PsiElement leafNode = PsiTreeUtil.firstChild(element);
    if (leafNode == null) return;
    AppleScriptProjectDictionaryService dictionaryService = ServiceManager.getService(element.getProject(),
        AppleScriptProjectDictionaryService.class);
    AppleScriptApplicationReference appRef = (AppleScriptApplicationReference) element;
    String appName = appRef.getApplicationName();
    if (dictionaryService == null || StringUtil.isEmpty(appName)) return;
    ApplicationDictionary dictionary = dictionaryService.getDictionary(appName);
    if (dictionary == null /*|| dictionary.getApplicationBundle() == null*/) return;

    NavigationGutterIconBuilder<PsiElement> builder =
        NavigationGutterIconBuilder.create(dictionary.getIcon(0)).
            setTargets(dictionary).setTooltipText("Navigate to application dictionary file");
    result.add(builder.createLineMarkerInfo(leafNode));

  }
}
项目:AppleScript-IDEA    文件:AppleScriptSystemDictionaryRegistryService.java   
/**
 * Fill {@link #dictionaryInfoMap} from saved data
 *
 * @param systemDictionaryRegistry application component, which saves/loads the data
 */
private void initDictionariesInfoFromCache(@NotNull AppleScriptSystemDictionaryRegistryComponent systemDictionaryRegistry) {
  notScriptableApplicationList.addAll(systemDictionaryRegistry.getNotScriptableApplications());
  for (DictionaryInfo.State dInfoState : systemDictionaryRegistry.getDictionariesPersistedInfo()) {
    String appName = dInfoState.applicationName;
    String dictionaryUrl = dInfoState.dictionaryUrl;
    String applicationUrl = dInfoState.applicationUrl;
    if (!StringUtil.isEmptyOrSpaces(appName) && !StringUtil.isEmptyOrSpaces(dictionaryUrl)) {
      File dictionaryFile = !StringUtil.isEmpty(dictionaryUrl) ? new File(dictionaryUrl) : null;
      File applicationFile = !StringUtil.isEmpty(applicationUrl) ? new File(applicationUrl) : null;
      if (dictionaryFile != null && dictionaryFile.exists()) {
        DictionaryInfo dInfo = new DictionaryInfo(appName, dictionaryFile, applicationFile);
        addDictionaryInfo(dInfo);
      }
    }
  }
}
项目:AppleScript-IDEA    文件:AppleScriptSystemDictionaryRegistryService.java   
/**
 * Initializes dictionary information for given application either from previously generated and saved dictionary
 * file or creates new dictionary file for this application and saves it for later use <br> by
 * {@link ApplicationDictionary} psi class. Standard folders are checked when searching for application's location
 *
 * @param applicationName Name of the Mac OS application
 * @return {@link DictionaryInfo} of the generated and cached dictionary for the application
 */
@Nullable
public DictionaryInfo getInitializedInfo(@NotNull final String applicationName) {
  if (StringUtil.isEmptyOrSpaces(applicationName) || isNotScriptable(applicationName) || isInUnknownList(applicationName)) return null;

  final DictionaryInfo savedDictionaryInfo = getDictionaryInfo(applicationName);
  if (savedDictionaryInfo != null) {
    if (savedDictionaryInfo.isInitialized() || initializeDictionaryFromInfo(savedDictionaryInfo)) {
      return savedDictionaryInfo;
    }
  }
  final File appFile = findApplicationBundleFile(applicationName);
  if (appFile != null) {
    return createAndInitializeInfo(appFile, applicationName);
  }
  return null;
}
项目:AppleScript-IDEA    文件:AppleScriptSystemDictionaryRegistryService.java   
private void parseClassElement(@NotNull String applicationName, @NotNull Element classElement, boolean isExtends) {
//    if isExtends -> name is always == "application"
    String className = isExtends ? classElement.getAttributeValue("extends") : classElement.getAttributeValue("name");
    String code = classElement.getAttributeValue("code");
    String pluralClassName = classElement.getAttributeValue("plural");
    if (className == null || code == null) return;
    pluralClassName = !StringUtil.isEmpty(pluralClassName) ? pluralClassName : className + "s";

    updateObjectNameSetForApplication(className, applicationName, applicationNameToClassNameSetMap);
    updateObjectNameSetForApplication(pluralClassName, applicationName, applicationNameToClassNamePluralSetMap);
    if (ApplicationDictionary.SCRIPTING_ADDITIONS_LIBRARY.equals(applicationName)) {
      updateApplicationNameSetFor(className, applicationName, stdClassNameToApplicationNameSetMap);
      updateApplicationNameSetFor(pluralClassName, applicationName, stdClassNamePluralToApplicationNameSetMap);
    }
  }
项目:AppleScript-IDEA    文件:AppleScriptRunConfiguration.java   
@Override
public void readExternal(Element element) throws InvalidDataException {
  super.readExternal(element);
  String scriptUrl = element.getAttributeValue(SCRIPT_PATH_URL);
  String scriptParams = element.getAttributeValue(SCRIPT_PARAMETERS);
  String scriptOptions = element.getAttributeValue(SCRIPT_OPTIONS);
  String logEvents = element.getAttributeValue(SCRIPT_SHOW_EVENTS);
  if (!StringUtil.isEmpty(scriptUrl)) {
    scriptPath = scriptUrl;
  }
  if (!StringUtil.isEmpty(scriptParams)) {
    scriptParameters = scriptParams;
  }
  if (!StringUtil.isEmpty(scriptOptions)) {
    this.scriptOptions = scriptOptions;
  }
  if (!StringUtil.isEmpty(logEvents)) myShowAppleEvents = "true".equals(logEvents);
}
项目:AppleScript-IDEA    文件:AppleScriptRunSettingsEditor.java   
@Override
protected void resetEditorFrom(AppleScriptRunConfiguration configuration) {
  String scriptPath = configuration.getScriptPath();
  String scriptParameters = configuration.getScriptParameters();
  String scriptOptions = configuration.getScriptOptions();
  boolean showAppleEvents = configuration.isShowAppleEvents();
  if (!StringUtil.isEmpty(scriptPath)) {
    scriptTextField.setText(scriptPath);
    String[] parts = scriptPath.split("/");
    if (parts.length > 0) {
      runConfiguration.setName(parts[parts.length - 1]);
    }
  }
  if (!StringUtil.isEmpty(scriptParameters)) {
    parametersTextField.setText(scriptParameters);
  }
  if (!StringUtil.isEmpty(scriptOptions)) {
    scriptOptionsTextField.setText(scriptOptions);
  }
  showAppleEventsCheckBox.setSelected(showAppleEvents);
}
项目:AppleScript-IDEA    文件:ApplicationDictionaryImpl.java   
public ApplicationDictionaryImpl(@NotNull Project project, @NotNull XmlFile dictionaryXmlFile,
                                 @NotNull String applicationName, @Nullable File applicationBundleFile) {
  this.project = project;
  this.dictionaryFile = dictionaryXmlFile.getVirtualFile();
  readDictionaryFromXmlFile(dictionaryXmlFile);
  this.applicationName = applicationName;
  if (applicationBundleFile != null) {
    this.applicationBundleFile = applicationBundleFile;
    setIconFromBundle(applicationBundleFile);
  }
  if (StringUtil.isEmpty(dictionaryName))
    dictionaryName = this.applicationName;
  LOG.info("Dictionary [" + dictionaryName + "] for application [" + this.applicationName + "] " +
          "initialized In project[" + project.getName() + "] " + " Commands: " + dictionaryCommandMap.size() +
          ". " + "Classes: " + dictionaryClassMap.size());
}
项目:magento2-phpstorm-plugin    文件:PhpServiceMethodReferenceProvider.java   
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    if (!(element instanceof XmlElement)) {
        return PsiReference.EMPTY_ARRAY;
    }

    List<PsiReference> psiReferences = new ArrayList<>();

    String methodName = StringUtil.unquoteString(element.getText());

    PhpClass phpClass = DiIndex.getPhpClassOfServiceMethod((XmlElement) element);
    if (phpClass != null) {
        Collection<Method> methods = phpClass.getMethods();
        methods.removeIf(m -> !m.getName().equalsIgnoreCase(methodName));
        psiReferences.add(new PolyVariantReferenceBase(element, methods));
    }

    return psiReferences.toArray(new PsiReference[psiReferences.size()]);
}
项目:magento2-phpstorm-plugin    文件:VirtualTypeReferenceProvider.java   
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {

    String value = StringUtil.unquoteString(element.getText());

    DiIndex index = DiIndex.getInstance(element.getProject());
    Collection<PsiElement> targets = index.getVirtualTypeElements(value, element.getResolveScope());

    if (!(targets.size() > 0)) {
        return PsiReference.EMPTY_ARRAY;
    }

    return new PsiReference[] {
            new PolyVariantReferenceBase(element, targets)
    };
}
项目:magento2-phpstorm-plugin    文件:EventDispatchReferenceProvider.java   
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<PsiElement> targets = EventIndex.getInstance(element.getProject())
            .getEventElements(
                    value,
                    GlobalSearchScope.getScopeRestrictedByFileTypes(
                            GlobalSearchScope.allScope(element.getProject()),
                            XmlFileType.INSTANCE
                    )
    );

    if (targets.size() > 0) {
        return new PsiReference[] {new PolyVariantReferenceBase(element, targets)};
    }
    return PsiReference.EMPTY_ARRAY;
}
项目:magento2-phpstorm-plugin    文件:EventNameReferenceProvider.java   
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(EventNameIndex.KEY, value,
                GlobalSearchScope.getScopeRestrictedByFileTypes(
                        GlobalSearchScope.allScope(element.getProject()),
                        PhpFileType.INSTANCE
                )
        );

    PsiManager psiManager = PsiManager.getInstance(element.getProject());
    for (VirtualFile virtualFile: containingFiles) {
        PhpFile phpFile = (PhpFile) psiManager.findFile(virtualFile);
        if (phpFile != null) {
            List<PsiElement> psiElements = new ArrayList<>();
            recursiveFill(psiElements, phpFile, value);
            if (psiElements.size() > 0) {
                return new PsiReference[] {new PolyVariantReferenceBase(element, psiElements)};
            }
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
项目:jfrog-idea-plugin    文件:XrayGlobalConfiguration.java   
public XrayGlobalConfiguration() {
    testConnectionButton.addActionListener(e -> ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {
            connectionResults.setText("Connecting to Xray...");
            config.validate();
            config.repaint();
            // use as a workaround to version not being username password validated
            Xray xrayClient = XrayClient.create(StringUtil.trim(url.getText()), StringUtil.trim(username.getText()), String.valueOf(password.getPassword()), USER_AGENT);
            Version xrayVersion = xrayClient.system().version();

            if (!Utils.isXrayVersionSupported(xrayVersion)) {
                connectionResults.setText("ERROR: Unsupported Xray version: " + xrayVersion.getVersion() +
                        ", version above " + MINIMAL_XRAY_VERSION_SUPPORTED + " and below " + MINIMAL_XRAY_VERSION_UNSUPPORTED + " is required.");
            } else {
                Pair<Boolean, String> testComponentPermissionRes = testComponentPermission(xrayClient);
                if (!testComponentPermissionRes.getLeft()) {
                    throw new IOException(testComponentPermissionRes.getRight());
                }
                connectionResults.setText("Successfully connected to Xray version: " + xrayVersion.getVersion());
            }
        } catch (IOException | IllegalArgumentException e1) {
            connectionResults.setText("Could not connect to Xray: " + e1.getMessage());
        }
    }));
}
项目:hybris-integration-intellij-idea-plugin    文件:AbstractSelectModulesToImportStep.java   
protected boolean validateCommon() throws ConfigurationException {
    final Set<HybrisModuleDescriptor> moduleDuplicates = this.calculateSelectedModuleDuplicates();
    final Collection<String> moduleDuplicateNames = newHashSet(moduleDuplicates.size());

    for (HybrisModuleDescriptor moduleDuplicate : moduleDuplicates) {
        moduleDuplicateNames.add(this.getModuleNameAndPath(moduleDuplicate));
    }

    if (!moduleDuplicates.isEmpty()) {
        throw new ConfigurationException(
            HybrisI18NBundleUtils.message(
                "hybris.project.import.duplicate.projects.found",
                StringUtil.join(ArrayUtil.toStringArray(moduleDuplicateNames), "\n")
            ),
            HybrisI18NBundleUtils.message("hybris.project.error")
        );
    }

    return true;
}
项目:hybris-integration-intellij-idea-plugin    文件:TSMetaModelImpl.java   
@Nullable
TSMetaEnumImpl findOrCreateEnum(final @NotNull EnumType domEnumType) {
    final String name = TSMetaEnumImpl.extractName(domEnumType);
    if (StringUtil.isEmpty(name)) {
        return null;
    }
    final NoCaseMap<TSMetaEnumImpl> enums = getEnums();
    TSMetaEnumImpl impl = enums.get(name);
    if (impl == null) {
        impl = new TSMetaEnumImpl(name, domEnumType);
        enums.put(name, impl);
    } else {
        //report a problem
    }
    return impl;
}
项目:ApkMultiChannelPlugin    文件:OptionsHelper.java   
public static boolean verify(Options options) {
    String message = null;
    if (StringUtil.isEmpty(options.keyStorePath)) {
        message = "Please choose a keystore file";
    } else if (StringUtil.isEmpty(options.keyStorePassword)) {
        message = "Please enter the keystore password";
    } else if (StringUtil.isEmpty(options.keyPassword)) {
        message = "Please enter the key password";
    } else if (StringUtil.isEmpty(options.keyAlias)) {
        message = "Please enter the key alias";
    } else if (options.channels.size() == 0) {
        message = "Please enter channels";
    } else if (StringUtil.isEmpty(options.zipalignPath)) {
        message = "Please choose a zipalign file";
    } else if (StringUtil.isEmpty(options.signer)) {
        message = "Please choose a signer";
    } else if (StringUtil.isEmpty(options.buildType)) {
        message = "Please choose a build type";
    }

    boolean success = message == null;
    if (!success) {
        NotificationHelper.error(message);
    }
    return success;
}
项目:hybris-integration-intellij-idea-plugin    文件:ValidateContextImpl.java   
private Attr createAndAppendAttribute(
    @NotNull final Element owner,
    @NotNull final Attributes attrs,
    final int idx
) {
    final String localName = attrs.getLocalName(idx);
    final Attr result;
    if (StringUtil.isEmpty(localName)) {
        result = this.myDoc.createAttribute(attrs.getQName(idx));
        owner.setAttributeNode(result);
    } else {
        result = this.myDoc.createAttributeNS(attrs.getURI(idx), localName);
        owner.setAttributeNodeNS(result);
    }
    return result;
}
项目:hybris-integration-intellij-idea-plugin    文件:TypeSystemGutterAnnotator.java   
private static Collection<XmlAttributeValue> findAlternativeDoms(@NotNull final ItemType source) {
    final String code = source.getCode().getStringValue();

    if (StringUtil.isEmpty(code)) {
        return Collections.emptyList();
    }
    final XmlElement element = source.getXmlElement();
    final PsiFile psiFile = element == null ? null : element.getContainingFile();

    if (psiFile == null) {
        return Collections.emptyList();
    }
    final TSMetaModel externalModel = TSMetaModelAccess.getInstance(psiFile.getProject()).
        getExternalTypeSystemMeta(psiFile);

    return Optional.ofNullable(externalModel.findMetaClassForDom(source))
                   .map(TSMetaClass::retrieveAllDomsStream)
                   .orElse(Stream.empty())
                   .filter(dom -> !dom.equals(source))
                   .map(ItemType::getCode)
                   .map(GenericAttributeValue::getXmlAttributeValue)
                   .collect(Collectors.toList());
}
项目:hybris-integration-intellij-idea-plugin    文件:TypeSystemGutterAnnotator.java   
@NotNull
private static Stream<TSMetaClass> getExtendingMetaClassNamesStream(@NotNull final ItemType source) {
    final String code = source.getCode().getStringValue();

    if (StringUtil.isEmpty(code)) {
        return Stream.empty();
    }
    final XmlElement xmlElement = source.getXmlElement();
    final PsiFile psiFile = xmlElement == null ? null : xmlElement.getContainingFile();

    if (psiFile == null) {
        return Stream.empty();
    }
    final TSMetaModel metaModel = TSMetaModelAccess.getInstance(psiFile.getProject()).getTypeSystemMeta(psiFile);
    final TSMetaClass sourceMeta = metaModel.findMetaClassForDom(source);

    if (sourceMeta == null) {
        return Stream.empty();
    }
    return metaModel
        .getMetaClassesStream()
        .map(TSMetaClass.class::cast)
        .filter(meta -> sourceMeta.getName().equals(meta.getExtendedMetaClassName()));
}
项目:IntelliJ-Key-Promoter-X    文件:KeyPromoter.java   
private void showTip(KeyPromoterAction action) {
    if (action == null || !action.isValid() || statsService.isSuppressed(action)) {
        return;
    }

    final String shortcut = action.getShortcut();
    if (!StringUtil.isEmpty(shortcut)) {
        statsService.registerAction(action);
        KeyPromoterNotification.showTip(action, statsService.get(action).getCount());

    } else {
        final String ideaActionID = action.getIdeaActionID();
        withoutShortcutStats.putIfAbsent(ideaActionID, 0);
        withoutShortcutStats.put(ideaActionID, withoutShortcutStats.get(ideaActionID) + 1);
        if (keyPromoterSettings.getProposeToCreateShortcutCount() > 0 && withoutShortcutStats.get(ideaActionID) % keyPromoterSettings.getProposeToCreateShortcutCount() == 0) {
            KeyPromoterNotification.askToCreateShortcut(action);

        }
    }
}
项目:educational-plugin    文件:EduStepicConnector.java   
static void addAvailableCourses(List<Course> result, StepicWrappers.CoursesContainer coursesContainer) throws IOException {
  final List<RemoteCourse> courses = coursesContainer.courses;
  for (RemoteCourse info : courses) {
    if (!info.isAdaptive() && StringUtil.isEmptyOrSpaces(info.getType())) continue;
    setCourseLanguage(info);

    if (canBeOpened(info)) {
      final ArrayList<StepicUser> authors = new ArrayList<>();
      for (Integer instructor : info.getInstructors()) {
        final StepicUser author = EduStepicClient.getFromStepic(EduStepicNames.USERS + String.valueOf(instructor),
                                                                StepicWrappers.AuthorWrapper.class).users.get(0);
        authors.add(author);
      }
      info.setAuthors(authors);

      if (info.isAdaptive()) {
        info.setDescription("This is a Stepik Adaptive course.\n\n" + info.getDescription() + ADAPTIVE_NOTE);
      }
      result.add(info);
    }
  }
}
项目:educational-plugin    文件:EduAdaptiveStepicConnector.java   
private static StudyCheckResult doAdaptiveCheck(@NotNull StepicWrappers.SubmissionToPostWrapper submission,
                                                     int attemptId, int userId) {
  final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
  if (client != null) {
    StepicWrappers.ResultSubmissionWrapper wrapper = postResultsForCheck(client, submission);
    if (wrapper != null) {
      wrapper = getCheckResults(client, wrapper, attemptId, userId);
      if (wrapper.submissions.length > 0) {
        final String status = wrapper.submissions[0].status;
        final String hint = wrapper.submissions[0].hint;
        final boolean isSolved = !status.equals("wrong");
        return new StudyCheckResult(isSolved ? StudyStatus.Solved : StudyStatus.Failed, hint.isEmpty() ? StringUtil.capitalize(status) + " solution" : hint);
      }
      else {
        LOG.warn("Got a submission wrapper with incorrect submissions number: " + wrapper.submissions.length);
      }
    }
    else {
      LOG.warn("Can't do adaptive check: " + "wrapper is null");
      return new StudyCheckResult(StudyStatus.Unchecked, "Can't get check results for Stepik");
    }
  }
  return new StudyCheckResult(StudyStatus.Unchecked, StudyCheckAction.FAILED_CHECK_LAUNCH);
}
项目:educational-plugin    文件:CCEditAnswerPlaceholder.java   
@Override
protected void performAnswerPlaceholderAction(@NotNull CCState state) {
  final Project project = state.getProject();
  PsiFile file = state.getFile();
  final PsiDirectory taskDir = file.getContainingDirectory();
  final PsiDirectory lessonDir = taskDir.getParent();
  if (lessonDir == null) return;
  AnswerPlaceholder answerPlaceholder = state.getAnswerPlaceholder();
  if (answerPlaceholder == null) {
    return;
  }
  CCCreateAnswerPlaceholderDialog dlg = new CCCreateAnswerPlaceholderDialog(project, answerPlaceholder.getTaskText(), answerPlaceholder.getHints());
  dlg.setTitle("Edit Answer Placeholder");
  if (dlg.showAndGet()) {
    final String answerPlaceholderText = dlg.getTaskText();
    answerPlaceholder.setTaskText(answerPlaceholderText);
    answerPlaceholder.setLength(answerPlaceholder.getActiveSubtaskInfo().isNeedInsertText() ? 0 : StringUtil.notNullize(answerPlaceholderText).length());
    answerPlaceholder.setHints(dlg.getHints());
  }
}
项目:educational-plugin    文件:CCChangePlaceholderVisibility.java   
private static void saveIndent(AnswerPlaceholder placeholder, CCState state, boolean visible) {
  Document document = state.getEditor().getDocument();
  int offset = placeholder.getOffset();
  int lineNumber = document.getLineNumber(offset);
  int nonSpaceCharOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, lineNumber);
  int newOffset = offset;
  int endOffset = offset + placeholder.getRealLength();
  if (!visible && nonSpaceCharOffset == offset) {
    newOffset = document.getLineStartOffset(lineNumber);
  }
  if (visible) {
    newOffset = DocumentUtil.getFirstNonSpaceCharOffset(document, offset, endOffset);
  }
  placeholder.setOffset(newOffset);
  int delta = offset - newOffset;
  placeholder.setPossibleAnswer(document.getText(TextRange.create(newOffset, newOffset + delta + placeholder.getRealLength())));
  String oldTaskText = placeholder.getTaskText();
  if (delta >= 0) {
    placeholder.setTaskText(StringUtil.repeat(" ", delta) + oldTaskText);
  }
  else {
    String newTaskText = oldTaskText.substring(Math.abs(delta));
    placeholder.setTaskText(newTaskText);
  }
}
项目:educational-plugin    文件:CCGetCourseFromStepic.java   
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (view == null || project == null) {
    return;
  }
  final String courseId = Messages.showInputDialog("Please, enter course id", "Get Course From Stepik", null);
  if (StringUtil.isNotEmpty(courseId)) {
    ProgressManager.getInstance().run(new Task.Modal(project, "Creating Course", true) {
      @Override
      public void run(@NotNull final ProgressIndicator indicator) {
        createCourse(project, courseId);
      }
    });
  }
}
项目:MultiHighlight    文件:MultiHighlightHandler.java   
private static void searchSelection(Editor editor, Project project) {
    final SelectionModel selectionModel = editor.getSelectionModel();
    if (!selectionModel.hasSelection()) {
        selectionModel.selectWordAtCaret(false);
    }

    final String text = selectionModel.getSelectedText();
    if (text == null) {
        return;
    }

    if (editor instanceof EditorWindow) {
        // highlightUsages selection in the whole editor, not injected fragment only
        editor = ((EditorWindow) editor).getDelegate();
    }

    EditorSearchSession oldSearch = EditorSearchSession.get(editor);
    if (oldSearch != null) {
        if (oldSearch.hasMatches()) {
            String oldText = oldSearch.getTextInField();
            if (!oldSearch.getFindModel().isRegularExpressions()) {
                oldText = StringUtil.escapeToRegexp(oldText);
                oldSearch.getFindModel().setRegularExpressions(true);
            }

            String newText = oldText + '|' + StringUtil.escapeToRegexp(text);
            oldSearch.setTextInField(newText);
            return;
        }
    }

    EditorSearchSession.start(editor, project).getFindModel().setRegularExpressions(false);
}
项目:mybatis-log-plugin    文件:GoogleTranslateAction.java   
public void actionPerformed(AnActionEvent var1) {
    DataContext var2 = var1.getDataContext();
    CopyProvider var3 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var2);
    if (var3 != null) {
        var3.performCopy(var2);
        String var4 = (String) CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
        if (StringUtil.isNotEmpty(var4)) {
            BrowserUtil.browse("https://translate.google.com/#en/zh-CN/" + URLEncoder.encode(var4));
        }
    }
}
项目:mybatis-log-plugin    文件:BaiduSearchAction.java   
public void actionPerformed(AnActionEvent var1) {
    DataContext var2 = var1.getDataContext();
    CopyProvider var3 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var2);
    if (var3 != null) {
        var3.performCopy(var2);
        String var4 = (String) CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
        if (StringUtil.isNotEmpty(var4)) {
            BrowserUtil.browse("https://www.baidu.com/s?wd=" + URLEncoder.encode(var4));
        }
    }
}
项目:AppleScript-IDEA    文件:AppleScriptGeneratedParserUtil.java   
/**
 * Add application name from this &lt;use statement&gt; to the set of application names from dictionary of which to
 * import terms if importing condition is not explicitly prohibited by syntax
 *
 * @param b           {@link PsiBuilder}
 * @param l           level deep
 * @param isImporting whether to make terms from this application's dictionary available in the script
 * @return true if this is application reference
 */
public static boolean parseUsedApplicationNameExternal(PsiBuilder b, int l, Parser isImporting) {
  if (!recursion_guard_(b, l, "parseUsedApplicationNameExternal")) return false;
  boolean r;
  if (!nextTokenIs(b, "parseUsedApplicationNameExternal", APPLICATION, APP, SCRIPTING_ADDITIONS)) return false;
  String appName = null;
  r = consumeToken(b, SCRIPTING_ADDITIONS);
  if (r) {
    appName = ApplicationDictionary.SCRIPTING_ADDITIONS_LIBRARY;
  } else {
    PsiBuilder.Marker mAppRef = enter_section_(b, l, _NONE_, "<application reference>");
    PsiBuilder.Marker mCls = enter_section_(b, l, _NONE_, "<dictionary class name>");
    r = consumeToken(b, APPLICATION);
    if (!r) r = consumeToken(b, APP);
    exit_section_(b, l, mCls, DICTIONARY_CLASS_NAME, r, false, null);
    if (r) {
      String appNameStr = b.getTokenText();
      r = consumeToken(b, STRING_LITERAL);
      if (r && !StringUtil.isEmpty(appNameStr)) {
        appName = appNameStr.replace("\"", "");
      }
    }
    exit_section_(b, l, mAppRef, APPLICATION_REFERENCE, r, false, null);
  }
  boolean doTermsImport = isImporting.parse(b, l + 1);
  if (doTermsImport && !StringUtil.isEmpty(appName)) {
    Set<String> usedAppNames = b.getUserData(USED_APPLICATION_NAMES);
    if (usedAppNames == null) {
      usedAppNames = new HashSet<>();
      b.putUserData(USED_APPLICATION_NAMES, usedAppNames);
    }
    usedAppNames.add(appName);
  }
  return r;
}
项目:AppleScript-IDEA    文件:AppleScriptGeneratedParserUtil.java   
/**
 * @param b                           {@link PsiBuilder}
 * @param l                           Level deep
 * @param tellStatementStartCondition If this is the application reference of a &lt;tell&gt; or &lt;using terms
 *                                    from&gt; statements
 * @return true if parsed
 */
public static boolean parseApplicationName(PsiBuilder b, int l, Parser tellStatementStartCondition) {
  if (!recursion_guard_(b, l, "parseApplicationName")) return false;
  boolean r;
  consumeToken(b, THE_KW);
  if (!nextTokenIs(b, "", APPLICATION, APP)) return false;

  PsiBuilder.Marker mCls = enter_section_(b, l, _NONE_, "<parse application name>");
  r = consumeToken(b, APPLICATION);
  if (!r) r = consumeToken(b, APP);
  exit_section_(b, l, mCls, DICTIONARY_CLASS_NAME, r, false, null);

  if (!nextTokenIs(b, "", STRING_LITERAL, ID)) return false;
  PsiBuilder.Marker mProp = enter_section_(b, l, _NONE_, "<parse application name>");
  boolean idReference = consumeToken(b, ID);
  exit_section_(b, l, mProp, DICTIONARY_PROPERTY_NAME, idReference, false, null);
  PsiBuilder.Marker m = enter_section_(b);
  String applicationNameString = b.getTokenText();
  r = consumeToken(b, STRING_LITERAL);

  // if this is start of <tell compound> or <tell simple> or <using terms from> statements, push the application name
  // which dictionary will be consulted for terms parsing (only the last pushed application is queried)
  if (r && applicationNameString != null) {
    applicationNameString = applicationNameString.replace("\"", "");
    if (!StringUtil.isEmptyOrSpaces(applicationNameString) && tellStatementStartCondition.parse(b, l + 1)) {
      pushTargetApplicationName(b, applicationNameString);
    }
  }
  exit_section_(b, m, null, r);
  return r;
}
项目:AppleScript-IDEA    文件:SDEF_Parser.java   
private static void processIncludes(@NotNull ApplicationDictionary parsedDictionary, @Nullable XmlTag[] includes) {
    if (includes == null) return;
    for (XmlTag include : includes) {
      String hrefIncl = include.getAttributeValue("href");
      if (!StringUtil.isEmpty(hrefIncl)) {
        hrefIncl = hrefIncl.replace("file://localhost", "");
        File includedFile = new File(hrefIncl);
//        ((IncludedXmlTag) suiteTag).getOriginal().getContainingFile();
        //as there is assertion error (java.lang.AssertionError: File accessed outside allowed roots),
        // we are trying to find if the dictionary file for this included dictionary was already generated
        AppleScriptSystemDictionaryRegistryService dictionarySystemRegistry = ServiceManager
            .getService(AppleScriptSystemDictionaryRegistryService.class);
        VirtualFile vFile;
        File ioFile = null;
        DictionaryInfo dInfo = dictionarySystemRegistry.getDictionaryInfoByApplicationPath(includedFile.getPath());
        if (dInfo != null) {
          ioFile = dInfo.getDictionaryFile();
        } else if (includedFile.isFile()) {
          String fName = includedFile.getName();
          int index = fName.lastIndexOf('.');
          fName = index < 0 ? fName : fName.substring(0, index);
          ioFile = dictionarySystemRegistry.getDictionaryFile(fName);
        }
        if (ioFile == null || !ioFile.exists()) ioFile = includedFile;
        if (ioFile.exists()) {
          vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile);
          if (vFile == null || !vFile.isValid()) continue;

          PsiFile psiFile = PsiManager.getInstance(parsedDictionary.getProject()).findFile(vFile);
          XmlFile xmlFile = (XmlFile) psiFile;
          if (xmlFile != null) {
            parsedDictionary.processInclude(xmlFile);
          }
        }
      }
    }
  }
项目:AppleScript-IDEA    文件:SDEF_Parser.java   
private static AppleScriptClass parseClassTag(XmlTag classTag, Suite suite) {
  String name = classTag.getAttributeValue("name");
  String code = classTag.getAttributeValue("code");
  String pluralName = classTag.getAttributeValue("plural");

  if (name == null || code == null) return null;

  String parentClassName = classTag.getAttributeValue("inherits");
  List<String> elementNames = initClassElements(classTag);
  List<String> respondingCommands = initClassRespondingMessages(classTag);


  final AppleScriptClass aClass = new DictionaryClass(suite, name, code, classTag, parentClassName, elementNames,
      respondingCommands, pluralName);
  String description = classTag.getAttributeValue("description");
  aClass.setDescription(description);
  XmlTag[] propertyTags = classTag.findSubTags("property");
  final List<AppleScriptPropertyDefinition> properties = new ArrayList<>();
  for (XmlTag propTag : propertyTags) {
    String pName = propTag.getAttributeValue("name");
    String pCode = propTag.getAttributeValue("code");
    String pDescription = propTag.getAttributeValue("description");
    String pType = propTag.getAttributeValue("type");
    if (StringUtil.isEmpty(pType)) {
      XmlTag tType = propTag.findFirstSubTag("type");
      pType = tType != null ? tType.getAttributeValue("type") : null;
    }
    String pAccessType = propTag.getAttributeValue("access");
    AccessType accessType = "r".equals(pAccessType) ? AccessType.R : AccessType.RW;
    if (pName != null && pCode != null && pType != null) {
      final AppleScriptPropertyDefinition property = new DictionaryPropertyImpl(aClass, pName, pCode, pType,
          pDescription, propTag, accessType);
      properties.add(property);
    }
  }
  aClass.setProperties(properties);
  return aClass;
}
项目:AppleScript-IDEA    文件:AbstractDictionaryComponent.java   
protected String getTypeDescription() {
  StringBuilder sb = new StringBuilder();
  sb.append("<p>");
  String type = StringUtil.capitalizeWords(getType(), true);
  sb.append(type.toLowerCase().contains("dictionary") ? type.substring(10) : type).append(" <b>").append(name).append("</b>");
  if (this instanceof AppleScriptClass) {
    AppleScriptClass parentClass = ((AppleScriptClass) this).getParentClass();
    if (parentClass != null) {
      sb.append(" [inh. ");
      String ext = "";
      int recursionGuard = 15;
      do {
        recursionGuard--;
        sb.append(ext);
        AppleScriptDocHelper.appendElementLink(sb, parentClass, parentClass.getName());
        parentClass = parentClass.getParentClass();
        ext = " > ";
      } while (parentClass != null && recursionGuard > 0);
      sb.append(" ]");
    }
  } else if (this instanceof CommandParameter) {
    CommandParameter param = (CommandParameter) this;
    String pType = StringUtil.notNullize(param.getTypeSpecifier());
    sb.append(" [").append(pType).append("]");
  }
  sb.append(" : ").append(StringUtil.notNullize(getDescription()));
  return sb.toString();
}
项目:AppleScript-IDEA    文件:AppleScriptCommandImpl.java   
@Override
  protected String getDocFooter() {
    StringBuilder sb = new StringBuilder();
    final String indent = "&nbsp;&nbsp;&nbsp;&nbsp;";
    CommandDirectParameter p = getDirectParameter();
    List<CommandParameter> parameters = getParameters();
    if (p != null || !parameters.isEmpty()) {
      sb.append("<p><b>Parameters:</b></p>");
    }
    if (p != null)
      sb.append(indent).append(indent).append(p.getTypeSpecifier()).append(" : ")
          .append(StringUtil.notNullize(p.getDescription())).append("<br>");

    for (CommandParameter par : parameters) {
      String op = "";
      String cl = "";
      if (par.isOptional()) {
        op = "[";
        cl = "]";
      }
      String pType = StringUtil.notNullize(par.getTypeSpecifier());
      sb.append(indent).append(indent).append(op).append("<b>").append(par.getName()).append("</b> ").append(pType)
          .append(cl).append(" : ").append(par.getDescription()).append("<br>");
    }
    CommandResult res = getResult();
    if (res != null) {
      sb.append("<p>").append("<b>Returns:</b></p>").append(indent).append(indent).
          append(res.getType()).append(" : ").append(StringUtil.notNullize(res.getDescription()));
    }
//    if (!StringUtil.isEmpty(documentation)) {
//      sb.append("<p>").append(documentation).append("</p>");
//    }
    return sb.toString();
  }
项目:AppleScript-IDEA    文件:AppleScriptSystemDictionaryRegistryService.java   
private void initializeScriptingAdditions() {
  for (String stdLibFolder : ApplicationDictionary.SCRIPTING_ADDITIONS_FOLDERS) {
    final File dir = new File(stdLibFolder);
    if (!dir.isDirectory()) continue;
    final File[] stdLibs = dir.listFiles();
    if (stdLibs == null || stdLibs.length == 0) continue;
    for (File stdLib : stdLibs) {
      String libraryName = stdLib.getName();
      int last = libraryName.lastIndexOf(".");
      libraryName = libraryName.substring(0, last > 0 ? last : libraryName.length() - 1);
      if (StringUtil.isEmpty(libraryName)) continue;
      DictionaryInfo dInfo = getDictionaryInfo(libraryName);
      if (dInfo != null) {
        initializeDictionaryFromInfo(dInfo);
      } else {
        if (stdLib.exists())
          dInfo = createAndInitializeInfo(stdLib, libraryName);
      }
      if (dInfo != null)
        scriptingAdditions.add(dInfo.getApplicationName());
      else {
        LOG.warn("Can not initialize scripting addition library from file: " + stdLib + ". Will copy bundled lib.");
        try {
          dInfo = initStdTerms(ApplicationDictionary.SCRIPTING_ADDITIONS_LIBRARY);
          if (dInfo != null) {
            scriptingAdditions.add(dInfo.getApplicationName());
          }
        } catch (IOException e) {
          LOG.warn("Can not initialize scripting addition library from bundle: " + e.getMessage());
        }
      }
    }
  }
}
项目:AppleScript-IDEA    文件:AppleScriptSystemDictionaryRegistryService.java   
private static void updateSetForMappedObjectName(@NotNull String objectName,
                                                 @NotNull String nameToAdd,
                                                 @NotNull Map<String, HashSet<String>> objectNameToNameSetMap,
                                                 @Nullable HashSet<String> nameSetForObject) {
  if (nameSetForObject == null) {
    nameSetForObject = new HashSet<>();
    if (!StringUtil.isEmpty(objectName)) {
      objectNameToNameSetMap.put(objectName, nameSetForObject);
    }
  }
  if (!nameSetForObject.contains(nameToAdd)) {
    nameSetForObject.add(nameToAdd);
  }
}
项目:AppleScript-IDEA    文件:AppleScriptFindUsagesProvider.java   
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
  if (element instanceof PsiNamedElement) {
    return StringUtil.notNullize(((PsiNamedElement) element).getName());
  }
  return "";
}