forked from iluwatar/30-seconds-of-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibrary.java
More file actions
339 lines (321 loc) · 11.2 KB
/
Library.java
File metadata and controls
339 lines (321 loc) · 11.2 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
/**
* MIT License
*
* Copyright (c) 2017-2018 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/*
* Java Snippets code
*
*/
public class Library {
/**
* Generic 2 array concatenation
* Credits: Joachim Sauer https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java
* @param first is the first array (not null)
* @param second is the second array (not null)
* @param <T> the element type
* @return concatenated array
*/
public static <T> T[] arrayConcat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
/**
* Generic N array concatenation
* Credits: Joachim Sauer https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java
* @param first is the first array (not null)
* @param rest the rest of the arrays (optional)
* @param <T> the element type
* @return concatenated array
*/
public static <T> T[] nArrayConcat(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
T[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/**
* Recursive Fibonacci series
* Works only for small n and is spectacularly inefficient
* @param n
* @return fibonacci number for given n
*/
public static int fibonacci(int n) {
if (n <= 1) return n;
else return fibonacci(n-1) + fibonacci(n-2);
}
/**
* Factorial
* Works only for small numbers
* @param number for which factorial is to be calculated for
* @return factorial
*/
public static int factorial(int number) {
int result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
/**
* Reverse string
* @param s the string to reverse
* @return reversed string
*/
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
/**
* Read file as list of strings
* @param filename the filename to read from
* @return list of strings
* @throws IOException
*/
public static List<String> readLines(String filename) throws IOException {
return Files.readAllLines(new File(filename).toPath());
}
/**
* Capture screenshot and save it to a file
* Credits: https://viralpatel.net/blogs/how-to-take-screen-shots-in-java-taking-screenshots-java/
* @param filename the name of the file
* @throws AWTException
* @throws IOException
*/
public static void captureScreen(String filename) throws AWTException, IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(filename));
}
/**
* Convert string to date
* @param date the date string
* @param format expected date format
* @return Date
* @throws ParseException
*/
public static Date stringToDate(String date, String format) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.parse(date);
}
/**
* List directories
* @param path the path where to look
* @return array of File
*/
public static File[] listDirectories(String path) {
return new File(path).listFiles(File::isDirectory);
}
/**
* Checks if given string is palindrome (same forward and backward)
* Skips non-letter characters
* Credits: https://github.com/kousen/java_8_recipes
* @param s string to check
* @return true if palindrome
*/
public static boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
sb.append(c);
}
}
String forward = sb.toString().toLowerCase();
String backward = sb.reverse().toString().toLowerCase();
return forward.equals(backward);
}
/**
* List files in directory
* @param folder the path where to look
* @return array of File
*/
public static File[] listFilesInDirectory(final File folder) {
return folder.listFiles(File::isFile);
}
/**
* Recursively list all the files in directory
* @param path the path to start the search from
* @return list of all files
*/
public static List<File> listAllFiles(String path) {
List<File> all = new ArrayList<>();
File[] list = new File(path).listFiles();
if (list != null) { // In case of access error, list is null
for (File f : list) {
if (f.isDirectory()) {
all.addAll(listAllFiles(f.getAbsolutePath()));
} else {
all.add(f.getAbsoluteFile());
}
}
}
return all;
}
/**
* Generate random lottery numbers
* @param numNumbers how many performLottery numbers are available (e.g. 49)
* @param numbersToPick how many numbers the player needs to pick (e.g. 6)
* @return array with the random numbers
*/
public static Integer[] performLottery(int numNumbers, int numbersToPick) {
List<Integer> numbers = new ArrayList<>();
for(int i = 0; i < numNumbers; i++) {
numbers.add(i+1);
}
Collections.shuffle(numbers);
return numbers.subList(0, numbersToPick).toArray(new Integer[numbersToPick]);
}
/**
* Zip single file
* @param srcFilename the filename of the source file
* @param zipFilename the filename of the destination zip file
* @throws IOException
*/
public static void zipFile(String srcFilename, String zipFilename) throws IOException {
File srcFile = new File(srcFilename);
try (
FileOutputStream fileOut = new FileOutputStream(zipFilename);
ZipOutputStream zipOut = new ZipOutputStream(fileOut);
FileInputStream fileIn = new FileInputStream(srcFile);
) {
ZipEntry zipEntry = new ZipEntry(srcFile.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fileIn.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
/**
* Zip multiples files
* @param srcFilenames array of source file names
* @param zipFilename the filename of the destination zip file
* @throws IOException
*/
public static void zipFiles(String[] srcFilenames, String zipFilename) throws IOException {
try (
FileOutputStream fileOut = new FileOutputStream(zipFilename);
ZipOutputStream zipOut = new ZipOutputStream(fileOut);
) {
for (int i=0; i<srcFilenames.length; i++) {
File srcFile = new File(srcFilenames[i]);
try (FileInputStream fileIn = new FileInputStream(srcFile)) {
ZipEntry zipEntry = new ZipEntry(srcFile.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fileIn.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}
}
/**
* Sort an array with quicksort algorithm
* @param arr array to sort
* @param left left index where to begin sort (e.g. 0)
* @param right right index where to end sort (e.g. array length - 1)
*/
public static void quickSort(int[] arr, int left, int right) {
int pivotIndex = left + (right - left) / 2;
int pivotValue = arr[pivotIndex];
int i = left, j = right;
while (i <= j) {
while (arr[i] < pivotValue) {
i++;
}
while (arr[j] > pivotValue) {
j--;
}
if (i <= j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
if (left < i) {
quickSort(arr, left, j);
}
if (right > i) {
quickSort(arr, i, right);
}
}
}
/**
* Performs HTTP GET request
* @param address the URL of the connection
* @return HTTP status code
* @throws IOException
*/
public static int httpGet(URL address) throws IOException {
HttpURLConnection con = (HttpURLConnection) address.openConnection();
return con.getResponseCode();
}
/**
* Checks if given number is a prime number
* Prime number is a number that is greater than 1 and divided by 1 or itself only
* Credits: https://en.wikipedia.org/wiki/Prime_number
* @param number number to check prime
* @return true if prime
*/
public static boolean isPrime(int number) {
if (number < 3) {
return true;
}
// check if n is a multiple of 2
if (number % 2 == 0) {
return false;
}
// if not, then just check the odds
for (int i = 3; i * i <= number; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}