summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/util/Util.java
blob: f8d92483edb65d2026829f01d9486d95cd186bad (plain) (blame)
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
package org.openslx.imagemaster.util;

import java.io.File;
import java.math.BigInteger;
import java.security.Key;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;

import org.apache.log4j.Logger;

/**
 * Some utilities to make our lives easier.
 */
public class Util
{

	private static Logger LOGGER = Logger.getLogger( Util.class );

	/**
	 * Check if the given object is null, abort program if true.
	 * An optional message to be printed can be passed. A stack trace
	 * will be printed, too. Finally the application terminates with
	 * exit code 2.
	 * 
	 * This comes in handy if something must not be null, and you want
	 * user friendly output. A perfect example would be reading settings
	 * from a config file. You can use this on mandatory fields.
	 * 
	 * @param something the object to compare to null
	 * @param message the message to be printed if something is null
	 */
	public static void notNullFatal( Object something, String message )
	{
		if ( something == null ) {
			if ( message != null )
				LOGGER.fatal( "[NOTNULL] " + message, new NullPointerException() );
			System.exit( 2 );
		}
	}

	/**
	 * Check if the given object is null, abort program if true.
	 * An optional message to be printed can be passed. A stack trace
	 * will be printed, too. Finally the application terminates with
	 * exit code 2.
	 * 
	 * This comes in handy if something must not be null, and you want
	 * user friendly output. A perfect example would be reading settings
	 * from a config file. You can use this on mandatory fields.
	 * 
	 * @param something the object to compare to null
	 * @param message the message to be printed if something is null
	 */
	public static void notNullFatal( int number, String message )
	{
		if ( number == 0 ) {
			if ( message != null )
				LOGGER.fatal( "[NOTNULL] " + message, new NullPointerException() );
			System.exit( 2 );
		}
	}

	/**
	 * Check if String is null or empty, abort program if so.
	 * An optional message to be printed can be passed. A stack trace
	 * will be printed, too. Finally the application terminates with
	 * exit code 2.
	 * 
	 * @param something The string you want to check
	 * @param message The message to be printed if "something" is null or empty
	 */
	public static void notNullOrEmptyFatal( String something, String message )
	{
		if ( something == null || something.isEmpty() ) {
			if ( message != null )
				LOGGER.fatal( "[NOTNULL] " + message, new NullPointerException() );
			System.exit( 2 );
		}
	}

	/**
	 * Static {@link Random} instance.
	 */
	private static final Random random = new Random();

	/**
	 * Return a random integer in the range of 0 (inclusive) and
	 * n (exclusive). Uses the internal static instance of {@link Random},
	 * so you don't have to deal with instances everywhere.
	 * 
	 * @param n the upper bound (exclusive)
	 * @return number between 0 (inclusive) and n (exclusive)
	 */
	public static int randomInt( int n )
	{
		return random.nextInt( n );
	}

	/**
	 * Remove a folder and all contents
	 * 
	 * @param folder
	 */
	public static void deleteFolder( File folder )
	{
		File[] files = folder.listFiles();
		if ( files != null ) {
			for ( File f : files ) {
				if ( f.isDirectory() ) {
					deleteFolder( f );
				} else {
					f.delete();
				}
			}
		}
		folder.delete();
	}

	public static boolean isEmpty( String str )
	{
		return str == null || str.isEmpty();
	}

	public static boolean isEmpty( String str, String message, Logger logger )
	{
		if ( str != null && !str.isEmpty() )
			return false;
		logger.debug( message );
		return true;
	}

	/**
	 * Tries to parse an int. Returns 0 on error.
	 * 
	 * @param s The strig to parse
	 * @return The parsed int or 0 on error
	 */
	public static int tryToParseInt( String s )
	{
		return tryToParseInt( s, 0 );
	}

	/**
	 * Tries to parse an int. Returns defaultValue on error.
	 * 
	 * @param s The strig to parse
	 * @param defaultValue value to be returned if s is not parsable
	 * @return The parsed int
	 */
	public static int tryToParseInt( String s, int defaultValue )
	{
		try {
			return Integer.parseInt( s );
		} catch ( NumberFormatException e ) {
			return defaultValue;
		}
	}

	/**
	 * Tries to parse a bigint. Returns null on error.
	 * 
	 * @param s The strig to parse
	 * @return The parsed bigint
	 */
	public static BigInteger tryToParseBigInt( String s )
	{
		try {
			return new BigInteger( s );
		} catch ( NumberFormatException e ) {
			return null;
		}
	}

	public static int getNumberOfBlocks( long fileSize, int blockSize )
	{
		int blocks = (int) ( fileSize / blockSize );
		if ( fileSize % blockSize != 0 )
			blocks++;
		return blocks;
	}

	public static String sanitizeFileName( String fileName )
	{
		fileName = fileName.replaceAll( "[^a-zA-Z0-9_\\-]+", "_" );
		if ( fileName.length() > 40 )
			fileName = fileName.substring( 0, 40 );
		return fileName;
	}

	/**
	 * Checks whether the two given keys are equal. Works for
	 * public and private keys.
	 * 
	 * @param k1 first key
	 * @param k2 second key
	 * @return true if equal
	 */
	public static boolean keysEqual( Key k1, Key k2 )
	{
		if ( k1 instanceof RSAPublicKey && k2 instanceof RSAPublicKey )
		{
			RSAPublicKey rsa1 = (RSAPublicKey)k1;
			RSAPublicKey rsa2 = (RSAPublicKey)k2;
			return rsa1.getModulus().equals( rsa2.getModulus() )
					&& rsa1.getPublicExponent().equals( rsa2.getPublicExponent() );
		}

		if ( k1 instanceof RSAPrivateKey && k2 instanceof RSAPrivateKey )
		{
			RSAPrivateKey rsa1 = (RSAPrivateKey)k1;
			RSAPrivateKey rsa2 = (RSAPrivateKey)k2;
			return rsa1.getModulus().equals( rsa2.getModulus() )
					&& rsa1.getPrivateExponent().equals( rsa2.getPrivateExponent() );
		}
		return Arrays.equals( k1.getEncoded(), k2.getEncoded() );
	}

	public static String getRelativePath( File absolutePath, File parentDir )
	{
		String file;
		String dir;
		try {
			file = absolutePath.getCanonicalPath();
			dir = parentDir.getCanonicalPath() + File.separator;
		} catch ( Exception e ) {
			LOGGER.error( "Could not get relative path for " + absolutePath.toString(), e );
			return null;
		}
		if ( !file.startsWith( dir ) )
			return null;
		return file.substring( dir.length() );
	}

	public static boolean isUUID( String id )
	{
		try {
			UUID.fromString( id );
		} catch ( Exception e ) {
			return false;
		}
		return true;
	}

}