summaryrefslogtreecommitdiff
path: root/json/src/com/jetbrains/jsonSchema/UserDefinedJsonSchemaConfiguration.java
blob: 8ab70270338d62eed95d766d6b996716288ca009 (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
/*
 * Copyright 2000-2017 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.jetbrains.jsonSchema;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.AtomicClearableLazyValue;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.PatternUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import com.jetbrains.jsonSchema.ide.JsonSchemaService;
import com.jetbrains.jsonSchema.impl.JsonSchemaObject;
import com.jetbrains.jsonSchema.impl.JsonSchemaVersion;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author Irina.Chernushina on 4/19/2017.
 */
@Tag("SchemaInfo")
public class UserDefinedJsonSchemaConfiguration {
  private final static Comparator<Item> ITEM_COMPARATOR = (o1, o2) -> {
    if (o1.isPattern() != o2.isPattern()) return o1.isPattern() ? -1 : 1;
    if (o1.isDirectory() != o2.isDirectory()) return o1.isDirectory() ? -1 : 1;
    return o1.path.compareToIgnoreCase(o2.path);
  };

  public String name;
  public String relativePathToSchema;
  public JsonSchemaVersion schemaVersion = JsonSchemaVersion.SCHEMA_4;
  public boolean applicationDefined;
  public List<Item> patterns = new SmartList<>();
  @Transient
  private final AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>> myCalculatedPatterns =
    new AtomicClearableLazyValue<List<PairProcessor<Project, VirtualFile>>>() {
      @NotNull
      @Override
      protected List<PairProcessor<Project, VirtualFile>> compute() {
        return recalculatePatterns();
      }
    };

  public UserDefinedJsonSchemaConfiguration() {
  }

  public UserDefinedJsonSchemaConfiguration(@NotNull String name,
                                            JsonSchemaVersion schemaVersion,
                                            @NotNull String relativePathToSchema,
                                            boolean applicationDefined,
                                            @Nullable List<Item> patterns) {
    this.name = name;
    this.relativePathToSchema = relativePathToSchema;
    this.schemaVersion = schemaVersion;
    this.applicationDefined = applicationDefined;
    setPatterns(patterns);
  }

  public String getName() {
    return name;
  }

  public void setName(@NotNull String name) {
    this.name = name;
  }

  public String getRelativePathToSchema() {
    return relativePathToSchema;
  }

  public JsonSchemaVersion getSchemaVersion() {
    return schemaVersion;
  }

  public void setSchemaVersion(JsonSchemaVersion schemaVersion) {
    this.schemaVersion = schemaVersion;
  }

  public void setRelativePathToSchema(String relativePathToSchema) {
    this.relativePathToSchema = relativePathToSchema;
  }

  public boolean isApplicationDefined() {
    return applicationDefined;
  }

  public void setApplicationDefined(boolean applicationDefined) {
    this.applicationDefined = applicationDefined;
  }

  public List<Item> getPatterns() {
    return patterns;
  }

  public void setPatterns(@Nullable List<Item> patterns) {
    this.patterns.clear();
    if (patterns != null) this.patterns.addAll(patterns);
    Collections.sort(this.patterns, ITEM_COMPARATOR);
    myCalculatedPatterns.drop();
  }

  public void refreshPatterns() {
    myCalculatedPatterns.drop();
  }

  @NotNull
  public List<PairProcessor<Project, VirtualFile>> getCalculatedPatterns() {
    return myCalculatedPatterns.getValue();
  }

  private List<PairProcessor<Project, VirtualFile>> recalculatePatterns() {
    final List<PairProcessor<Project, VirtualFile>> result = new SmartList<>();
    for (final Item patternText : patterns) {
      switch (patternText.mappingKind) {
        case File:
          result.add((project, vfile) -> vfile.equals(getRelativeFile(project, patternText)) || vfile.getUrl().equals(patternText.getPath()));
          break;
        case Pattern:
          String pathText = patternText.getPath().replace(File.separatorChar, '/').replace('\\', '/');
          final Pattern pattern = pathText.isEmpty()
                                  ? PatternUtil.NOTHING
                                  : pathText.indexOf('/') >= 0
                                    ? PatternUtil.compileSafe(".*/" + PatternUtil.convertToRegex(pathText), PatternUtil.NOTHING)
                                    : PatternUtil.fromMask(pathText);
          result.add((project, file) -> JsonSchemaObject.matchPattern(pattern, pathText.indexOf('/') >= 0
                                                        ? file.getPath()
                                                        : file.getName()));
          break;
        case Directory:
          result.add((project, vfile) -> {
            final VirtualFile relativeFile = getRelativeFile(project, patternText);
            if (relativeFile == null || !VfsUtilCore.isAncestor(relativeFile, vfile, true)) return false;
            JsonSchemaService service = JsonSchemaService.Impl.get(project);
            return service.isApplicableToFile(vfile);
          });
          break;
      }
    }
    return result;
  }

  @Nullable
  private static VirtualFile getRelativeFile(@NotNull final Project project, @NotNull final Item pattern) {
    if (project.getBasePath() == null) {
      return null;
    }

    final String path = FileUtilRt.toSystemIndependentName(StringUtil.notNullize(pattern.path));
    final List<String> parts = pathToPartsList(path);
    if (parts.isEmpty()) {
      return project.getBaseDir();
    }
    else {
      return VfsUtil.findRelativeFile(project.getBaseDir(), ArrayUtil.toStringArray(parts));
    }
  }

  @NotNull
  private static List<String> pathToPartsList(@NotNull String path) {
    return ContainerUtil.filter(StringUtil.split(path, "/"), s -> !".".equals(s));
  }

  @NotNull
  private static String[] pathToParts(@NotNull String path) {
    return ArrayUtil.toStringArray(pathToPartsList(path));
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    UserDefinedJsonSchemaConfiguration info = (UserDefinedJsonSchemaConfiguration)o;

    if (applicationDefined != info.applicationDefined) return false;
    if (schemaVersion != info.schemaVersion) return false;
    if (!Objects.equals(name, info.name)) return false;
    if (!Objects.equals(relativePathToSchema, info.relativePathToSchema)) return false;

    return Objects.equals(patterns, info.patterns);
  }

  @Override
  public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + (relativePathToSchema != null ? relativePathToSchema.hashCode() : 0);
    result = 31 * result + (applicationDefined ? 1 : 0);
    result = 31 * result + (patterns != null ? patterns.hashCode() : 0);
    result = 31 * result + schemaVersion.hashCode();
    return result;
  }

  public static class Item {
    public String path;
    public JsonMappingKind mappingKind = JsonMappingKind.File;

    public Item() {
    }

    public Item(String path, JsonMappingKind mappingKind) {
      this.path = neutralizePath(path);
      this.mappingKind = mappingKind;
    }

    public Item(String path, boolean isPattern, boolean isDirectory) {
      this.path = neutralizePath(path);
      this.mappingKind = isPattern ? JsonMappingKind.Pattern : isDirectory ? JsonMappingKind.Directory : JsonMappingKind.File;
    }

    @NotNull
    private static String normalizePath(String path) {
      if (preserveSlashes(path)) return path;
      return StringUtil.trimEnd(FileUtilRt.toSystemDependentName(path), File.separatorChar);
    }

    private static boolean preserveSlashes(String path) {
      // http/https URLs to schemas
      // mock URLs of fragments editor
      return StringUtil.startsWith(path, "http:")
             || StringUtil.startsWith(path, "https:")
             || StringUtil.startsWith(path, "mock:");
    }

    @NotNull
    private static String neutralizePath(String path) {
      if (preserveSlashes(path)) return path;
      return StringUtil.trimEnd(FileUtilRt.toSystemIndependentName(path), '/');
    }

    public String getPath() {
      return normalizePath(path);
    }

    public void setPath(String path) {
      this.path = neutralizePath(path);
    }

    public String getError() {
      switch (mappingKind) {
        case File:
          return !StringUtil.isEmpty(path) ? null : "Empty file path doesn't match anything";
        case Pattern:
          return !StringUtil.isEmpty(path) ? null : "Empty pattern matches nothing";
        case Directory:
          return null;
      }

      return "Unknown mapping kind";
    }

    public boolean isPattern() {
      return mappingKind == JsonMappingKind.Pattern;
    }

    public void setPattern(boolean pattern) {
      mappingKind = pattern ? JsonMappingKind.Pattern : JsonMappingKind.File;
    }

    public boolean isDirectory() {
      return mappingKind == JsonMappingKind.Directory;
    }

    public void setDirectory(boolean directory) {
      mappingKind = directory ? JsonMappingKind.Directory : JsonMappingKind.File;
    }

    public String getPresentation() {
      if (mappingKind == JsonMappingKind.Directory && StringUtil.isEmpty(path)) {
        return mappingKind.getPrefix() + "[Project Directory]";
      }
      return mappingKind.getPrefix() + getPath();
    }

    public String[] getPathParts() {
      return pathToParts(path);
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Item item = (Item)o;

      if (mappingKind != item.mappingKind) return false;
      return Objects.equals(path, item.path);
    }

    @Override
    public int hashCode() {
      int result = Objects.hashCode(path);
      result = 31 * result + Objects.hashCode(mappingKind);
      return result;
    }
  }
}