-
Notifications
You must be signed in to change notification settings - Fork 57
/
UseScanManager.java
388 lines (361 loc) · 12.6 KB
/
UseScanManager.java
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*******************************************************************************
* Copyright (c) 2010, 2013 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.api.tools.internal.search;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.variables.IStringVariableManager;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.osgi.util.NLS;
import org.eclipse.pde.api.tools.internal.IApiCoreConstants;
import org.eclipse.pde.api.tools.internal.SynchronizedOverflowingLRUCache;
import org.eclipse.pde.api.tools.internal.provisional.ApiPlugin;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiComponent;
import org.eclipse.pde.api.tools.internal.util.FileManager;
import org.eclipse.pde.api.tools.internal.util.Util;
public class UseScanManager {
private static UseScanCache fApiComponentCache;
private static UseScanManager fUseScanProcessor;
private static String tempLocation = "${workspace_loc}/.metadata/.plugins/" + ApiPlugin.PLUGIN_ID + "/ApiUseScans/"; //$NON-NLS-1$ //$NON-NLS-2$
public static final String STATE_DELIM = "*"; //$NON-NLS-1$
public static final String LOCATION_DELIM = "|"; //$NON-NLS-1$
public static final String ESCAPE_REGEX = "\\"; //$NON-NLS-1$
/**
* Regular expression for finding use scan directories <br>
* <br>
* Value is: <code>^.* \\(.*\\)$</code>
*/
public static final Pattern NAME_REGEX = Pattern.compile("^.* \\(.*\\)$"); //$NON-NLS-1$
/**
* Number of entries to cache in the {@link UseScanCache}
*/
public static final int DEFAULT_CACHE_SIZE = 1000;
/**
* Cache to maintain the list of least recently used
* <code>UseScanReferences</code>
*/
private static class UseScanCache extends SynchronizedOverflowingLRUCache<IApiComponent, IReferenceCollection> {
public UseScanCache(int size) {
super(size);
}
public UseScanCache(int size, int overflow) {
super(size, overflow);
}
@Override
protected boolean close(LRUCacheEntry<IApiComponent, IReferenceCollection> entry) {
IReferenceCollection references = entry.value;
references.clear();
return true;
}
@Override
protected UseScanCache newInstance(int size, int newOverflow) {
return new UseScanCache(size, newOverflow);
}
}
private String[] fLocations = null;
/**
* {@link FileFilter} for finding use scan directories
*/
static FileFilter USESCAN_FILTER = pathname -> {
if (NAME_REGEX.matcher(pathname.getName()).matches()) {
throw new RuntimeException(pathname.getName());
}
return false;
};
// Singleton
private UseScanManager() {
}
/**
* Returns a handle to the singleton instance
*
* @return the singleton {@link UseScanManager}
*/
public synchronized static UseScanManager getInstance() {
if (fUseScanProcessor == null) {
fUseScanProcessor = new UseScanManager();
fApiComponentCache = new UseScanCache(DEFAULT_CACHE_SIZE);
}
return fUseScanProcessor;
}
/**
* Returns the references for a given <code>IApiComponent</code>. If it can not
* find them in cache, they will be fetched from the API Use Scans and stored.
*
* @param apiComponent component whose references have to be fetched
* @param apiUseTypes reference types for which the references has to be
* computed in the given <code>IApiComponent</code>. If
* <code>null</code> or empty, all references will be
* returned
* @return the array of reference descriptors
*/
public IReferenceDescriptor[] getExternalDependenciesFor(IApiComponent apiComponent, String[] apiUseTypes, IProgressMonitor monitor) {
IReferenceCollection references = fApiComponentCache.get(apiComponent);
if (references == null) {
references = apiComponent.getExternalDependencies();
}
SubMonitor localmonitor = SubMonitor.convert(monitor, SearchMessages.collecting_external_dependencies, 10);
List<String> unavailableMembers = new ArrayList<>();
if (apiUseTypes != null && apiUseTypes.length > 0) {
for (String apiUseType : apiUseTypes) {
if (!references.hasReferencesTo(apiUseType)) {
unavailableMembers.add(apiUseType);
}
}
if (!unavailableMembers.isEmpty()) {
fetch(apiComponent, unavailableMembers.toArray(new String[unavailableMembers.size()]), references,
localmonitor.split(9));
}
localmonitor.setWorkRemaining(1).split(1);
return references.getExternalDependenciesTo(apiUseTypes);
} else {
// full build has been triggered so re-fetch
fetch(apiComponent, null, references, localmonitor.split(9));
localmonitor.split(1);
return references.getAllExternalDependencies();
}
}
/**
* fetches the references from the API Use Scan locations
*/
private void fetch(IApiComponent apiComponent, String[] types, IReferenceCollection references, IProgressMonitor monitor) {
UseScanParser parser = new UseScanParser();
UseScanReferenceVisitor visitor = new UseScanReferenceVisitor(apiComponent, types, references);
SubMonitor localmonitor = SubMonitor.convert(monitor, SearchMessages.load_external_dependencies, 10);
try {
String[] locations;
if (fLocations == null) {
locations = getReportLocations();
} else {
locations = fLocations;
}
if (locations != null) {
IStringVariableManager stringManager = null;
localmonitor.setWorkRemaining(locations.length);
for (int i = 0; i < locations.length; i++) {
SubMonitor iterationMonitor = localmonitor.split(1);
File file = new File(locations[i]);
if (!file.exists()) {
continue;
}
if (file.isFile()) {
if (Util.isArchive(file.getName())) {
String destDirPath = tempLocation + file.getName() + '.' + file.getAbsolutePath().hashCode();
if (stringManager == null) {
stringManager = VariablesPlugin.getDefault().getStringVariableManager();
}
destDirPath = stringManager.performStringSubstitution(destDirPath);
locations[i] = destDirPath + '/' + file.lastModified();
File unzipDirLoc = new File(destDirPath);
if (unzipDirLoc.exists()) {
String[] childDirs = unzipDirLoc.list();
for (String childDir : childDirs) {
if (!childDir.equals(String.valueOf(file.lastModified()))) {
FileManager.getManager().recordTempFileRoot(destDirPath + '/' + childDir);
}
}
} else {
Util.unzip(file.getPath(), locations[i]);
}
} else {
continue;
}
}
try {
locations[i] = getExactScanLocation(locations[i]);
if (locations[i] == null) {
String message;
if (file.isDirectory()) {
message = NLS.bind(SearchMessages.UseScanManager_InvalidDir, file.getAbsolutePath());
} else {
message = NLS.bind(SearchMessages.UseScanManager_InvalidArchive, file.getAbsolutePath());
}
throw new Exception(message);
}
parser.parse(locations[i], iterationMonitor, visitor);
} catch (Exception e) {
ApiPlugin.log(e); // log the exception and continue with
// next location
}
}
fApiComponentCache.remove(apiComponent); // remove current value
// so that it only
// doesn't gets
// purged if size
// limit is reached
fApiComponentCache.put(apiComponent, references);
}
} catch (Exception e) {
ApiPlugin.log(e);
}
}
/**
* Returns the scan
*/
public static String getExactScanLocation(String location) {
File file = new File(location);
if (isValidDirectory(file)) {
return location;
}
file = new File(location, IApiCoreConstants.XML);
if (isValidDirectory(file)) {
return file.getAbsolutePath();
}
return null;
}
/**
* Validate if the given {@link File} is a folder that contains a use scan. <br>
* <br>
* The {@link File} is considered valid iff:
* <ul>
* <li>it is a folder</li>
* <li>the folder has child folder that matches the name pattern
* <code>^.* (.*)$</code></li>
* <li>the previous child directory has its own child directory that matches
* the name pattern <code>^.* (.*)$</code></li>
* </ul>
*
* @return <code>true</code> is the sub folders match the patterns,
* <code>false</code> otherwise
*/
public static boolean isValidDirectory(File file) {
if (file.exists() && file.isDirectory()) {
try {
file.listFiles(USESCAN_FILTER);
} catch (RuntimeException rte) {
File f = new File(file, rte.getMessage());
try {
if (f.exists() && f.isDirectory()) {
f.listFiles(USESCAN_FILTER);
}
} catch (RuntimeException re) {
return true;
}
}
}
return false;
}
/**
* Validate if the given {@link File} is an archive that contains a use
* scan. <br>
* <br>
* The {@link File} is considered valid iff:
* <ul>
* <li>it has an XML folder</li>
* <li>the XML folder has child folder that matches the name pattern
* <code>{@link #NAME_REGEX}</code></li>
* <li>the previous child directory has its own child directory that matches
* the name pattern <code>{@link #NAME_REGEX}</code></li>
* </ul>
*
* @return <code>true</code> is the sub folders match the patterns,
* <code>false</code> otherwise
*/
public static boolean isValidArchive(File file) {
String fname = file.getName().toLowerCase(Locale.ENGLISH);
if (file.exists() && Util.isArchive(fname)) {
if (fname.endsWith(Util.DOT_JAR)) {
try (JarFile jfile = new JarFile(file)) {
return containsUseScans(jfile);
} catch (IOException ioe) {
return false;
}
} else if (fname.endsWith(Util.DOT_ZIP)) {
try (ZipFile zfile = new ZipFile(file)) {
return containsUseScans(zfile);
} catch (IOException e) {
return false;
}
}
}
return false;
}
private static boolean containsUseScans(ZipFile zfile) {
return zfile.stream().filter(ZipEntry::isDirectory).anyMatch(o -> {
IPath path = IPath.fromOSString(o.getName());
if (path.segmentCount() > 2) {
return NAME_REGEX.matcher(path.segment(0)).matches() || NAME_REGEX.matcher(path.segment(1)).matches();
}
return false;
});
}
/**
* Returns if the scan if a valid API use scan
*
* @return true if the scan is valid false otherwise
*/
public static boolean isValidScanLocation(String location) {
if (location != null && location.length() > 0) {
File file = new File(location);
return isValidDirectory(file) || isValidArchive(file);
}
return false;
}
/**
* Returns the report locations from the preferences
*/
public String[] getReportLocations() {
IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ApiPlugin.PLUGIN_ID);
String apiUseScanPaths = node.get(IApiCoreConstants.API_USE_SCAN_LOCATION, null);
if (apiUseScanPaths == null || apiUseScanPaths.length() == 0) {
return new String[0];
}
String[] locations = apiUseScanPaths.split(ESCAPE_REGEX + LOCATION_DELIM);
List<String> locationList = new ArrayList<>(locations.length);
for (String location : locations) {
String[] values = location.split(ESCAPE_REGEX + STATE_DELIM);
if (Boolean.parseBoolean(values[1])) {
locationList.add(values[0]);
}
}
return locationList.toArray(new String[locationList.size()]);
}
/**
* Sets the report locations to be used. Once set, these locations will be
* used instead of ones in the preference. When set to <code>null</code>,
* the locations in preference will be used.
*/
public void setReportLocations(String[] locations) {
fLocations = locations;
}
/**
* Sets the cache size
*
* @param size The total number of references that can be held in memory
*/
public void setCacheSize(int size) {
fApiComponentCache.setSpaceLimit(size);
}
/**
* Purges all reference information
*/
public void clearCache() {
List<IReferenceCollection> elements = fApiComponentCache.elementsSnapshot();
for (IReferenceCollection reference : elements) {
reference.clear();
}
fApiComponentCache.flush();
}
}