private void validateModule(@NotNull Module module) throws Exception { final String importedModulePath = getProject().getBaseDir().getPath(); final Element actualImlElement = new Element("root"); ((ModuleRootManagerImpl) ModuleRootManager.getInstance(module)) .getState() .writeExternal(actualImlElement); PathMacros.getInstance().setMacro(MODULE_DIR, importedModulePath); PathMacroManager.getInstance(module).collapsePaths(actualImlElement); PathMacroManager.getInstance(getProject()).collapsePaths(actualImlElement); PathMacros.getInstance().removeMacro(MODULE_DIR); final String projectPath = getProject().getBaseDir().getPath(); final File expectedImlFile = new File(projectPath + "/expected/" + module.getName() + ".iml"); final Document expectedIml = JDOMUtil.loadDocument(expectedImlFile); final Element expectedImlElement = expectedIml.getRootElement(); final String errorMsg = "Configuration of module " + module.getName() + " does not meet expectations.\nExpected:\n" + new String(JDOMUtil.printDocument(expectedIml, "\n")) + "\nBut got:\n" + new String(JDOMUtil.printDocument(new Document(actualImlElement), "\n")); Assert.assertTrue(errorMsg, JDOMUtil.areElementsEqual(expectedImlElement, actualImlElement)); validateFacet(module); }
/** Parse and print pretty-formatted XML to {@code logger}, if its level is DEBUG or below. */ public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull String xml) { if (logger.isDebugEnabled()) { try { logger.debug( "\n" + JDOMUtil.createOutputter("\n").outputString(JDOMUtil.loadDocument(xml))); } catch (Exception e) { logger.debug(e); } } }
public static boolean isEmpty(@Nullable Parent element) { if (element == null) { return true; } else if (element instanceof Element) { return JDOMUtil.isEmpty((Element) element); } else { Document document = (Document) element; return !document.hasRootElement() || JDOMUtil.isEmpty(document.getRootElement()); } }
@SuppressWarnings("deprecation") protected static void checkSettingsEqual( JDOMExternalizable expected, JDOMExternalizable settings, String message) throws Exception { if (expected == null || settings == null) return; Element oldS = new Element("temp"); expected.writeExternal(oldS); Element newS = new Element("temp"); settings.writeExternal(newS); String newString = JDOMUtil.writeElement(newS, "\n"); String oldString = JDOMUtil.writeElement(oldS, "\n"); Assert.assertEquals(message, oldString, newString); }
private static void fillSdks(List<GlobalLibrary> globals) { for (Sdk sdk : ProjectJdkTable.getInstance().getAllJdks()) { final String name = sdk.getName(); final String homePath = sdk.getHomePath(); if (homePath == null) { continue; } final SdkAdditionalData data = sdk.getSdkAdditionalData(); final String additionalDataXml; final SdkType sdkType = (SdkType) sdk.getSdkType(); if (data == null) { additionalDataXml = null; } else { final Element element = new Element("additional"); sdkType.saveAdditionalData(data, element); additionalDataXml = JDOMUtil.writeElement(element, "\n"); } final List<String> paths = convertToLocalPaths(sdk.getRootProvider().getFiles(OrderRootType.CLASSES)); String versionString = sdk.getVersionString(); if (versionString != null && sdkType instanceof JavaSdk) { final JavaSdkVersion version = ((JavaSdk) sdkType).getVersion(versionString); if (version != null) { versionString = version.getDescription(); } } globals.add( new SdkLibrary( name, sdkType.getName(), versionString, homePath, paths, additionalDataXml)); } }
@Override public void performPaste(@NotNull DataContext dataContext) { TemplateGroup group = myConfigurable.getSingleSelectedGroup(); assert group != null; String buffer = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); assert buffer != null; try { for (Element templateElement : JDOMUtil.load(new StringReader("<root>" + buffer + "</root>")) .getChildren(TemplateSettings.TEMPLATE)) { TemplateImpl template = TemplateSettings.readTemplateFromElement( group.getName(), templateElement, getClass().getClassLoader()); while (group.containsTemplate(template.getKey(), template.getId())) { template.setKey(template.getKey() + "1"); if (template.getId() != null) { template.setId(template.getId() + "1"); } } myConfigurable.addTemplate(template); } } catch (JDOMException ignore) { } catch (IOException ignore) { } }
public ImportRunProfile(VirtualFile file, Project project) { myFile = file; myProject = project; try { final Document document = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(myFile)); final Element config = document.getRootElement().getChild("config"); if (config != null) { String configTypeId = config.getAttributeValue("configId"); if (configTypeId != null) { final ConfigurationType configurationType = ConfigurationTypeUtil.findConfigurationType(configTypeId); if (configurationType != null) { myConfiguration = configurationType.getConfigurationFactories()[0].createTemplateConfiguration( project); myConfiguration.setName(config.getAttributeValue("name")); myConfiguration.readExternal(config); final Executor executor = ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID); if (executor != null) { if (myConfiguration instanceof SMRunnerConsolePropertiesProvider) { myProperties = ((SMRunnerConsolePropertiesProvider) myConfiguration) .createTestConsoleProperties(executor); } } } } } } catch (Exception ignore) { } }
/** Print pretty-formatted XML to {@code logger}, if its level is DEBUG or below. */ public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull Element element) { if (logger.isDebugEnabled()) { // alternatively // new XMLOutputter(Format.getPrettyFormat()).outputString(root) logger.debug("\n" + JDOMUtil.createOutputter("\n").outputString(element)); } }
@Nullable public static Configuration load(final InputStream is) throws IOException, JDOMException { try { final Document document = JDOMUtil.loadDocument(is); final ArrayList<Element> elements = new ArrayList<Element>(); elements.add(document.getRootElement()); elements.addAll(document.getRootElement().getChildren("component")); final Element element = ContainerUtil.find( elements, new Condition<Element>() { public boolean value(final Element element) { return "component".equals(element.getName()) && COMPONENT_NAME.equals(element.getAttributeValue("name")); } }); if (element != null) { final Configuration cfg = new Configuration(); cfg.loadState(element, false); return cfg; } return null; } finally { is.close(); } }
public void serializeInto( @NotNull Object o, @NotNull Element element, @NotNull SerializationFilter filter) { for (Binding binding : myPropertyBindings.keySet()) { Accessor accessor = myPropertyBindings.get(binding); if (!filter.accepts(accessor, o)) { continue; } // todo: optimize. Cache it. Property property = accessor.getAnnotation(Property.class); if (property != null && property.filter() != SerializationFilter.class) { try { if (!ReflectionUtil.newInstance(property.filter()).accepts(accessor, o)) { continue; } } catch (RuntimeException e) { throw new XmlSerializationException(e); } } Object node = binding.serialize(o, element, filter); if (node != null) { if (node instanceof org.jdom.Attribute) { element.setAttribute((org.jdom.Attribute) node); } else { JDOMUtil.addContent(element, node); } } } }
private static void loadAdditionalRoots( Element rootModelComponent, final String rootsTagName, final JpsUrlList result) { final Element roots = rootModelComponent.getChild(rootsTagName); for (Element root : JDOMUtil.getChildren(roots, ROOT_TAG)) { result.addUrl(root.getAttributeValue(URL_ATTRIBUTE)); } }
public String getReportText() { final Element rootElement = new Element("root"); rootElement.setAttribute("isBackward", String.valueOf(!myForward)); final List<PsiFile> files = new ArrayList<PsiFile>(myDependencies.keySet()); Collections.sort( files, new Comparator<PsiFile>() { @Override public int compare(PsiFile f1, PsiFile f2) { final VirtualFile virtualFile1 = f1.getVirtualFile(); final VirtualFile virtualFile2 = f2.getVirtualFile(); if (virtualFile1 != null && virtualFile2 != null) { return virtualFile1.getPath().compareToIgnoreCase(virtualFile2.getPath()); } return 0; } }); for (PsiFile file : files) { final Element fileElement = new Element("file"); fileElement.setAttribute("path", file.getVirtualFile().getPath()); for (PsiFile dep : myDependencies.get(file)) { Element depElement = new Element("dependency"); depElement.setAttribute("path", dep.getVirtualFile().getPath()); fileElement.addContent(depElement); } rootElement.addContent(fileElement); } PathMacroManager.getInstance(myProject).collapsePaths(rootElement); return JDOMUtil.writeDocument(new Document(rootElement), SystemProperties.getLineSeparator()); }
@NotNull public static BufferExposingByteArrayOutputStream writeToBytes( @NotNull Parent element, @NotNull String lineSeparator) throws IOException { BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream(512); JDOMUtil.writeParent(element, out, lineSeparator); return out; }
@NotNull private GradleProjectConfiguration loadLastConfiguration(@NotNull File gradleConfigFile) { final GradleProjectConfiguration projectConfig = new GradleProjectConfiguration(); if (gradleConfigFile.exists()) { try { final Document document = JDOMUtil.loadDocument(gradleConfigFile); XmlSerializer.deserializeInto(projectConfig, document.getRootElement()); // filter orphan modules final Set<String> actualModules = myModulesConfigurationHash.keySet(); for (Iterator<Map.Entry<String, GradleModuleResourceConfiguration>> iterator = projectConfig.moduleConfigurations.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, GradleModuleResourceConfiguration> configurationEntry = iterator.next(); if (!actualModules.contains(configurationEntry.getKey())) { iterator.remove(); } } } catch (Exception e) { LOG.info(e); } } return projectConfig; }
@Override @Nullable public Object deserialize(Object o, @NotNull Object... nodes) { assert nodes.length > 0; Object[] children; if (nodes.length == 1) { children = JDOMUtil.getContent((Element) nodes[0]); } else { String name = ((Element) nodes[0]).getName(); List<Content> childrenList = new SmartList<Content>(); for (Object node : nodes) { assert ((Element) node).getName().equals(name); childrenList.addAll(((Element) node).getContent()); } children = ArrayUtil.toObjectArray(childrenList); } if (children.length == 0) { children = new Object[] {new Text(myTagAnnotation.textIfEmpty())}; } assert myBinding != null; Object v = myBinding.deserialize(myAccessor.read(o), children); Object value = XmlSerializerImpl.convert(v, myAccessor.getValueClass()); myAccessor.write(o, value); return o; }
@NotNull public static TreeMap<String, Element> load( @NotNull Element rootElement, @Nullable PathMacroSubstitutor pathMacroSubstitutor, boolean intern) { if (pathMacroSubstitutor != null) { pathMacroSubstitutor.expandPaths(rootElement); } StringInterner interner = intern ? new StringInterner() : null; List<Element> children = rootElement.getChildren(COMPONENT); TreeMap<String, Element> map = new TreeMap<String, Element>(); for (Element element : children) { String name = getComponentNameIfValid(element); if (name == null || !(element.getAttributes().size() > 1 || !element.getChildren().isEmpty())) { continue; } if (interner != null) { JDOMUtil.internElement(element, interner); } map.put(name, element); if (pathMacroSubstitutor instanceof TrackingPathMacroSubstitutor) { ((TrackingPathMacroSubstitutor) pathMacroSubstitutor) .addUnknownMacros(name, PathMacrosCollector.getMacroNames(element)); } // remove only after "getMacroNames" - some PathMacroFilter requires element name attribute element.removeAttribute(NAME); } return map; }
@Override public boolean accepts(final Accessor accessor, final Object bean) { if (bean == null) { return true; } Object defaultBean = getDefaultBean(bean); final Object defValue = accessor.read(defaultBean); final Object beanValue = accessor.read(bean); if (defValue instanceof Element && beanValue instanceof Element) { return !JDOMUtil.writeElement((Element) defValue, "\n") .equals(JDOMUtil.writeElement((Element) beanValue, "\n")); } return !Comparing.equal(beanValue, defValue); }
public void readExternal( @NotNull Document document, @NotNull URL url, boolean ignoreMissingInclude) throws InvalidDataException, FileNotFoundException { document = JDOMXIncluder.resolve(document, url.toExternalForm(), ignoreMissingInclude); Element rootElement = document.getRootElement(); JDOMUtil.internElement(rootElement, new StringInterner()); readExternal(document.getRootElement()); }
ApplicationInfoImpl() { String resource = IDEA_PATH + ApplicationNamesInfo.getComponentName() + XML_EXTENSION; try { Document doc = JDOMUtil.loadDocument(ApplicationInfoImpl.class, resource); loadState(doc.getRootElement()); } catch (Exception e) { throw new RuntimeException("Cannot load resource: " + resource, e); } }
@Nullable public static Element getSettingsElement(@Nullable Element element, String name) { for (Element child : JDOMUtil.getChildren(element, "setting")) { if (child.getAttributeValue("name").equals(name)) { return child; } } return null; }
@Nullable private static Element findComponent(Element root, String componentName) { for (Element element : JDOMUtil.getChildren(root, "component")) { if (componentName.equals(element.getAttributeValue("name"))) { return element; } } return null; }
@Nullable static String getComponentNameIfValid(@NotNull Element element) { String name = element.getAttributeValue(NAME); if (StringUtil.isEmpty(name)) { LOG.warn("No name attribute for component in " + JDOMUtil.writeElement(element)); return null; } return name; }
public static Document loadDocument(File file) throws CannotConvertException { try { return JDOMUtil.loadDocument(file); } catch (JDOMException e) { throw new CannotConvertException(file.getAbsolutePath() + ": " + e.getMessage(), e); } catch (IOException e) { throw new CannotConvertException(file.getAbsolutePath() + ": " + e.getMessage(), e); } }
private static boolean isValidExternalFile(String version, File toCheck) { try { Document document = JDOMUtil.loadDocument(toCheck); String versionPattern = document.getRootElement().getChildText("version"); return Pattern.compile(versionPattern).matcher(version).find(); } catch (Exception e) { e.printStackTrace(); } return false; }
private void loadModules(Element root) { Element componentRoot = findComponent(root, "ProjectModuleManager"); if (componentRoot == null) return; final Element modules = componentRoot.getChild("modules"); for (Element moduleElement : JDOMUtil.getChildren(modules, "module")) { final String path = moduleElement.getAttributeValue("filepath"); JpsModule module = loadModule(path); myProject.addModule(module); } }
private Element loadRootElement(final File file) { try { final Element element = JDOMUtil.loadDocument(file).getRootElement(); myMacroToPathMap.substitute(element, SystemInfo.isFileSystemCaseSensitive); return element; } catch (JDOMException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
public void readExternal(@NotNull URL url) throws InvalidDataException, FileNotFoundException { try { Document document = JDOMUtil.loadDocument(url); readExternal(document, url); } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw new InvalidDataException(e); } catch (JDOMException e) { throw new InvalidDataException(e); } }
@Nullable public static Document loadDocument(final byte[] bytes) { try { return bytes == null || bytes.length == 0 ? null : JDOMUtil.loadDocument(new ByteArrayInputStream(bytes)); } catch (JDOMException e) { return null; } catch (IOException e) { return null; } }
public void writeConfiguration(ProjectDescriptor pd, final PrintWriter out) { out.println("id: " + myId); out.println( JDOMUtil.writeElement(XmlSerializer.serialize(JpsFlexBCState.getState(myBC)), "\n")); final JpsFlexModuleOrProjectCompilerOptions moduleOptions = myBC.getModule().getProperties().getModuleLevelCompilerOptions(); out.println( JDOMUtil.writeElement( XmlSerializer.serialize(((JpsFlexCompilerOptionsImpl) moduleOptions).getState()), "\n")); final JpsFlexModuleOrProjectCompilerOptions projectOptions = JpsFlexProjectLevelCompilerOptionsExtension.getProjectLevelCompilerOptions( myBC.getModule().getProject()); out.println( JDOMUtil.writeElement( XmlSerializer.serialize(((JpsFlexCompilerOptionsImpl) projectOptions).getState()), "\n")); }
/** * Changes parent keymap for the Vim * * @return true if document was changed successfully */ private static boolean configureVimParentKeymap( final String path, @NotNull final Document document, final boolean showNotification) throws IOException, InvalidDataException { final Element rootElement = document.getRootElement(); final String parentKeymapName = rootElement.getAttributeValue("parent"); final VimKeymapDialog vimKeymapDialog = new VimKeymapDialog(parentKeymapName); vimKeymapDialog.show(); if (vimKeymapDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { return false; } rootElement.removeAttribute("parent"); final Keymap parentKeymap = vimKeymapDialog.getSelectedKeymap(); final String keymapName = parentKeymap.getName(); VimKeymapConflictResolveUtil.resolveConflicts(rootElement, parentKeymap); // We cannot set a user-defined modifiable keymap as the parent of our Vim keymap so we have to // copy its shortcuts if (parentKeymap.canModify()) { final KeymapImpl vimKeyMap = new KeymapImpl(); final KeymapManager keymapManager = KeymapManager.getInstance(); final KeymapManagerImpl keymapManagerImpl = (KeymapManagerImpl) keymapManager; final Keymap[] allKeymaps = keymapManagerImpl.getAllKeymaps(); vimKeyMap.readExternal(rootElement, allKeymaps); final HashSet<String> ownActions = new HashSet<String>(Arrays.asList(vimKeyMap.getOwnActionIds())); final KeymapImpl parentKeymapImpl = (KeymapImpl) parentKeymap; for (String parentAction : parentKeymapImpl.getOwnActionIds()) { if (!ownActions.contains(parentAction)) { final List<Shortcut> shortcuts = Arrays.asList(parentKeymap.getShortcuts(parentAction)); rootElement.addContent( VimKeymapConflictResolveUtil.createActionElement(parentAction, shortcuts)); } } final Keymap grandParentKeymap = parentKeymap.getParent(); rootElement.setAttribute("parent", grandParentKeymap.getName()); } else { rootElement.setAttribute("parent", keymapName); } VimPlugin.getInstance().setPreviousKeyMap(keymapName); // Save modified keymap to the file JDOMUtil.writeDocument(document, path, "\n"); if (showNotification) { Notifications.Bus.notify( new Notification( VimPlugin.IDEAVIM_NOTIFICATION_ID, VimPlugin.IDEAVIM_NOTIFICATION_TITLE, "Successfully configured vim keymap to be based on " + parentKeymap.getPresentableName(), NotificationType.INFORMATION)); } return true; }