@Nullable private static IProperty getResolvedProperty(@NotNull final XmlAttributeValue codeValue) { return CachedValuesManager.getCachedValue(codeValue, KEY, () -> { List<IProperty> allProperties = new SmartList<>(); for (PsiReference nextRef : codeValue.getReferences()) { if (nextRef instanceof PsiPolyVariantReference) { Arrays.stream(((PsiPolyVariantReference) nextRef).multiResolve(false)) .filter(ResolveResult::isValidResult) .map(ResolveResult::getElement) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .filter(Objects::nonNull) .forEach(allProperties::add); } else { Optional.ofNullable(nextRef.resolve()) .map(o -> ObjectUtils.tryCast(o, IProperty.class)) .ifPresent(allProperties::add); } } IProperty theChosenOne = chooseForLocale(allProperties); return new CachedValueProvider.Result<>(theChosenOne, PsiModificationTracker.MODIFICATION_COUNT); }); }
private static IProperty chooseForLocale( final @NotNull List<Locale.LanguageRange> priorityList, final @NotNull List<IProperty> properties ) { if (properties.isEmpty()) { return null; } IProperty first = properties.get(0); if (properties.size() == 1) { return first; } final Map<Locale, IProperty> map = new HashMap<>(); final List<Locale> locales = new LinkedList<>(); for (IProperty nextProperty : properties) { Locale nextLocale = safeGetLocale(nextProperty); if (nextLocale != null) { map.put(nextLocale, nextProperty); locales.add(nextLocale); } } Locale best = Locale.lookup(priorityList, locales); //System.err.println("found locales: " + locales + ", best: " + best + ", result: " + map.get(best)); return Optional.ofNullable(best).map(map::get).orElse(first); }
private Optional<ConfigInfo> extractConfigInfo(PropertiesFile propertiesFile, CoffigResolver.Match match) { Optional<String> description = Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath())).map(IProperty::getValue); if (description.isPresent()) { // Base info ConfigInfo configInfo = new ConfigInfo(match.getFullPath(), description.get()); // Extended info Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath() + ".long")).map(IProperty::getValue).ifPresent(configInfo::setLongDescription); // Field info CoffigResolver.Match resolvedMatch = match.fullyResolve(); if (resolvedMatch.isFullyResolved()) { Optional<PsiField> psiField = resolvedMatch.resolveField(resolvedMatch.getUnmatchedPath()); psiField.map(PsiVariable::getType).map(PsiType::getPresentableText).ifPresent(configInfo::setType); } return Optional.of(configInfo); } return Optional.empty(); }
@Override public void update(AnActionEvent anActionEvent) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); boolean isProperty = false; boolean isPropertyFile = false; boolean isEncrypted = false; if (file != null) { isPropertyFile = "properties".equalsIgnoreCase(file.getExtension()); if (isPropertyFile) { IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext()); if (selectedProperty != null) { String propertyValue = selectedProperty.getValue(); isEncrypted = (propertyValue.startsWith("![") && propertyValue.endsWith("]")); isProperty = true; } } } anActionEvent.getPresentation().setEnabled(isPropertyFile && isEncrypted && isProperty); anActionEvent.getPresentation().setVisible(isPropertyFile && isProperty); }
@Override public void update(AnActionEvent anActionEvent) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext()); boolean isProperty = false; boolean isPropertyFile = false; boolean isEncrypted = false; if (file != null) { isPropertyFile = "properties".equalsIgnoreCase(file.getExtension()); if (isPropertyFile) { IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext()); if (selectedProperty != null) { String propertyValue = selectedProperty.getValue(); isEncrypted = (propertyValue.startsWith("![") && propertyValue.endsWith("]")); isProperty = true; } } } anActionEvent.getPresentation().setEnabled(isPropertyFile && !isEncrypted && isProperty); anActionEvent.getPresentation().setVisible(isPropertyFile && isProperty); }
public void testLocalProperties() { VirtualFile vFile = myFixture.copyFileToProject("test.properties", "local.properties"); PsiFile file = PsiManager.getInstance(getProject()).findFile(vFile); assertNotNull(file); PropertiesFile propertiesFile = (PropertiesFile)file; GradleImplicitPropertyUsageProvider provider = new GradleImplicitPropertyUsageProvider(); for (IProperty property : propertiesFile.getProperties()) { Property p = (Property)property; // Only but the property with "unused" in its name are considered used String name = property.getName(); if (name.contains("unused")) { assertFalse(name, provider.isUsed(p)); } else { assertTrue(name, provider.isUsed(p)); } } }
public PsiElement resolve() { final Project project = myFile.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile formVirtualFile = myFile.getVirtualFile(); if (formVirtualFile == null) { return null; } final Module module = fileIndex.getModuleForFile(formVirtualFile); if (module == null) { return null; } final PropertiesFile propertiesFile = PropertiesUtilBase.getPropertiesFile(myBundleName, module, null); if (propertiesFile == null) { return null; } IProperty property = propertiesFile.findPropertyByKey(getRangeText()); return property == null ? null : property.getPsiElement(); }
@Nullable public String resolve(@Nullable StringDescriptor descriptor, @Nullable Locale locale) { if (descriptor == null) { return null; } if (descriptor.getValue() != null) { return descriptor.getValue(); } IProperty prop = resolveToProperty(descriptor, locale); if (prop != null) { final String value = prop.getUnescapedValue(); if (value != null) { return value; } } // We have to return surrogate string in case if propFile name is invalid or bundle doesn't have specified key return "[" + descriptor.getKey() + " / " + descriptor.getBundleName() + "]"; }
public IProperty resolveToProperty(@NotNull StringDescriptor descriptor, @Nullable Locale locale) { String propFileName = descriptor.getDottedBundleName(); Pair<Locale, String> cacheKey = Pair.create(locale, propFileName); PropertiesFile propertiesFile; synchronized (myPropertiesFileCache) { propertiesFile = myPropertiesFileCache.get(cacheKey); } if (propertiesFile == null || !propertiesFile.getContainingFile().isValid()) { propertiesFile = PropertiesUtilBase.getPropertiesFile(propFileName, myModule, locale); synchronized (myPropertiesFileCache) { myPropertiesFileCache.put(cacheKey, propertiesFile); } } if (propertiesFile != null) { final IProperty propertyByKey = propertiesFile.findPropertyByKey(descriptor.getKey()); if (propertyByKey != null) { return propertyByKey; } } return null; }
@NotNull protected List<String> getExistingValueKeys(String value) { if(!myCustomization.suggestExistingProperties) { return Collections.emptyList(); } final ArrayList<String> result = new ArrayList<String>(); // check if property value already exists among properties file values and suggest corresponding key PropertiesFile propertiesFile = getPropertiesFile(); if (propertiesFile != null) { for (IProperty property : propertiesFile.getProperties()) { if (Comparing.strEqual(property.getValue(), value)) { result.add(0, property.getUnescapedKey()); } } } return result; }
@Override protected void doOKAction() { if (!createPropertiesFileIfNotExists()) return; Collection<PropertiesFile> propertiesFiles = getAllPropertiesFiles(); for (PropertiesFile propertiesFile : propertiesFiles) { IProperty existingProperty = propertiesFile.findPropertyByKey(getKey()); final String propValue = myValue.getText(); if (existingProperty != null && !Comparing.strEqual(existingProperty.getValue(), propValue)) { final String messageText = CodeInsightBundle.message("i18nize.dialog.error.property.already.defined.message", getKey(), propertiesFile.getName()); final int code = Messages.showOkCancelDialog(myProject, messageText, CodeInsightBundle.message("i18nize.dialog.error.property.already.defined.title"), null); if (code == Messages.CANCEL) { return; } } } super.doOKAction(); }
/** * Tries to derive {@link com.intellij.lang.properties.ResourceBundle resource bundle} related to the given context. * * @param dataContext target context * @return {@link com.intellij.lang.properties.ResourceBundle resource bundle} related to the given context if any; * <code>null</code> otherwise */ @Nullable public static ResourceBundle getResourceBundleFromDataContext(@NotNull DataContext dataContext) { PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); if (element instanceof IProperty) return null; //rename property final ResourceBundle[] bundles = ResourceBundle.ARRAY_DATA_KEY.getData(dataContext); if (bundles != null && bundles.length == 1) return bundles[0]; VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (virtualFile == null) { return null; } final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (virtualFile instanceof ResourceBundleAsVirtualFile && project != null) { return ((ResourceBundleAsVirtualFile)virtualFile).getResourceBundle(); } if (project != null) { final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile instanceof PropertiesFile) { return ((PropertiesFile)psiFile).getResourceBundle(); } } return null; }
@Override public void update(AnActionEvent e) { final FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(e.getDataContext()); if (fileEditor instanceof ResourceBundleEditor) { ResourceBundleEditor resourceBundleEditor = (ResourceBundleEditor)fileEditor; final Project project = getEventProject(e); if (project != null) { if (!processSelectedIncompleteProperties(new Processor<IProperty>() { @Override public boolean process(IProperty property) { return false; } }, resourceBundleEditor, project)) { e.getPresentation().setEnabledAndVisible(true); return; } } } e.getPresentation().setEnabledAndVisible(false); }
private static boolean processSelectedIncompleteProperties(final @NotNull Processor<IProperty> processor, final @NotNull ResourceBundleEditor resourceBundleEditor, final @NotNull Project project) { final IgnoredPropertiesFilesSuffixesManager suffixesManager = IgnoredPropertiesFilesSuffixesManager.getInstance(project); for (ResourceBundleEditorViewElement element : resourceBundleEditor.getSelectedElements()) { final IProperty[] properties = element.getProperties(); if (properties != null) { for (IProperty property : properties) { if (!suffixesManager.isPropertyComplete(resourceBundleEditor.getResourceBundle(), property.getKey()) && !processor.process(property)) { return false; } } } } return true; }
@Override public void deleteElement(@NotNull final DataContext dataContext) { final List<PropertiesFile> bundlePropertiesFiles = myResourceBundle.getPropertiesFiles(); final List<PsiElement> toDelete = new ArrayList<PsiElement>(); for (IProperty property : myProperties) { final String key = property.getKey(); if (key == null) { LOG.error("key must be not null " + property); } else { for (PropertiesFile propertiesFile : bundlePropertiesFiles) { for (final IProperty iProperty : propertiesFile.findPropertiesByKey(key)) { toDelete.add(iProperty.getPsiElement()); } } } } final Project project = CommonDataKeys.PROJECT.getData(dataContext); LOG.assertTrue(project != null); new SafeDeleteHandler().invoke(project, PsiUtilCore.toPsiElementArray(toDelete), dataContext); myInsertDeleteManager.reload(); }
public void insertOrUpdateTranslation(String key, String value, final PropertiesFile propertiesFile) throws IncorrectOperationException { final IProperty property = propertiesFile.findPropertyByKey(key); if (property != null) { property.setValue(value); return; } if (myOrdered) { if (myAlphaSorted) { propertiesFile.addProperty(key, value); return; } final Pair<IProperty, Integer> propertyAndPosition = findExistedPrevSiblingProperty(key, propertiesFile); propertiesFile.addPropertyAfter(key, value, propertyAndPosition == null ? null : (Property)propertyAndPosition.getFirst()); } else { insertPropertyLast(key, value, propertiesFile); } }
public void deletePropertyIfExist(String key, PropertiesFile file) { final IProperty property = file.findPropertyByKey(key); if (property != null && myKeysOrder != null) { boolean keyExistInOtherPropertiesFiles = false; for (PropertiesFile propertiesFile : myResourceBundle.getPropertiesFiles()) { if (!propertiesFile.equals(file) && propertiesFile.findPropertyByKey(key) != null) { keyExistInOtherPropertiesFiles = true; break; } } if (!keyExistInOtherPropertiesFiles) { myKeysOrder.remove(key); } } if (property != null) { property.getPsiElement().delete(); } }
@Override public void findCollisions(PsiElement element, final String newName, Map<? extends PsiElement, String> allRenames, List<UsageInfo> result) { for (final Map.Entry<? extends PsiElement, String> e: allRenames.entrySet()) { for (IProperty property : ((PropertiesFile)e.getKey().getContainingFile()).getProperties()) { if (Comparing.strEqual(e.getValue(), property.getKey())) { result.add(new UnresolvableCollisionUsageInfo(property.getPsiElement(), e.getKey()) { @Override public String getDescription() { return "New property name \'" + e.getValue() + "\' hides existing property"; } }); } } } }
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) { if (!(file instanceof PropertiesFile)) return null; final List<IProperty> properties = ((PropertiesFile)file).getProperties(); final List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>(); for (IProperty property : properties) { ProgressManager.checkCanceled(); final PropertyImpl propertyImpl = (PropertyImpl)property; for (ASTNode node : ContainerUtil.ar(propertyImpl.getKeyNode(), propertyImpl.getValueNode())) { if (node != null) { PsiElement key = node.getPsi(); TextRange textRange = getTrailingSpaces(key, myIgnoreVisibleSpaces); if (textRange != null) { descriptors.add(manager.createProblemDescriptor(key, textRange, "Trailing spaces", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, new RemoveTrailingSpacesFix(myIgnoreVisibleSpaces))); } } } } return descriptors.toArray(new ProblemDescriptor[descriptors.size()]); }
@NotNull @Override public IProperty[] getProperties() { final List<IProperty> elements = ContainerUtil.mapNotNull(getChildren(), new NullableFunction<TreeElement, IProperty>() { @Nullable @Override public IProperty fun(final TreeElement treeElement) { if (treeElement instanceof PropertiesStructureViewElement) { PropertiesStructureViewElement propertiesElement = (PropertiesStructureViewElement)treeElement; return propertiesElement.getValue(); } else if (treeElement instanceof ResourceBundlePropertyStructureViewElement) { return ((ResourceBundlePropertyStructureViewElement)treeElement).getProperties()[0]; } return null; } }); return elements.toArray(new IProperty[elements.size()]); }
private void ensurePropertiesLoaded() { while (myFileModificationStamp != myFile.getModificationStamp() || myPropertiesMap == null) { myFileModificationStamp = myFile.getModificationStamp(); MostlySingularMultiMap<String, IProperty> propertiesMap = new MostlySingularMultiMap<String, IProperty>(); XmlTag rootTag = myFile.getRootTag(); final List<IProperty> propertiesOrder = new ArrayList<IProperty>(); if (rootTag != null) { XmlTag[] entries = rootTag.findSubTags("entry"); for (XmlTag entry : entries) { XmlProperty property = new XmlProperty(entry, this); propertiesOrder.add(property); propertiesMap.add(property.getKey(), property); } } final boolean isAlphaSorted = PropertiesImplUtil.isAlphaSorted(propertiesOrder); myAlphaSorted = isAlphaSorted; myProperties = propertiesOrder; myPropertiesMap = propertiesMap; } }
@NotNull public ResolveResult[] multiResolve(final boolean incompleteCode) { final String key = getKeyText(); List<IProperty> properties; final List<PropertiesFile> propertiesFiles = getPropertiesFiles(); if (propertiesFiles == null) { properties = PropertiesImplUtil.findPropertiesByKey(getElement().getProject(), key); } else { properties = new ArrayList<IProperty>(); for (PropertiesFile propertiesFile : propertiesFiles) { properties.addAll(propertiesFile.findPropertiesByKey(key)); } } // put default properties file first ContainerUtil.quickSort(properties, new Comparator<IProperty>() { public int compare(final IProperty o1, final IProperty o2) { String name1 = o1.getPropertiesFile().getName(); String name2 = o2.getPropertiesFile().getName(); return Comparing.compare(name1, name2); } }); return getResolveResults(properties); }
public static MultiMap<String, IProperty> getPropertiesMap(ResourceBundle resourceBundle, boolean onlyIncomplete) { List<PropertiesFile> propertiesFiles = resourceBundle.getPropertiesFiles(); final MultiMap<String, IProperty> propertyNames; if (onlyIncomplete) { propertyNames = getChildrenIdShowOnlyIncomplete(resourceBundle); } else { propertyNames = MultiMap.createLinked(); for (PropertiesFile propertiesFile : propertiesFiles) { List<IProperty> properties = propertiesFile.getProperties(); for (IProperty property : properties) { String name = property.getKey(); propertyNames.putValue(name, property); } } } return propertyNames; }
public Couple<List<String>> collectExtensions(GlobalSearchScope resolveScope) { PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage("META-INF.services"); if (aPackage == null) { return Couple.of(Collections.<String>emptyList(), Collections.<String>emptyList()); } List<String> instanceClasses = new ArrayList<String>(); List<String> staticClasses = new ArrayList<String>(); for (PsiDirectory directory : aPackage.getDirectories(resolveScope)) { PsiFile file = directory.findFile(ORG_CODEHAUS_GROOVY_RUNTIME_EXTENSION_MODULE); if (file instanceof PropertiesFile) { IProperty inst = ((PropertiesFile)file).findPropertyByKey("extensionClasses"); IProperty stat = ((PropertiesFile)file).findPropertyByKey("staticExtensionClasses"); if (inst != null) collectClasses(inst, instanceClasses); if (stat != null) collectClasses(stat, staticClasses); } } return Couple.of(instanceClasses, staticClasses); }
@Override public String getPlaceholderText(@NotNull ASTNode node) { final PsiElement element = node.getPsi(); if (element instanceof XmlAttributeValue) { IProperty property = getResolvedProperty((XmlAttributeValue) element); return property == null ? element.getText() : "{" + property.getValue() + "}"; } return element.getText(); }
private static Locale safeGetLocale(final @NotNull IProperty property) { try { PropertiesFile file = property.getPropertiesFile(); return file == null ? null : file.getLocale(); } catch (PsiInvalidElementAccessException e) { return null; } }
@Override public void actionPerformed(AnActionEvent anActionEvent) { final Project project = (Project) anActionEvent.getData(CommonDataKeys.PROJECT); PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE); IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext()); final EncryptDialog form = new EncryptDialog(); form.setTitle("Decrypt Property: " + selectedProperty.getKey()); form.show(); boolean isOk = form.getExitCode() == DialogWrapper.OK_EXIT_CODE; logger.debug("**** ALGORITHM " + form.getAlgorithm().getSelectedItem()); logger.debug("**** MODE " + form.getMode().getSelectedItem()); if (isOk) { new WriteCommandAction.Simple(project, psiFile) { @Override protected void run() throws Throwable { EncryptionAlgorithm algorithm = (EncryptionAlgorithm) form.getAlgorithm().getSelectedItem(); EncryptionMode mode = (EncryptionMode) form.getMode().getSelectedItem(); try { String originalValue = selectedProperty.getValue(); String encryptedProperty = originalValue.substring(2, originalValue.length() - 1); byte[] decryptedBytes = algorithm.getBuilder().forKey(form.getEncryptionKey().getText()).using(mode) .build().decrypt(Base64.decode(encryptedProperty)); selectedProperty.setValue(new String(decryptedBytes)); } catch (Exception e) { Notification notification = MuleUIUtils.MULE_NOTIFICATION_GROUP.createNotification("Unable to decrypt property", "Property '" + selectedProperty.getKey() + "' cannot be decrypted : " + e, NotificationType.ERROR, null); Notifications.Bus.notify(notification, project); } } }.execute(); } }
@Override public void actionPerformed(AnActionEvent anActionEvent) { final Project project = (Project)anActionEvent.getData(CommonDataKeys.PROJECT); PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE); IProperty selectedProperty = getSelectedProperty(anActionEvent.getDataContext()); if (selectedProperty == null) return; final EncryptDialog form = new EncryptDialog(); form.setTitle("Encrypt Property: " + selectedProperty.getKey()); form.show(); boolean isOk = form.getExitCode() == DialogWrapper.OK_EXIT_CODE; // System.out.println("******** IS OK " + isOk); logger.debug("**** ALGORITHM " + form.getAlgorithm().getSelectedItem()); logger.debug("**** MODE " + form.getMode().getSelectedItem()); if (isOk) { new WriteCommandAction.Simple(project, psiFile) { @Override protected void run() throws Throwable { EncryptionAlgorithm algorithm = (EncryptionAlgorithm) form.getAlgorithm().getSelectedItem(); EncryptionMode mode = (EncryptionMode) form.getMode().getSelectedItem(); byte[] encryptedBytes = algorithm.getBuilder().forKey(form.getEncryptionKey().getText()).using(mode) .build().encrypt(selectedProperty.getValue().getBytes()); StringBuilder result = new StringBuilder(); result.append(ENCRYPT_PREFIX); result.append(new String(Base64.encode(encryptedBytes))); result.append(ENCRYPT_SUFFIX); selectedProperty.setValue(result.toString()); } }.execute(); } }
private void searchProperty(String query) { FindModel findModel = new FindModel(); findModel.setStringToFind(query); findModel.setWholeWordsOnly(true); findModel.setFromCursor(false); findModel.setGlobal(true); findModel.setMultipleFiles(true); findModel.setProjectScope(true); findModel.setDirectoryName(mySourceDirs[0].getPath()); findModel.setWithSubdirectories(true); List<UsageInfo> usages = findUsages(findModel); assertEquals(2, usages.size()); if (!(usages.get(0).getFile() instanceof PsiJavaFile)) { Collections.swap(usages, 0, 1); } PsiElement refElement = getParentFromUsage(usages.get(0)); assertTrue(refElement instanceof PsiLiteralExpression); assertEquals("xx.yy", ((PsiLiteralExpression)refElement).getValue()); VirtualFile file = mySourceDirs[0].findFileByRelativePath("x/dd.properties"); assertNotNull(file); PropertiesFile propertiesFile = (PropertiesFile)PsiManager.getInstance(myProject).findFile(file); assertNotNull(propertiesFile); refElement = getParentFromUsage(usages.get(1)); assertTrue(refElement instanceof IProperty); assertSame(propertiesFile.findPropertyByKey("xx.yy"), refElement); }
public void testGradleWrapper() { VirtualFile vFile = myFixture.copyFileToProject("projects/projectWithAppandLib/gradle/wrapper/gradle-wrapper.properties", "gradle/wrapper/gradle-wrapper.properties"); PsiFile file = PsiManager.getInstance(getProject()).findFile(vFile); assertNotNull(file); PropertiesFile propertiesFile = (PropertiesFile)file; GradleImplicitPropertyUsageProvider provider = new GradleImplicitPropertyUsageProvider(); for (IProperty property : propertiesFile.getProperties()) { // All properties are considered used in this file String name = property.getName(); assertTrue(name, provider.isUsed((Property)property)); } }
protected static void collectPropertiesFileVariants(@Nullable PropertiesFile file, @Nullable String prefix, List<Object> result, Set<String> variants) { if (file == null) return; for (IProperty each : file.getProperties()) { String name = each.getKey(); if (name != null) { if (prefix != null) name = prefix + name; if (variants.add(name)) { result.add(createLookupElement(each, name, PlatformIcons.PROPERTY_ICON)); } } } }
@Override protected PsiElement doResolve() { PsiElement result = super.doResolve(); if (result != null) return result; for (String each : myMavenProject.getFilterPropertiesFiles()) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(each); if (file == null) continue; IProperty property = MavenDomUtil.findProperty(myProject, file, myText); if (property != null) return property.getPsiElement(); } return null; }
public void testUpperCaseEnvPropertiesOnWindows() throws Exception { if (!SystemInfo.isWindows) return; createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<name>${<caret>env.PATH}</name>"); PsiReference ref = getReferenceAtCaret(myProjectPom); assertNotNull(ref); PsiElement resolved = ref.resolve(); assertEquals(System.getenv("Path").replaceAll("[^A-Za-z]", ""), ((IProperty)resolved).getValue().replaceAll("[^A-Za-z]", "")); }
public PsiElement getNavigationElement(final String propertyName) { DomTarget domTarget = DomTarget.getTarget(this); if (domTarget == null) { final GenericAttributeValue<String> environment = getEnvironment(); if (environment.getRawText() != null) { domTarget = DomTarget.getTarget(this, environment); } if (domTarget == null) { final GenericAttributeValue<String> resource = getResource(); if (resource.getRawText() != null) { domTarget = DomTarget.getTarget(this, resource); } } } if (domTarget != null) { final PsiElement psi = PomService.convertToPsi(domTarget); if (psi != null) { return psi; } } final PsiFileSystemItem psiFile = getFile().getValue(); if (psiFile != null) { final String prefix = getPropertyPrefixValue(); String _propertyName = propertyName; if (prefix != null) { if (!propertyName.startsWith(prefix)) { return null; } _propertyName = propertyName.substring(prefix.length()); } final PropertiesFile pf = toPropertiesFile(psiFile); if (pf != null) { final IProperty property = pf.findPropertyByKey(_propertyName); return property != null? property.getPsiElement() : null; } } return null; }
public PsiElement bindToElement(@NotNull final PsiElement element) throws IncorrectOperationException { if (!(element instanceof IProperty)) { throw new IncorrectOperationException(); } updateRangeText(((IProperty)element).getUnescapedKey()); return myFile; }
public boolean isReferenceTo(final PsiElement element) { if (!(element instanceof IProperty)) { return false; } IProperty property = (IProperty) element; String baseName = ResourceBundleManager.getInstance(element.getProject()).getFullName(property.getPropertiesFile()); return baseName != null && myBundleName.equals(baseName.replace('.', '/')) && getRangeText().equals(property.getUnescapedKey()); }
private void fillPropertyList() { myPairs = new ArrayList<Couple<String>>(); final List<IProperty> properties = myBundle.getProperties(); for (IProperty property : properties) { final String key = property.getUnescapedKey(); final String value = property.getValue(); if (key != null) { myPairs.add(Couple.of(key, value != null ? value : NULL)); } } Collections.sort(myPairs, new MyPairComparator()); }
@Override public void renderElement(LookupElement element, LookupElementPresentation presentation) { IProperty property = (IProperty)element.getObject(); presentation.setIcon(PlatformIcons.PROPERTY_ICON); String key = StringUtil.notNullize(property.getUnescapedKey()); presentation.setItemText(key); PropertiesFile propertiesFile = property.getPropertiesFile(); ResourceBundle resourceBundle = propertiesFile.getResourceBundle(); String value = property.getValue(); boolean hasBundle = resourceBundle != EmptyResourceBundle.getInstance(); if (hasBundle) { PropertiesFile defaultPropertiesFile = resourceBundle.getDefaultPropertiesFile(); IProperty defaultProperty = defaultPropertiesFile.findPropertyByKey(key); if (defaultProperty != null) { value = defaultProperty.getValue(); } } if (hasBundle) { presentation.setTypeText(resourceBundle.getBaseName(), AllIcons.FileTypes.Properties); } if (presentation instanceof RealLookupElementPresentation && value != null) { value = "=" + value; int limit = 1000; if (value.length() > limit || !((RealLookupElementPresentation)presentation).hasEnoughSpaceFor(value, false)) { if (value.length() > limit) { value = value.substring(0, limit); } while (value.length() > 0 && !((RealLookupElementPresentation)presentation).hasEnoughSpaceFor(value + "...", false)) { value = value.substring(0, value.length() - 1); } value += "..."; } } TextAttributes attrs = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(PropertiesHighlighter.PROPERTY_VALUE); presentation.setTailText(value, attrs.getForegroundColor()); }
public static LookupElement[] getVariants(Set<Object> variants) { List<LookupElement> elements = ContainerUtil.mapNotNull(variants, new NullableFunction<Object, LookupElement>() { @Override public LookupElement fun(Object o) { if (o instanceof String) return LookupElementBuilder.create((String)o).withIcon(PlatformIcons.PROPERTY_ICON); return createVariant((IProperty)o); } }); return elements.toArray(new LookupElement[elements.size()]); }
private String suggestSelectedFileUrl(List<String> paths) { if (myDefaultPropertyValue != null) { for (String path : paths) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(path)); if (file == null) continue; PsiFile psiFile = myContext.getManager().findFile(file); if (!(psiFile instanceof PropertiesFile)) continue; for (IProperty property : ((PropertiesFile)psiFile).getProperties()) { if (property.getValue().equals(myDefaultPropertyValue)) return path; } } } return LastSelectedPropertiesFileStore.getInstance().suggestLastSelectedPropertiesFileUrl(myContext); }