-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathMiscUtils.java
More file actions
440 lines (370 loc) · 12.8 KB
/
MiscUtils.java
File metadata and controls
440 lines (370 loc) · 12.8 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/***************************************************************************
* Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite *
* Copyright (C) 2014 Konloch - Konloch.com / BytecodeViewer.com *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
package the.bytecode.club.bytecodeviewer.util;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.tree.ClassNode;
import the.bytecode.club.bytecodeviewer.BytecodeViewer;
import the.bytecode.club.bytecodeviewer.Configuration;
import the.bytecode.club.bytecodeviewer.resources.ResourceContainer;
import the.bytecode.club.bytecodeviewer.translation.Language;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import static the.bytecode.club.bytecodeviewer.BytecodeViewer.gson;
/**
* A collection of Misc Utils.
*
* @author Konloch
*/
public class MiscUtils
{
private static final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final String AN = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final Random RND = new Random();
private static final Set<String> CREATED_RANDOMIZED_NAMES = new HashSet<>();
/**
* Returns a random string without numbers
*
* @param len the length of the String
* @return the randomized string
*/
public static String randomString(int len)
{
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(RND.nextInt(AB.length())));
return sb.toString();
}
/**
* Ensures it will only return a uniquely generated names, contains a dupe checker to be sure
*
* @return the unique randomized name of 25 characters.
*/
public static String getRandomizedName()
{
boolean generated = false;
String name = "";
while (!generated)
{
String randomizedName = MiscUtils.randomString(25);
if (!CREATED_RANDOMIZED_NAMES.contains(randomizedName))
{
CREATED_RANDOMIZED_NAMES.add(randomizedName);
name = randomizedName;
generated = true;
}
}
return name;
}
public static void printProcess(Process process) throws Exception
{
//Read out dir output
try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
try (InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
}
/**
* Returns a random string with numbers
*
* @param len the length of the String
* @return the randomized string
*/
public static String randomStringNum(int len)
{
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AN.charAt(RND.nextInt(AN.length())));
return sb.toString();
}
/**
* Checks the file system to ensure it's a unique name
*
* @param stringStart directory it'll be in
* @param fileExtension the file extension it'll use
* @return the unique name
*/
public static String getUniqueName(String stringStart, String fileExtension)
{
String uniqueName = null;
boolean searching = true;
File tempFile;
String randomString;
while (searching)
{
randomString = MiscUtils.randomString(32);
uniqueName = stringStart + randomString + fileExtension;
tempFile = new File(stringStart + randomString + fileExtension);
if (!tempFile.exists())
searching = false;
}
return uniqueName;
}
/**
* Checks the file system to ensure it's a unique name
*
* @param stringStart directory it'll be in
* @param fileExtension the file extension it'll use
* @return the unique name
*/
//TODO anything using this should be updated:
// The + ".class" needs to be removed
@Deprecated
public static String getUniqueNameBroken(String stringStart, String fileExtension)
{
String uniqueName = null;
boolean searching = true;
File tempFile;
String randomString;
while (searching)
{
randomString = MiscUtils.randomString(32);
tempFile = new File(stringStart + randomString + fileExtension);
if (!tempFile.exists())
{
uniqueName = stringStart + randomString;
searching = false;
}
}
return uniqueName;
}
/**
* Checks the file system to ensure it's a unique number
*
* @param stringStart directory it'll be in
* @param fileExtension the file extension it'll use
* @return the unique number
*/
public static int getClassNumber(String stringStart, String fileExtension)
{
boolean searching = true;
int index = 0;
while (searching)
{
File tempF = new File(stringStart + index + fileExtension);
if (!tempF.exists())
searching = false;
else
index++;
}
return index;
}
public static File autoAppendFileExtension(String extension, File file)
{
if (!file.getName().endsWith(extension))
file = new File(file.getAbsolutePath() + extension);
return file;
}
public static String extension(String name)
{
return name.substring(name.lastIndexOf('.') + 1);
}
public static String append(File file, String extension)
{
String path = file.getAbsolutePath();
if (!path.endsWith(extension))
path += extension;
return path;
}
public static int fileContainersHash(List<ResourceContainer> resourceContainers)
{
StringBuilder block = new StringBuilder();
for (ResourceContainer container : resourceContainers)
{
block.append(container.name);
for (ClassNode node : container.resourceClasses.values())
{
block.append(node.name);
}
}
return block.hashCode();
}
/**
* Converts an array list to a string
*
* @param a array
* @return string with newline per array object
*/
public static String listToString(List<String> a)
{
return gson.toJson(a);
}
/**
* @author JoshTheWolfe
*/
@SuppressWarnings({"unchecked"})
public static void updateEnv(String name, String val) throws ReflectiveOperationException
{
Map<String, String> env = System.getenv();
Field field = env.getClass().getDeclaredField("m");
field.setAccessible(true);
((Map<String, String>) field.get(env)).put(name, val);
}
public static BufferedImage loadImage(BufferedImage defaultImage, byte[] contents)
{
try (ByteArrayInputStream bais = new ByteArrayInputStream(contents))
{
return ImageIO.read(bais);
}
catch (IOException e)
{
BytecodeViewer.handleException(e);
}
return defaultImage;
}
public static void deduplicateAndTrim(List<String> list, int maxLength)
{
List<String> temporaryList = new ArrayList<>();
for (String s : list)
if (!s.isEmpty() && !temporaryList.contains(s))
temporaryList.add(s);
list.clear();
list.addAll(temporaryList);
while (list.size() > maxLength)
list.remove(list.size() - 1);
}
/**
* Returns whether the bytes most likely represent binary data.
* Based on https://stackoverflow.com/a/13533390/5894824
*/
public static boolean guessIfBinary(byte[] bytes)
{
double ascii = 0;
double other = 0;
for (byte b : bytes)
{
if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D || (b >= 0x20 && b <= 0x7E))
ascii++;
else
other++;
}
return other != 0 && other / (ascii + other) > 0.25;
}
public static Language guessLanguage()
{
String userLanguage = System.getProperty("user.language");
String systemLanguageCode = userLanguage != null ? userLanguage.toLowerCase() : "";
return Language.getLanguageCodeLookup().getOrDefault(systemLanguageCode, Language.ENGLISH);
}
public static void setLanguage(Language language)
{
Configuration.language = language;
try
{
Language.ENGLISH.setLanguageTranslations(); //load english first incase the translation file is missing anything
language.setLanguageTranslations(); //load translation file and swap text around as needed
SwingUtilities.updateComponentTreeUI(BytecodeViewer.viewer);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* START's a new thread (Creates a new thread and runs that thread runnable on it)
*/
public static Thread createNewThread(String threadName, Runnable threadRunnable)
{
return createNewThread(threadName, false, threadRunnable);
}
/**
* START's a new thread (Creates a new thread and runs that thread runnable on it)
* RUN's a new thread (Just executes the thread runnable on the active thread)
*/
public static Thread createNewThread(String threadName, boolean runDontStart, Runnable threadRunnable)
{
Thread temporaryThread = new Thread(threadRunnable, threadName);
if (runDontStart)
temporaryThread.run();
else
temporaryThread.start();
return temporaryThread;
}
public static String getChildFromPath(String path)
{
if (path != null && path.contains("/"))
{
String[] pathParts = StringUtils.split(path, "/");
return pathParts[pathParts.length - 1];
}
return path;
}
/**
* Reads an InputStream and returns the read byte[]
*
* @param is InputStream
* @return the read byte[]
* @throws IOException
*/
public static byte[] getBytes(InputStream is) throws IOException
{
try (ByteArrayOutputStream baos = new ByteArrayOutputStream())
{
byte[] buffer = new byte[1024];
int a;
while ((a = is.read(buffer)) != -1)
baos.write(buffer, 0, a);
return baos.toByteArray();
}
}
public static File[] listFiles(File file)
{
if (file == null)
return new File[0];
File[] list = file.listFiles();
if (list != null)
return list;
return new File[0];
}
public static File deleteExistingFile(File file)
{
if (file.exists())
file.delete();
return file;
}
public static void extractFileFromZip(Path zipFile, String fileName, Path outputFile) throws IOException
{
try (FileSystem fileSystem = FileSystems.newFileSystem(zipFile, (ClassLoader) null)) {
Path fileToExtract = fileSystem.getPath(fileName);
Files.copy(fileToExtract, outputFile);
}
}
}