cleanup — introduce JDOMUtil.load — just load element and close input stream

avoid Document usage
This commit is contained in:
Vladimir Krivosheev
2014-11-18 17:56:47 +01:00
parent 0021bf8af8
commit d6834cec6b
24 changed files with 188 additions and 240 deletions
@@ -22,7 +22,6 @@ import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.profile.Profile;
import com.intellij.profile.ProfileManager;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
@@ -36,25 +35,23 @@ public class InspectionProfileLoadUtil {
@NonNls private static final String PROFILE_NAME_TAG = "profile_name";
@NonNls public static final String PROFILE_TAG = "profile";
private static String getProfileName(@NotNull File file, @NotNull Document document) {
String name = getRootElementAttribute(PROFILE_NAME_TAG, document);
if (name != null) return name;
return FileUtil.getNameWithoutExtension(file);
private static String getProfileName(@NotNull File file, @NotNull Element element) {
String name = getRootElementAttribute(PROFILE_NAME_TAG, element);
return name != null ? name : FileUtil.getNameWithoutExtension(file);
}
private static String getRootElementAttribute(@NotNull Document document, @NonNls String name) {
Element root = document.getRootElement();
return root.getAttributeValue(name);
private static String getRootElementAttribute(@NotNull Element element, @NonNls String name) {
return element.getAttributeValue(name);
}
@Nullable
private static String getRootElementAttribute(@NonNls String name, final Document doc) {
return getRootElementAttribute(doc, name);
private static String getRootElementAttribute(@NonNls String name, @NotNull Element element) {
return getRootElementAttribute(element, name);
}
@NotNull
public static String getProfileName(@NotNull Document document) {
String name = getRootElementAttribute(document, PROFILE_NAME_TAG);
public static String getProfileName(@NotNull Element element) {
String name = getRootElementAttribute(element, PROFILE_NAME_TAG);
if (name != null) return name;
return "unnamed";
}
@@ -63,14 +60,13 @@ public class InspectionProfileLoadUtil {
public static Profile load(@NotNull File file,
@NotNull InspectionToolRegistrar registrar,
@NotNull ProfileManager profileManager) throws JDOMException, IOException, InvalidDataException {
Document document = JDOMUtil.loadDocument(file);
InspectionProfileImpl profile = new InspectionProfileImpl(getProfileName(file, document), registrar, profileManager);
Element rootElement = document.getRootElement();
final Element profileElement = rootElement.getChild(PROFILE_TAG);
Element element = JDOMUtil.loadDocument(file).getRootElement();
InspectionProfileImpl profile = new InspectionProfileImpl(getProfileName(file, element), registrar, profileManager);
final Element profileElement = element.getChild(PROFILE_TAG);
if (profileElement != null) {
rootElement = profileElement;
element = profileElement;
}
profile.readExternal(rootElement);
profile.readExternal(element);
return profile;
}
}
@@ -18,7 +18,6 @@ package com.intellij.openapi.application;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PlatformUtilsCore;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -51,8 +50,7 @@ public class ApplicationNamesInfo {
private ApplicationNamesInfo() {
try {
//noinspection HardCodedStringLiteral
final Document doc = JDOMUtil.loadDocument(ApplicationNamesInfo.class.getResourceAsStream("/idea/" + getComponentName() + ".xml"));
readInfo(doc.getRootElement());
readInfo((JDOMUtil.load(ApplicationNamesInfo.class.getResourceAsStream("/idea/" + getComponentName() + ".xml"))));
}
catch (Exception e) {
//noinspection CallToPrintStackTrace
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,21 +15,40 @@
*/
package com.intellij.openapi.options;
import com.intellij.openapi.util.InvalidDataException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/**
* @author yole
*/
public abstract class BaseSchemeProcessor<T extends ExternalizableScheme> implements SchemeProcessor<T> {
@Override
public void initScheme(@NotNull T scheme) {
}
@Override
public void onSchemeAdded(@NotNull final T scheme) {
}
@Override
public void onSchemeDeleted(@NotNull final T scheme) {
}
@Override
public void onCurrentSchemeChanged(final Scheme newCurrentScheme) {
}
public T readScheme(@NotNull Element element) throws InvalidDataException, IOException, JDOMException {
return readScheme(new Document(element));
}
@Override
public T readScheme(@NotNull Document schemeContent) throws InvalidDataException, IOException, JDOMException {
throw new AbstractMethodError();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,11 @@ import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/**
* Please extend {@link com.intellij.openapi.options.BaseSchemeProcessor} to avoid compatibility issues
*/
public interface SchemeProcessor<T extends ExternalizableScheme> {
@Deprecated
T readScheme(@NotNull Document schemeContent) throws InvalidDataException, IOException, JDOMException;
Parent writeScheme(@NotNull T scheme) throws WriteExternalException;
@@ -510,7 +510,7 @@ public class PluginManagerCore {
final Comparator<PluginId> idComparator = builder.comparator();
return new Comparator<IdeaPluginDescriptor>() {
@Override
public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) {
public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) {
final PluginId pluginId1 = o1.getPluginId();
final PluginId pluginId2 = o2.getPluginId();
if (pluginId1.getIdString().equals(CORE_PLUGIN_ID)) return -1;
@@ -526,7 +526,7 @@ public class PluginManagerCore {
// needed to make sure that extensions are always in the same order
Collections.sort(ids, new Comparator<PluginId>() {
@Override
public int compare(PluginId o1, PluginId o2) {
public int compare(@NotNull PluginId o1, @NotNull PluginId o2) {
return o2.getIdString().compareTo(o1.getIdString());
}
});
@@ -635,7 +635,7 @@ public class PluginManagerCore {
}
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
public int compare(@NotNull File o1, @NotNull File o2) {
if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE;
if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE;
if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE;
@@ -1161,7 +1161,7 @@ public class PluginManagerCore {
// sort descriptors according to plugin dependencies
Collections.sort(result, new Comparator<IdeaPluginDescriptor>() {
@Override
public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) {
public int compare(@NotNull IdeaPluginDescriptor o1, @NotNull IdeaPluginDescriptor o2) {
return idComparator.compare(o1.getPluginId(), o2.getPluginId());
}
});
@@ -19,13 +19,10 @@ package com.intellij.codeEditor.printing;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.util.containers.HashMap;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class PageSizes {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeEditor.printing.PageSizes");
@@ -100,10 +97,8 @@ class PageSizes {
myNamesToPageSizes = new HashMap();
try {
final Document document = JDOMUtil.loadDocument(PageSizes.class.getResourceAsStream(PAGE_SIZES_RESOURCE));
final List elements = document.getRootElement().getChildren(ELEMENT_SIZE);
for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
final Element element = (Element) iterator.next();
//noinspection ConstantConditions
for (Element element : JDOMUtil.load(PageSizes.class.getResourceAsStream(PAGE_SIZES_RESOURCE)).getChildren(ELEMENT_SIZE)) {
String name = element.getAttributeValue(ATTRIBUTE_NAME);
final String widthStr = element.getAttributeValue(ATTRIBUTE_WIDTH);
final String heightStr = element.getAttributeValue(ATTRIBUTE_HEIGHT);
@@ -31,7 +31,6 @@ import com.intellij.util.SmartList;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.xmlb.Converter;
import com.intellij.util.xmlb.annotations.OptionTag;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
@@ -189,8 +188,8 @@ public class TemplateSettings implements PersistentStateComponent<TemplateSettin
mySchemesManager = schemesManagerFactory.createSchemesManager(TEMPLATES_DIR_PATH, new BaseSchemeProcessor<TemplateGroup>() {
@Override
@Nullable
public TemplateGroup readScheme(@NotNull final Document schemeContent) throws InvalidDataException {
return readTemplateFile(schemeContent, schemeContent.getRootElement().getAttributeValue("group"), false, false,
public TemplateGroup readScheme(@NotNull Element element) throws InvalidDataException {
return readTemplateFile(element, element.getAttributeValue("group"), false, false,
getClass().getClassLoader());
}
@@ -458,7 +457,7 @@ public class TemplateSettings implements PersistentStateComponent<TemplateSettin
String templateName = getDefaultTemplateName(defTemplate);
InputStream inputStream = DecodeDefaultsUtil.getDefaultsInputStream(provider, defTemplate);
if (inputStream != null) {
TemplateGroup group = readTemplateFile(JDOMUtil.loadDocument(inputStream), templateName, true, registerTemplate, provider.getClass().getClassLoader());
TemplateGroup group = readTemplateFile(JDOMUtil.load(inputStream), templateName, true, registerTemplate, provider.getClass().getClassLoader());
if (group != null && group.getReplace() != null) {
for (TemplateImpl template : myTemplates.get(group.getReplace())) {
removeTemplate(template);
@@ -472,26 +471,20 @@ public class TemplateSettings implements PersistentStateComponent<TemplateSettin
}
@Nullable
private TemplateGroup readTemplateFile(Document document, @NonNls String defGroupName, boolean isDefault, boolean registerTemplate, ClassLoader classLoader) throws InvalidDataException {
if (document == null) {
throw new InvalidDataException();
}
Element root = document.getRootElement();
if (!TEMPLATE_SET.equals(root.getName())) {
private TemplateGroup readTemplateFile(@NotNull Element element, @NonNls String defGroupName, boolean isDefault, boolean registerTemplate, ClassLoader classLoader) throws InvalidDataException {
if (!TEMPLATE_SET.equals(element.getName())) {
throw new InvalidDataException();
}
String groupName = root.getAttributeValue(GROUP);
String groupName = element.getAttributeValue(GROUP);
if (groupName == null || groupName.isEmpty()) groupName = defGroupName;
TemplateGroup result = new TemplateGroup(groupName, root.getAttributeValue("REPLACE"));
TemplateGroup result = new TemplateGroup(groupName, element.getAttributeValue("REPLACE"));
Map<String, TemplateImpl> created = new LinkedHashMap<String, TemplateImpl>();
for (final Object o1 : root.getChildren(TEMPLATE)) {
Element element = (Element)o1;
TemplateImpl template = readTemplateFromElement(isDefault, groupName, element, classLoader);
for (Element child : element.getChildren(TEMPLATE)) {
TemplateImpl template = readTemplateFromElement(isDefault, groupName, child, classLoader);
TemplateImpl existing = getTemplate(template.getKey(), template.getGroupName());
boolean defaultTemplateModified = isDefault && (myState.deletedKeys.contains(TemplateKey.keyOf(template)) ||
myTemplatesById.containsKey(template.getId()) ||
@@ -50,7 +50,6 @@ import com.intellij.profile.Profile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.ui.UIUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
@@ -85,9 +84,9 @@ public class InspectionProfileManagerImpl extends InspectionProfileManager imple
SchemeProcessor<InspectionProfileImpl> processor = new BaseSchemeProcessor<InspectionProfileImpl>() {
@Override
public InspectionProfileImpl readScheme(@NotNull final Document document) {
InspectionProfileImpl profile = new InspectionProfileImpl(InspectionProfileLoadUtil.getProfileName(document), myRegistrar, InspectionProfileManagerImpl.this);
read(profile, document.getRootElement());
public InspectionProfileImpl readScheme(@NotNull Element element) {
InspectionProfileImpl profile = new InspectionProfileImpl(InspectionProfileLoadUtil.getProfileName(element), myRegistrar, InspectionProfileManagerImpl.this);
read(profile, element);
return profile;
}
@@ -132,7 +131,7 @@ public class InspectionProfileManagerImpl extends InspectionProfileManager imple
try {
profile.readExternal(element);
}
catch (Exception e) {
catch (Exception ignored) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
@@ -233,7 +232,7 @@ public class InspectionProfileManagerImpl extends InspectionProfileManager imple
catch (JDOMException e) {
throw e;
}
catch (Exception e) {
catch (Exception ignored) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
@@ -130,20 +130,15 @@ public class CodeStyleSchemeImpl implements JDOMExternalizable, CodeStyleScheme,
myCodeStyleSettings.readExternal(element);
}
public static CodeStyleSchemeImpl readScheme(Document document) throws InvalidDataException {
Element root = document.getRootElement();
if (root == null){
throw new InvalidDataException("No root element in code style scheme file");
}
String schemeName = root.getAttributeValue(NAME);
String parentName = root.getAttributeValue(PARENT);
public static CodeStyleSchemeImpl readScheme(@NotNull Element element) throws InvalidDataException {
String schemeName = element.getAttributeValue(NAME);
String parentName = element.getAttributeValue(PARENT);
if (schemeName == null) {
throw new InvalidDataException("Name attribute missing in code style scheme file");
}
return new CodeStyleSchemeImpl(schemeName, parentName, root);
return new CodeStyleSchemeImpl(schemeName, parentName, element);
}
public void save(File dir) throws WriteExternalException{
@@ -27,13 +27,10 @@ import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiBundle;
import com.intellij.psi.codeStyle.CodeStyleScheme;
import com.intellij.psi.codeStyle.CodeStyleSchemes;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Collection;
/**
@@ -53,8 +50,8 @@ public abstract class CodeStyleSchemesImpl extends CodeStyleSchemes implements E
public CodeStyleSchemesImpl(SchemesManagerFactory schemesManagerFactory) {
SchemeProcessor<CodeStyleSchemeImpl> processor = new BaseSchemeProcessor<CodeStyleSchemeImpl>() {
@Override
public CodeStyleSchemeImpl readScheme(@NotNull final Document schemeContent) throws IOException, JDOMException, InvalidDataException {
return CodeStyleSchemeImpl.readScheme(schemeContent);
public CodeStyleSchemeImpl readScheme(@NotNull Element element) throws InvalidDataException {
return CodeStyleSchemeImpl.readScheme(element);
}
@Override
@@ -22,10 +22,8 @@ import com.intellij.openapi.options.BaseSchemeProcessor;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Parent;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -56,12 +54,9 @@ abstract public class ToolsProcessor<T extends Tool> extends BaseSchemeProcessor
@NonNls private static final String ELEMENT_OPTION = "option";
@NonNls private static final String ATTRIBUTE_VALUE = "value";
@NonNls private static final String APPLICATION_HOME_MACRO = "$APPLICATION_HOME_DIR$";
@Override
public ToolsGroup<T> readScheme(@NotNull final Document document) throws InvalidDataException, IOException, JDOMException {
Element root = document.getRootElement();
if (root == null || !TOOL_SET.equals(root.getName())) {
public ToolsGroup<T> readScheme(@NotNull Element root) throws InvalidDataException, IOException, JDOMException {
if (!TOOL_SET.equals(root.getName())) {
throw new InvalidDataException();
}
@@ -71,9 +66,7 @@ abstract public class ToolsProcessor<T extends Tool> extends BaseSchemeProcessor
final PathMacroManager macroManager = PathMacroManager.getInstance(ApplicationManager.getApplication());
for (final Object o : root.getChildren(TOOL)) {
Element element = (Element)o;
for (Element element : root.getChildren(TOOL)) {
T tool = createTool();
readToolAttributes(element, tool);
@@ -93,10 +86,10 @@ abstract public class ToolsProcessor<T extends Tool> extends BaseSchemeProcessor
}
}
if (COMMAND.equals(name)) {
tool.setProgram(macroManager.expandPath(ToolManager.convertString(value)));
tool.setProgram(macroManager.expandPath(BaseToolManager.convertString(value)));
}
if (PARAMETERS.equals(name)) {
tool.setParameters(macroManager.expandPath(ToolManager.convertString(value)));
tool.setParameters(macroManager.expandPath(BaseToolManager.convertString(value)));
}
}
}
@@ -117,8 +110,8 @@ abstract public class ToolsProcessor<T extends Tool> extends BaseSchemeProcessor
}
protected void readToolAttributes(Element element, T tool) {
tool.setName(ToolManager.convertString(element.getAttributeValue(NAME)));
tool.setDescription(ToolManager.convertString(element.getAttributeValue(DESCRIPTION)));
tool.setName(BaseToolManager.convertString(element.getAttributeValue(NAME)));
tool.setDescription(BaseToolManager.convertString(element.getAttributeValue(DESCRIPTION)));
tool.setShownInMainMenu(Boolean.valueOf(element.getAttributeValue(SHOW_IN_MAIN_MENU)).booleanValue());
tool.setShownInEditor(Boolean.valueOf(element.getAttributeValue(SHOW_IN_EDITOR)).booleanValue());
tool.setShownInProjectViews(Boolean.valueOf(element.getAttributeValue(SHOW_IN_PROJECT)).booleanValue());
@@ -137,9 +130,7 @@ abstract public class ToolsProcessor<T extends Tool> extends BaseSchemeProcessor
@Override
public Element writeScheme(@NotNull final ToolsGroup<T> scheme) throws WriteExternalException {
Element groupElement = new Element(TOOL_SET);
if (scheme.getName() != null) {
groupElement.setAttribute(ATTRIBUTE_NAME, scheme.getName());
}
groupElement.setAttribute(ATTRIBUTE_NAME, scheme.getName());
for (T tool : scheme.getElements()) {
saveTool(tool, groupElement);
@@ -34,7 +34,6 @@ import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.NamedJDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
@@ -64,8 +63,8 @@ public class QuickListsManager implements ExportableApplicationComponent, NamedJ
mySchemesManager = schemesManagerFactory.createSchemesManager(StoragePathMacros.ROOT_CONFIG + "/quicklists",
new BaseSchemeProcessor<QuickList>() {
@Override
public QuickList readScheme(@NotNull final Document schemeContent) {
return loadListFromDocument(schemeContent);
public QuickList readScheme(@NotNull Element element) {
return loadListFromDocument(element);
}
@Override
@@ -87,9 +86,9 @@ public class QuickListsManager implements ExportableApplicationComponent, NamedJ
registerActions();
}
private static QuickList loadListFromDocument(Document schemeContent) {
private static QuickList loadListFromDocument(@NotNull Element element) {
QuickList list = new QuickList();
list.readExternal(schemeContent.getRootElement());
list.readExternal(element);
return list;
}
@@ -198,16 +197,15 @@ public class QuickListsManager implements ExportableApplicationComponent, NamedJ
continue;
}
final Document document;
Element element;
try {
document = JDOMUtil.loadDocument(inputStream);
element = JDOMUtil.load(inputStream);
}
catch (JDOMException e) {
LOG.info("Error reading quick list from " + path + ": " + e.getLocalizedMessage());
throw e;
}
final QuickList scheme = loadListFromDocument(document);
mySchemesManager.addNewScheme(scheme, false);
mySchemesManager.addNewScheme(loadListFromDocument(element), false);
}
catch (final Exception e) {
ApplicationManager.getApplication().invokeLater(
@@ -188,7 +188,7 @@ public class StorageUtil {
try {
virtualFile.delete(requestor);
}
catch (FileNotFoundException e) {
catch (FileNotFoundException ignored) {
throw new ReadOnlyModificationException(virtualFile);
}
finally {
@@ -278,37 +278,15 @@ public class StorageUtil {
return true;
}
@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;
}
}
@Nullable
public static Element loadElement(@Nullable InputStream stream) {
if (stream == null) {
return null;
}
try {
try {
return JDOMUtil.loadDocument(stream).detachRootElement();
}
finally {
stream.close();
}
return JDOMUtil.load(stream);
}
catch (JDOMException e) {
catch (JDOMException ignored) {
return null;
}
catch (IOException e) {
catch (IOException ignored) {
return null;
}
}
@@ -30,10 +30,8 @@ import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
@@ -111,8 +109,7 @@ public abstract class XmlElementStorage extends StateStorageBase<StorageData> {
@Nullable
protected final Element loadDataFromStreamProvider() throws IOException, JDOMException {
assert myStreamProvider != null;
InputStream inputStream = myStreamProvider.loadContent(myFileSpec, myRoamingType);
return inputStream == null ? null : JDOMUtil.loadDocument(inputStream).detachRootElement();
return JDOMUtil.load(myStreamProvider.loadContent(myFileSpec, myRoamingType));
}
protected final void loadState(@NotNull StorageData result, @NotNull Element element) {
@@ -260,9 +257,4 @@ public abstract class XmlElementStorage extends StateStorageBase<StorageData> {
}
}
}
@TestOnly
public void resetData() {
myLoadedData = null;
}
}
@@ -42,7 +42,6 @@ import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ui.UIUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
@@ -140,9 +139,7 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Name
}
try {
InputStream inputStream = attributesEP.getLoaderForClass().getResourceAsStream(attributesEP.file);
Document document = JDOMUtil.loadDocument(inputStream);
((AbstractColorsScheme)editorColorsScheme).readAttributes(document.getRootElement());
((AbstractColorsScheme)editorColorsScheme).readAttributes(JDOMUtil.load(inputStream));
}
catch (Exception e1) {
LOG.error(e1);
@@ -159,34 +156,29 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Name
return null;
}
final Document document;
Element element;
try {
document = JDOMUtil.loadDocument(inputStream);
element = JDOMUtil.load(inputStream);
}
catch (JDOMException e) {
LOG.info("Error reading scheme from " + schemePath + ": " + e.getLocalizedMessage());
throw e;
}
return loadSchemeFromDocument(document, false);
return loadSchemeFromDocument(element, false);
}
@NotNull
private static EditorColorsSchemeImpl loadSchemeFromDocument(final Document document,
final boolean isEditable)
throws InvalidDataException {
final Element root = document.getRootElement();
if (root == null || !SCHEME_NODE_NAME.equals(root.getName())) {
private static EditorColorsSchemeImpl loadSchemeFromDocument(@NotNull Element element, boolean isEditable) throws InvalidDataException {
if (!SCHEME_NODE_NAME.equals(element.getName())) {
throw new InvalidDataException();
}
final EditorColorsSchemeImpl scheme = isEditable
// editable scheme
? new EditorColorsSchemeImpl(null, DefaultColorSchemesManager.getInstance())
//not editable scheme
: new ReadOnlyColorsSchemeImpl(null, DefaultColorSchemesManager.getInstance());
scheme.readExternal(root);
// editable scheme
? new EditorColorsSchemeImpl(null, DefaultColorSchemesManager.getInstance())
//not editable scheme
: new ReadOnlyColorsSchemeImpl(null, DefaultColorSchemesManager.getInstance());
scheme.readExternal(element);
return scheme;
}
@@ -224,7 +216,7 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Name
ArrayList<EditorColorsScheme> schemes = new ArrayList<EditorColorsScheme>(mySchemesManager.getAllSchemes());
Collections.sort(schemes, new Comparator<EditorColorsScheme>() {
@Override
public int compare(EditorColorsScheme s1, EditorColorsScheme s2) {
public int compare(@NotNull EditorColorsScheme s1, @NotNull EditorColorsScheme s2) {
if (isDefaultScheme(s1) && !isDefaultScheme(s2)) return -1;
if (!isDefaultScheme(s1) && isDefaultScheme(s2)) return 1;
@@ -379,10 +371,10 @@ public class EditorColorsManagerImpl extends EditorColorsManager implements Name
private final class MySchemeProcessor extends BaseSchemeProcessor<EditorColorsSchemeImpl> implements SchemeExtensionProvider {
@Override
public EditorColorsSchemeImpl readScheme(@NotNull final Document document)
public EditorColorsSchemeImpl readScheme(@NotNull Element element)
throws InvalidDataException {
return loadSchemeFromDocument(document, true);
return loadSchemeFromDocument(element, true);
}
@Override
@@ -55,7 +55,6 @@ import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -183,11 +182,7 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOME
myMessageBus = bus;
mySchemesManager = schemesManagerFactory.createSchemesManager(FILE_SPEC, new BaseSchemeProcessor<AbstractFileType>() {
@Override
public AbstractFileType readScheme(@NotNull final Document document) throws InvalidDataException {
Element root = document.getRootElement();
if (!ELEMENT_FILETYPE.equals(root.getName())) {
throw new InvalidDataException();
}
public AbstractFileType readScheme(@NotNull Element root) {
Element element = root.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING);
if (element != null) {
final SyntaxTable table = AbstractFileType.readSyntaxTable(element);
@@ -27,7 +27,6 @@ import com.intellij.openapi.options.SchemesManagerFactory;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -48,7 +47,6 @@ public class KeymapManagerImpl extends KeymapManagerEx implements PersistentStat
private String myActiveKeymapName;
private final Map<String, String> myBoundShortcuts = new HashMap<String, String>();
@NonNls private static final String KEYMAP = "keymap";
@NonNls private static final String ACTIVE_KEYMAP = "active_keymap";
@NonNls private static final String NAME_ATTRIBUTE = "name";
private final SchemesManager<Keymap, KeymapImpl> mySchemesManager;
@@ -59,8 +57,10 @@ public class KeymapManagerImpl extends KeymapManagerEx implements PersistentStat
mySchemesManager = factory.createSchemesManager(KEYMAPS_DIR_PATH,
new BaseSchemeProcessor<KeymapImpl>() {
@Override
public KeymapImpl readScheme(@NotNull final Document schemeContent) throws InvalidDataException {
return readKeymap(schemeContent);
public KeymapImpl readScheme(@NotNull Element element) throws InvalidDataException {
KeymapImpl keymap = new KeymapImpl();
keymap.readExternal(element, getAllIncludingDefaultsKeymaps());
return keymap;
}
@Override
@@ -81,7 +81,7 @@ public class KeymapManagerImpl extends KeymapManagerEx implements PersistentStat
: defaultKeymap.getDefaultKeymapName();
for (Keymap keymap : keymaps) {
addKeymap(keymap);
if (systemDefaultKeymap.equals(keymap.getName())) {
if (keymap.getName().equals(systemDefaultKeymap)) {
setActiveKeymap(keymap);
}
}
@@ -205,18 +205,6 @@ public class KeymapManagerImpl extends KeymapManagerEx implements PersistentStat
}
}
@NotNull
private KeymapImpl readKeymap(Document document) throws InvalidDataException {
if (document == null) throw new InvalidDataException();
Element root = document.getRootElement();
if (!KEYMAP.equals(root.getName())) {
throw new InvalidDataException();
}
KeymapImpl keymap = new KeymapImpl();
keymap.readExternal(root, getAllIncludingDefaultsKeymaps());
return keymap;
}
private void fireActiveKeymapChanged() {
for (KeymapManagerListener listener : myListeners) {
listener.activeKeymapChanged(mySchemesManager.getCurrentScheme());
@@ -332,7 +332,7 @@ public class SchemesManagerImpl<T extends Scheme, E extends ExternalizableScheme
try {
Element element;
try {
element = JDOMUtil.loadDocument(file.getInputStream()).detachRootElement();
element = JDOMUtil.load(file.getInputStream());
}
catch (JDOMException e) {
try {
@@ -395,14 +395,14 @@ public class SchemesManagerImpl<T extends Scheme, E extends ExternalizableScheme
return null;
}
else {
E scheme = myProcessor.readScheme(new Document(localCopyElement.getChildren().get(0).clone()));
E scheme = doReadScheme(localCopyElement.getChildren().get(0).clone());
return filter.containsKey(scheme.getName()) ? null : scheme;
}
}
}
else if (element.getName().equals(SHARED_SCHEME_ORIGINAL)) {
SharedSchemeData schemeData = unwrap(element);
E scheme = myProcessor.readScheme(new Document(schemeData.original));
E scheme = doReadScheme(schemeData.original);
if (scheme == null || filter.containsKey(scheme.getName())) {
return null;
}
@@ -410,11 +410,21 @@ public class SchemesManagerImpl<T extends Scheme, E extends ExternalizableScheme
return scheme;
}
else {
E scheme = myProcessor.readScheme(new Document(element));
E scheme = doReadScheme(element);
return filter.containsKey(scheme.getName()) ? null : scheme;
}
}
private E doReadScheme(Element element) throws InvalidDataException, IOException, JDOMException {
if (myProcessor instanceof BaseSchemeProcessor) {
return ((BaseSchemeProcessor<E>)myProcessor).readScheme(element);
}
else {
//noinspection deprecation
return myProcessor.readScheme(new Document(element));
}
}
@Nullable
private Element loadGlobalScheme(@NotNull String schemePath) throws IOException {
StreamProvider provider = getProvider();
@@ -491,7 +501,7 @@ public class SchemesManagerImpl<T extends Scheme, E extends ExternalizableScheme
Element element = StorageUtil.loadElement(provider.loadContent(getFileFullPath(subPath), myRoamingType));
if (element != null) {
SharedSchemeData original = unwrap(element);
E scheme = myProcessor.readScheme(new Document(original.original));
E scheme = doReadScheme(original.original);
if (!alreadyShared(subPath, currentSchemeList)) {
String schemeName = original.name;
String uniqueName = UniqueNameGenerator.generateUniqueName("[shared] " + schemeName, names);
@@ -44,7 +44,6 @@ import com.intellij.util.io.UrlConnectionUtil;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.net.NetUtils;
import com.intellij.util.ui.UIUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.Contract;
@@ -195,7 +194,7 @@ public final class UpdateChecker {
try {
checkPluginsHost(host, downloaded, incompatiblePlugins, true, indicator, buildNumber);
}
catch (ProcessCanceledException e) {
catch (ProcessCanceledException ignored) {
return null;
}
catch (Exception e) {
@@ -334,7 +333,7 @@ public final class UpdateChecker {
try {
return checkPluginsHost(host, downloaded, null, true, progressIndicator, null);
}
catch (ProcessCanceledException e) {
catch (ProcessCanceledException ignored) {
return false;
}
}
@@ -382,11 +381,11 @@ public final class UpdateChecker {
});
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.getInternalBuffer(), 0, bytes.size());
final Document document;
Element element;
try {
document = JDOMUtil.loadDocument(inputStream);
element = JDOMUtil.load(inputStream);
}
catch (JDOMException e) {
catch (JDOMException ignored) {
return false;
}
finally {
@@ -404,7 +403,7 @@ public final class UpdateChecker {
}
boolean success = true;
for (Element pluginElement : document.getRootElement().getChildren("plugin")) {
for (Element pluginElement : element.getChildren("plugin")) {
final String pluginId = pluginElement.getAttributeValue("id");
String pluginUrl = pluginElement.getAttributeValue("url");
final String pluginVersion = pluginElement.getAttributeValue("version");
@@ -506,16 +505,13 @@ public final class UpdateChecker {
public UpdatesInfo convert(URLConnection connection) throws Exception {
InputStream inputStream = HttpRequests.getInputStream(connection);
try {
return new UpdatesInfo(JDOMUtil.loadDocument(inputStream).getRootElement());
return new UpdatesInfo(JDOMUtil.load(inputStream));
}
catch (JDOMException e) {
// Broken xml downloaded. Don't bother telling user.
LOG.info(e);
return null;
}
finally {
inputStream.close();
}
}
});
}
@@ -664,7 +660,7 @@ public final class UpdateChecker {
return args.toString();
}
catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException ignored) {
return ""; // Can't be anyway
}
}
@@ -90,7 +90,7 @@ public class UpdatesInfoXppParserTest extends TestCase {
public static UpdatesInfo read(String fileName) {
final InputStream stream = UpdatesInfoXppParserTest.class.getResourceAsStream(fileName);
try {
return new UpdatesInfo(JDOMUtil.loadDocument(stream).getRootElement());
return new UpdatesInfo(JDOMUtil.load(stream));
}
catch (Exception e) {
throw new RuntimeException(e);
@@ -36,7 +36,6 @@ import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Collection;
@@ -197,18 +196,8 @@ final class StateMap {
@NotNull
public static Element unarchiveState(@NotNull byte[] state) {
InputStream in = null;
try {
try {
in = new SnappyInputStream(new ByteArrayInputStream(state));
//noinspection ConstantConditions
return JDOMUtil.loadDocument(in).detachRootElement();
}
finally {
if (in != null) {
in.close();
}
}
return JDOMUtil.load(new SnappyInputStream(new ByteArrayInputStream(state)));
}
catch (IOException e) {
throw new StateStorageException(e);
@@ -34,6 +34,7 @@ import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -378,6 +379,16 @@ public class JDOMUtil {
}
}
@Contract("null -> null; !null -> !null")
public static Element load(InputStream stream) throws JDOMException, IOException {
try {
return loadDocument(stream).detachRootElement();
}
finally {
stream.close();
}
}
@NotNull
public static Document loadDocument(@NotNull Class clazz, String resource) throws JDOMException, IOException {
InputStream stream = clazz.getResourceAsStream(resource);
@@ -455,7 +466,7 @@ public class JDOMUtil {
writeDocument(document, writer, lineSeparator);
return writer.toString();
}
catch (IOException e) {
catch (IOException ignored) {
// Can't be
return "";
}
@@ -468,8 +479,8 @@ public class JDOMUtil {
writeParent(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException ignored) {
throw new RuntimeException(ignored);
catch (IOException e) {
throw new RuntimeException(e);
}
}
@@ -504,8 +515,8 @@ public class JDOMUtil {
writeElement(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException ignored) {
throw new RuntimeException(ignored);
catch (IOException e) {
throw new RuntimeException(e);
}
}
@@ -608,6 +619,8 @@ public class JDOMUtil {
return buffer == null ? text : buffer.toString();
}
@SuppressWarnings("unused")
@Deprecated
@NotNull
public static List<Element> getChildrenFromAllNamespaces(@NotNull final Element element, @NotNull @NonNls final String name) {
List<Element> result = new SmartList<Element>();
@@ -723,6 +736,8 @@ public class JDOMUtil {
public boolean hasNullAttributes = false;
}
@SuppressWarnings("unused")
@Deprecated
public static org.w3c.dom.Element convertToDOM(@NotNull Element e) {
try {
final Document d = new Document();
@@ -744,6 +759,8 @@ public class JDOMUtil {
}
}
@SuppressWarnings("unused")
@Deprecated
public static Element convertFromDOM(org.w3c.dom.Element e) {
return new DOMBuilder().build(e);
}
@@ -762,7 +779,9 @@ public class JDOMUtil {
}
}
@SuppressWarnings("unused")
@Nullable
@Deprecated
public static Element cloneElement(@NotNull Element element, @NotNull ElementFilter elementFilter) {
Element result = new Element(element.getName(), element.getNamespace());
List<Attribute> attributes = element.getAttributes();
@@ -46,7 +46,6 @@ import org.intellij.plugins.intelliLang.inject.LanguageInjectionConfigBean;
import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport;
import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
import org.intellij.plugins.intelliLang.inject.config.InjectionPlace;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
@@ -161,6 +160,7 @@ public class Configuration extends SimpleModificationTracker implements Persiste
return super.getModificationCount() + myParentConfiguration.getModificationCount();
}
@Override
public boolean replaceInjections(List<? extends BaseInjection> newInjections,
List<? extends BaseInjection> originalInjections,
boolean forceLevel) {
@@ -229,6 +229,7 @@ public class Configuration extends SimpleModificationTracker implements Persiste
throw new UnsupportedOperationException("getAdvancedConfiguration should not be called");
}
@Override
public void loadState(final Element element) {
myInjections.clear();
final THashMap<String, LanguageInjectionSupport> supports = new THashMap<String, LanguageInjectionSupport>();
@@ -305,12 +306,14 @@ public class Configuration extends SimpleModificationTracker implements Persiste
return defaultInjections;
}
@Override
public Element getState() {
return getState(new Element(COMPONENT_NAME));
}
protected Element getState(final Element element) {
Comparator<BaseInjection> comparator = new Comparator<BaseInjection>() {
@Override
public int compare(final BaseInjection o1, final BaseInjection o2) {
return Comparing.compare(o1.getDisplayName(), o2.getDisplayName());
}
@@ -346,34 +349,29 @@ public class Configuration extends SimpleModificationTracker implements Persiste
@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>();
final Element rootElement = document.getRootElement();
final Element state;
if (rootElement.getName().equals(COMPONENT_NAME)) {
state = rootElement;
}
else {
elements.add(rootElement);
//noinspection unchecked
elements.addAll(rootElement.getChildren("component"));
state = ContainerUtil.find(elements, new Condition<Element>() {
public boolean value(final Element element) {
return "component".equals(element.getName()) && COMPONENT_NAME.equals(element.getAttributeValue("name"));
}
});
}
if (state != null) {
final Configuration cfg = new Configuration();
cfg.loadState(state);
return cfg;
}
return null;
final ArrayList<Element> elements = new ArrayList<Element>();
final Element rootElement = JDOMUtil.load(is);
final Element state;
if (rootElement.getName().equals(COMPONENT_NAME)) {
state = rootElement;
}
finally {
is.close();
else {
elements.add(rootElement);
//noinspection unchecked
elements.addAll(rootElement.getChildren("component"));
state = ContainerUtil.find(elements, new Condition<Element>() {
@Override
public boolean value(final Element element) {
return "component".equals(element.getName()) && COMPONENT_NAME.equals(element.getAttributeValue("name"));
}
});
}
if (state != null) {
final Configuration cfg = new Configuration();
cfg.loadState(state);
return cfg;
}
return null;
}
private int importPlaces(final List<BaseInjection> injections) {
@@ -405,6 +403,7 @@ public class Configuration extends SimpleModificationTracker implements Persiste
}
main: for (BaseInjection other : importingInjections) {
final List<BaseInjection> matchingInjections = ContainerUtil.concat(other.getInjectionPlaces(), new Function<InjectionPlace, Collection<? extends BaseInjection>>() {
@Override
public Collection<? extends BaseInjection> fun(final InjectionPlace o) {
final Collection<BaseInjection> collection = placeMap.get(o);
return collection == null? Collections.<BaseInjection>emptyList() : collection;
@@ -496,6 +495,7 @@ public class Configuration extends SimpleModificationTracker implements Persiste
final List<? extends PsiElement> psiElementsToRemove) {
replaceInjectionsWithUndo(project, newInjections, originalInjections, psiElementsToRemove,
new PairProcessor<List<? extends BaseInjection>, List<? extends BaseInjection>>() {
@Override
public boolean process(final List<? extends BaseInjection> add,
final List<? extends BaseInjection> remove) {
replaceInjectionsWithUndoInner(add, remove);
@@ -516,20 +516,24 @@ public class Configuration extends SimpleModificationTracker implements Persiste
final List<? extends PsiElement> psiElementsToRemove,
final PairProcessor<T, T> actualProcessor) {
final UndoableAction action = new GlobalUndoableAction() {
@Override
public void undo() {
actualProcessor.process(remove, add);
}
@Override
public void redo() {
actualProcessor.process(add, remove);
}
};
final List<PsiFile> psiFiles = ContainerUtil.mapNotNull(psiElementsToRemove, new NullableFunction<PsiElement, PsiFile>() {
@Override
public PsiFile fun(final PsiElement psiAnnotation) {
return psiAnnotation instanceof PsiCompiledElement ? null : psiAnnotation.getContainingFile();
}
});
new WriteCommandAction.Simple(project, "Language Injection Configuration Update", PsiUtilCore.toPsiFileArray(psiFiles)) {
@Override
public void run() {
for (PsiElement annotation : psiElementsToRemove) {
annotation.delete();
@@ -42,8 +42,8 @@ public class TaskSettingsTest extends TaskManagerTestCase {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JDOMUtil.writeDocument(new Document(element), stream, "\n");
Document document = JDOMUtil.loadDocument(new ByteArrayInputStream(stream.toByteArray()));
TaskManagerImpl.Config deserialize = XmlSerializer.deserialize(document, TaskManagerImpl.Config.class);
Element element1 = JDOMUtil.load(new ByteArrayInputStream(stream.toByteArray()));
TaskManagerImpl.Config deserialize = XmlSerializer.deserialize(element1, TaskManagerImpl.Config.class);
myTaskManager.loadState(deserialize);
TaskRepository[] repositories = myTaskManager.getAllRepositories();