summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/openapi/components/impl/stores/FileBasedStorage.java
blob: 923072d4fb1d9fc5593095d121933d65d6ecc771 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
 * 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.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.openapi.components.impl.stores;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.StateStorageException;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.components.TrackingPathMacroSubstitutor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.tracker.VirtualFileTracker;
import com.intellij.util.io.fs.FileSystem;
import com.intellij.util.io.fs.IFile;
import com.intellij.util.messages.MessageBus;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.picocontainer.PicoContainer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class FileBasedStorage extends XmlElementStorage {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.components.impl.stores.FileBasedStorage");

  private static boolean ourConfigDirectoryRefreshed = false;

  private final String myFilePath;
  private final IFile myFile;
  private final String myRootElementName;
  private volatile VirtualFile myCachedVirtualFile;

  public FileBasedStorage(@Nullable TrackingPathMacroSubstitutor pathMacroManager,
                          StreamProvider streamProvider,
                          String filePath,
                          String fileSpec,
                          String rootElementName,
                          @NotNull Disposable parentDisposable,
                          PicoContainer picoContainer,
                          ComponentRoamingManager componentRoamingManager,
                          ComponentVersionProvider componentVersionProvider) {
    super(pathMacroManager, parentDisposable, rootElementName, streamProvider, fileSpec, componentRoamingManager, componentVersionProvider);

    refreshConfigDirectoryOnce();

    myRootElementName = rootElementName;
    myFilePath = filePath;
    myFile = FileSystem.FILE_SYSTEM.createFile(myFilePath);

    VirtualFileTracker virtualFileTracker = ServiceManager.getService(VirtualFileTracker.class);
    MessageBus messageBus = (MessageBus)picoContainer.getComponentInstanceOfType(MessageBus.class);
    if (virtualFileTracker != null && messageBus != null) {
      final String path = myFile.getAbsolutePath();
      final String fileUrl = LocalFileSystem.PROTOCOL_PREFIX + path.replace(File.separatorChar, '/');

      final Listener listener = messageBus.syncPublisher(STORAGE_TOPIC);
      virtualFileTracker.addTracker(fileUrl, new VirtualFileAdapter() {
        @Override
        public void fileMoved(@NotNull VirtualFileMoveEvent event) {
          myCachedVirtualFile = null;
        }

        @Override
        public void fileDeleted(@NotNull VirtualFileEvent event) {
          myCachedVirtualFile = null;
        }

        @Override
        public void contentsChanged(@NotNull final VirtualFileEvent event) {
          if (!isDisposed()) {
            listener.storageFileChanged(event, FileBasedStorage.this);
          }
        }
      }, false, this);
    }
  }

  private static void refreshConfigDirectoryOnce() {
    Application app = ApplicationManager.getApplication();
    if (!ourConfigDirectoryRefreshed && (app.isUnitTestMode() || app.isDispatchThread())) {
      try {
        VirtualFile configDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(PathManager.getConfigPath());
        if (configDir != null) {
          VfsUtilCore.visitChildrenRecursively(configDir, new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {
              return !"componentVersions".equals(file.getName());
            }
          });
          VfsUtil.markDirtyAndRefresh(false, true, false, configDir);
        }
      }
      finally {
        ourConfigDirectoryRefreshed = true;
      }
    }
  }

  @Override
  protected MySaveSession createSaveSession(final MyExternalizationSession externalizationSession) {
    return new FileSaveSession(externalizationSession);
  }

  public void resetProviderCache() {
    myProviderUpToDateHash = -1;
    if (myRemoteVersionProvider != null) {
      myRemoteVersionProvider.myProviderVersions = null;
    }
  }

  private class FileSaveSession extends MySaveSession {
    protected FileSaveSession(MyExternalizationSession externalizationSession) {
      super(externalizationSession);
    }

    @Override
    protected boolean physicalContentNeedsSave() {
      VirtualFile file = getVirtualFile();
      if (file == null || !file.exists())
        return !myStorageData.isEmpty();
      return !StorageUtil.contentEquals(getDocumentToSave(), file);
    }

    @Override
    protected int calcHash() {
      int hash = myStorageData.getHash();
      if (myPathMacroSubstitutor != null) {
        hash = 31 * hash + myPathMacroSubstitutor.hashCode();
      }
      return hash;
    }

    @Override
    protected void doSave() throws StateStorageException {
      if (myBlockSavingTheContent) {
        return;
      }
      if (ApplicationManager.getApplication().isUnitTestMode() && myFile != null && StringUtil.startsWithChar(myFile.getPath(), '$')) {
        throw new StateStorageException("It seems like some macros were not expanded for path: " + myFile.getPath());
      }

      LOG.assertTrue(myFile != null);
      myCachedVirtualFile = StorageUtil.save(myFile, getDocumentToSave(), this);
    }

    @NotNull
    @Override
    public Collection<IFile> getStorageFilesToSave() throws StateStorageException {
      boolean needsSave = needsSave();
      if (needsSave) {
        if (LOG.isDebugEnabled()) {
          LOG.info("File " + myFileSpec + " needs save; hash=" + myUpToDateHash + "; currentHash=" + calcHash() + "; " +
                   "content needs save=" + physicalContentNeedsSave());
        }
        return getAllStorageFiles();
      }
      else {
        return Collections.emptyList();
      }
    }

    @NotNull
    @Override
    public List<IFile> getAllStorageFiles() {
      return Collections.singletonList(myFile);
    }
  }

  @Override
  protected void loadState(final StorageData result, final Element element) throws StateStorageException {
    ((FileStorageData)result).myFilePath = myFile.getAbsolutePath();
    super.loadState(result, element);
  }

  @Override
  @NotNull
  protected StorageData createStorageData() {
    return new FileStorageData(myRootElementName);
  }

  public static class FileStorageData extends StorageData {
    String myFilePath;

    public FileStorageData(final String rootElementName) {
      super(rootElementName);
    }

    protected FileStorageData(FileStorageData storageData) {
      super(storageData);
      myFilePath = storageData.myFilePath;
    }

    @Override
    public StorageData clone() {
      return new FileStorageData(this);
    }

    @NonNls
    public String toString() {
      return "FileStorageData[" + myFilePath + "]";
    }
  }

  @Nullable
  public VirtualFile getVirtualFile() {
    VirtualFile virtualFile = myCachedVirtualFile;
    if (virtualFile == null) {
      myCachedVirtualFile = virtualFile = StorageUtil.getVirtualFile(myFile);
    }
    return virtualFile;
  }

  public File getFile() {
    return new File(myFile.getPath());
  }

  @Override
  @Nullable
  protected Document loadDocument() throws StateStorageException {
    myBlockSavingTheContent = false;
    try {
      VirtualFile file = getVirtualFile();
      if (file == null || file.isDirectory() || !file.isValid()) {
        LOG.info("Document was not loaded for " + myFileSpec + " file is " + (file == null ? "null" : "directory"));
        return null;
      }
      if (file.getLength() == 0) {
        return processReadException(null);
      }
      return loadDocumentImpl(file);
    }
    catch (final JDOMException e) {
      return processReadException(e);
    }
    catch (final IOException e) {
      return processReadException(e);
    }
  }

  @Nullable
  private Document processReadException(@Nullable final Exception e) {
    boolean contentTruncated = e == null;
    myBlockSavingTheContent = isProjectOrModuleOrWorkspaceFile() && !contentTruncated;
    if (!ApplicationManager.getApplication().isUnitTestMode() && !ApplicationManager.getApplication().isHeadlessEnvironment()) {
      if (e != null) {
        LOG.info(e);
      }
      final String message = "Cannot load settings from file '" + myFile.getPath() + "': " + (e == null ? "content truncated" : e.getLocalizedMessage()) + "\n" +
                             getInvalidContentMessage(contentTruncated);
      Notifications.Bus.notify(
        new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", message, NotificationType.WARNING));
    }

    return null;
  }

  private boolean isProjectOrModuleOrWorkspaceFile() {
    return StorageUtil.isProjectOrModuleFile(myFileSpec) || myFileSpec.equals(StoragePathMacros.WORKSPACE_FILE);
  }

  private String getInvalidContentMessage(boolean contentTruncated) {
    return isProjectOrModuleOrWorkspaceFile() && !contentTruncated ? "Please correct the file content" : "File content will be recreated";
  }

  private static Document loadDocumentImpl(final VirtualFile file) throws IOException, JDOMException {
    InputStream stream = file.getInputStream();
    try {
      return JDOMUtil.loadDocument(stream);
    }
    finally {
      stream.close();
    }
  }

  public String getFileName() {
    return myFile.getName();
  }

  public String getFilePath() {
    return myFilePath;
  }

  @Override
  public void setDefaultState(final Element element) {
    element.setName(myRootElementName);
    super.setDefaultState(element);
  }

  protected boolean physicalContentNeedsSave(final Document doc) {
    VirtualFile file = getVirtualFile();
    return file == null || !file.exists() || !StorageUtil.contentEquals(doc, file);
  }

  @Nullable
  public File updateFileExternallyFromStreamProviders() throws IOException {
    StorageData loadedData = loadData(true);
    Document document = getDocument(loadedData);
    if (physicalContentNeedsSave(document)) {
      File file = new File(myFile.getAbsolutePath());
      JDOMUtil.writeDocument(document, file, "\n");
      return file;
    }

    return null;
  }
}