View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  
15  package de.softwareforge.testing.postgres.embedded;
16  
17  import static com.google.common.base.Preconditions.checkArgument;
18  import static com.google.common.base.Preconditions.checkState;
19  
20  import jakarta.annotation.Nonnull;
21  import java.io.File;
22  import java.io.IOException;
23  import java.net.ServerSocket;
24  import java.nio.file.Files;
25  import java.nio.file.Path;
26  import java.time.Duration;
27  import java.util.Comparator;
28  import java.util.Locale;
29  import java.util.Objects;
30  import java.util.concurrent.ThreadLocalRandom;
31  import java.util.stream.Stream;
32  
33  import com.google.common.base.Joiner;
34  import com.google.common.base.Strings;
35  import com.google.common.collect.ImmutableList;
36  
37  final class EmbeddedUtil {
38  
39      static final String OS_NAME;
40      static final String OS_ARCH;
41  
42      static final boolean IS_OS_WINDOWS;
43      static final boolean IS_OS_MAC;
44      static final boolean IS_OS_LINUX;
45      static final boolean IS_ALPINE_LINUX;
46  
47      static final boolean IS_ARCH_X86_64;
48      static final boolean IS_ARCH_AARCH64;
49      static final boolean IS_ARCH_AARCH32;
50  
51      private static final String ALPHANUM;
52      private static final String LOWERCASE;
53  
54      static {
55          OS_NAME = getSystemProperty("os.name");
56          OS_ARCH = getSystemProperty("os.arch");
57  
58          IS_OS_WINDOWS = getOsMatchesName("Windows");
59          IS_OS_LINUX = getOsMatchesName("Linux");
60          IS_OS_MAC = getOsMatchesName("Mac");
61  
62          IS_ARCH_X86_64 = OS_ARCH.equals("x86_64") || OS_ARCH.equals("amd64");
63          IS_ARCH_AARCH64 = OS_ARCH.equals("aarch64");
64          IS_ARCH_AARCH32 = OS_ARCH.equals("aarch32") || OS_ARCH.equals("arm");
65  
66          // this is a glorious hack
67          IS_ALPINE_LINUX = new File("/etc/alpine-release").exists();
68  
69          String numbers = sequence('0', 10);
70          LOWERCASE = sequence('a', 26);
71          String uppercase = sequence('A', 26);
72          ALPHANUM = numbers + LOWERCASE + uppercase;
73      }
74  
75      private EmbeddedUtil() {
76          throw new AssertionError("EmbeddedUtil can not be instantiated");
77      }
78  
79      static File getWorkingDirectory() {
80          File parent = new File(System.getProperty("java.io.tmpdir"));
81          // personalize the unpack folder to allow systems with many users using the same tmp folder to work
82          File workDir = new File(parent, "embedded-pg-" + Objects.requireNonNullElse(System.getProperty("user.name"), "unknown"));
83  
84          ensureDirectory(workDir);
85  
86          return workDir;
87      }
88  
89      static void ensureDirectory(@Nonnull File workDir) {
90  
91          if (!workDir.exists()) {
92              checkState(workDir.mkdirs(), " Could not create directory '%s'", workDir);
93          }
94  
95          checkState(workDir.exists(), "'%s' does not exist!", workDir);
96          checkState(workDir.isDirectory(), "'%s' exists but is not a directory!", workDir);
97  
98          if (!workDir.canWrite()) {
99              checkState(workDir.setWritable(true, false), "Could not make directory '%s' writeable!", workDir);
100         }
101 
102         checkState(workDir.canWrite(), "'%s' is a directory but can not be written!", workDir);
103     }
104 
105     //
106     // taken from apache commons io
107     //
108     static String getFileBaseName(final String fileName) {
109         if (fileName == null) {
110             return null;
111         }
112         failIfNullBytePresent(fileName);
113         final int index = indexOfLastSeparator(fileName);
114         return fileName.substring(index + 1);
115     }
116 
117     private static void failIfNullBytePresent(final String path) {
118         final int len = path.length();
119         for (int i = 0; i < len; i++) {
120             checkArgument(path.charAt(i) != 0,
121                     "Null byte present in file/path name.");
122         }
123     }
124 
125     private static int indexOfLastSeparator(final String fileName) {
126         if (fileName == null) {
127             return -1;
128         }
129         final int lastUnixPos = fileName.lastIndexOf('/'); // unix
130         final int lastWindowsPos = fileName.lastIndexOf('\\'); // windows
131         return Math.max(lastUnixPos, lastWindowsPos);
132     }
133 
134     //
135     // taken from apache commons io
136     //
137 
138     static void rmdirs(File dir) throws IOException {
139         if (dir.exists() && dir.isDirectory()) {
140             try (Stream<Path> walk = Files.walk(dir.toPath())) {
141                 walk.sorted(Comparator.reverseOrder())
142                         .map(Path::toFile)
143                         .forEach(File::delete);
144             }
145         }
146     }
147 
148     static String formatDuration(Duration duration) {
149         long millis = duration.toMillis();
150         long hours;
151         long minutes;
152         long secs;
153         long ms;
154         ImmutableList.Builder<String> builder = ImmutableList.builder();
155         if (millis == 0) {
156             builder.add("0 ms");
157         } else {
158             long seconds = millis / 1000L;
159             hours = seconds / 3600L;
160             minutes = (seconds % 3600L) / 60L;
161             secs = (seconds % 60L);
162             ms = millis % 1000L;
163 
164             if (hours != 0) {
165                 builder.add(hours + " hours");
166             }
167             if (minutes != 0) {
168                 builder.add(minutes + " minutes");
169             }
170             if (secs != 0) {
171                 builder.add(secs + " seconds");
172             }
173             if (ms != 0) {
174                 builder.add(ms + " ms");
175             }
176         }
177 
178         return Joiner.on(' ').join(builder.build());
179     }
180 
181     static int allocatePort() throws IOException {
182         try (ServerSocket socket = new ServerSocket(0)) {
183             while (!socket.isBound()) {
184                 Thread.sleep(50);
185             }
186             return socket.getLocalPort();
187         } catch (InterruptedException e) {
188             Thread.currentThread().interrupt();
189             throw new IOException("Thread interrupted!", e);
190         }
191     }
192 
193     static String randomAlphaNumeric(int length) {
194         return randomString(ALPHANUM, length);
195     }
196 
197     static String randomLowercase(int length) {
198         return randomString(LOWERCASE, length);
199     }
200 
201     private static String sequence(char start, int count) {
202         StringBuilder sb = new StringBuilder();
203         for (int i = 0; i < count; i++) {
204             sb.append((char) (start + i));
205         }
206         return sb.toString();
207     }
208 
209     private static String randomString(String alphabet, int length) {
210         StringBuilder sb = new StringBuilder();
211         for (int i = 0; i < length; i++) {
212             int random = ThreadLocalRandom.current().nextInt(alphabet.length());
213             sb.append(alphabet.charAt(random));
214         }
215         return sb.toString();
216     }
217 
218     private static String getSystemProperty(String propertyName) {
219         try {
220             return Strings.nullToEmpty(System.getProperty(propertyName, ""));
221         } catch (SecurityException e) {
222             return "<unknown>";
223         }
224     }
225 
226     private static boolean getOsMatchesName(final String osNamePrefix) {
227         return OS_NAME.toLowerCase(Locale.ROOT).startsWith(osNamePrefix.toLowerCase(Locale.ROOT));
228     }
229 }