Last active
February 1, 2016 09:47
-
-
Save asimjalis/5475179 to your computer and use it in GitHub Desktop.
Useful Java utility functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LICENSE OVERVIEW | |
This is released under the zlib/libpng license http://opensource.org/licenses/Zlib which is one of the most liberal software licenses. If you have any concerns or want this released under a different license contact me. | |
LICENSE TEXT | |
Copyright (c) 2013 Asim Jalis. | |
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. | |
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: | |
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. | |
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. | |
3. This notice may not be removed or altered from any source distribution. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package core; | |
import java.io.*; | |
import java.net.*; | |
/** | |
* Useful utility functions. | |
*/ | |
public class Util { | |
private static final String UTF_8 = "UTF-8"; | |
/** | |
* Converts stream to string. | |
*/ | |
static String streamToString(InputStream inputStream) { | |
BufferedReader reader = new BufferedReader(new InputStreamReader( | |
inputStream)); | |
final String contents; | |
try { | |
try { | |
StringBuilder builder = new StringBuilder(); | |
char[] buffer = new char[8192]; | |
while (true) { | |
int byteCount = reader.read(buffer, 0, buffer.length); | |
if (byteCount < 0) { | |
break; | |
} | |
builder.append(buffer, 0, byteCount); | |
} | |
contents = builder.toString(); | |
} finally { | |
reader.close(); | |
} | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
return contents; | |
} | |
/** | |
* Converts string to writer. | |
*/ | |
static void stringToWriter(String contents, Writer writer) { | |
try { | |
BufferedWriter bufferedWriter = new BufferedWriter(writer); | |
try { | |
bufferedWriter.write(contents); | |
} finally { | |
bufferedWriter.close(); | |
} | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Returns new file writer. | |
*/ | |
static FileWriter newFileWriter(String filePath, boolean append) { | |
try { | |
return new FileWriter(filePath, append); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Converts arguments to POST data by interpreting as alternating | |
* sequence of key value pairs and returns POST data. | |
*/ | |
static String webDataToString(String... data) { | |
StringBuilder builder = new StringBuilder(); | |
if (data == null) { | |
return ""; | |
} | |
for (int i = 0; i < data.length; i += 2) { | |
if (i > 0) { | |
builder.append("&"); | |
} | |
String name = data[i]; | |
String value = data[i + 1]; | |
try { | |
builder.append(URLEncoder.encode(name, UTF_8)); | |
builder.append("="); | |
builder.append(URLEncoder.encode(value, UTF_8)); | |
} catch (UnsupportedEncodingException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
return builder.toString(); | |
} | |
/** | |
* Prints out prompt and returns user input. | |
*/ | |
public static String prompt(String prompt) { | |
System.out.print(prompt); | |
System.out.flush(); | |
InputStreamReader inputStreamReader = new InputStreamReader(System.in); | |
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); | |
try { | |
return bufferedReader.readLine(); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Returns random integer between 0 (inclusive) and n (exclusive). | |
*/ | |
public static int randomInt(int n) { | |
return (int) (Math.random() * n); | |
} | |
/** | |
* Returns random integer between a (inclusive) and b (inclusive). | |
*/ | |
public static int randomInt(int a, int b) { | |
return (int) (Math.random() * (b - a + 1) + a); | |
} | |
/** | |
* Returns file contents as string. | |
*/ | |
public static String fileRead(String filePath) { | |
final String contents; | |
try { | |
BufferedReader reader = new BufferedReader(new InputStreamReader( | |
new FileInputStream(filePath))); | |
try { | |
StringBuilder builder = new StringBuilder(); | |
char[] buffer = new char[8192]; | |
while (true) { | |
int byteCount = reader.read(buffer, 0, buffer.length); | |
if (byteCount < 0) { | |
break; | |
} | |
builder.append(buffer, 0, byteCount); | |
} | |
contents = builder.toString(); | |
} finally { | |
reader.close(); | |
} | |
} catch (FileNotFoundException e) { | |
throw new RuntimeException(e); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
return contents; | |
} | |
/** | |
* Writes contents to file. | |
*/ | |
static void fileWrite(String filePath, String contents, boolean append) { | |
try { | |
FileWriter fileWriter = new FileWriter(filePath, append); | |
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); | |
try { | |
bufferedWriter.write(contents); | |
} finally { | |
bufferedWriter.close(); | |
} | |
} | |
catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Writes contents to file. | |
*/ | |
static void fileWrite(String filePath, String contents) { | |
fileWrite(filePath, contents, false); | |
} | |
/** | |
* Appends contents to file. | |
*/ | |
public static void fileAppend(String filePath, String contents) { | |
fileWrite(filePath, contents, true); | |
} | |
/** | |
* Executes shell command and returns its output as string. | |
*/ | |
public static String shellExecute(String command) { | |
try { | |
Runtime runtime = Runtime.getRuntime(); | |
Process process = runtime.exec(command); | |
process.waitFor(); | |
return streamToString(process.getInputStream()); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Calls URL with GET request and returns response body. | |
*/ | |
public static String webGet(String urlString, | |
String... data) { | |
try { | |
// Append data if any passed in. | |
if (data.length != 0) { | |
String separator = | |
urlString.contains("?") ? "&" : "?"; | |
urlString += | |
separator + webDataToString(data); | |
} | |
// Send request. | |
URL url = new URL(urlString); | |
URLConnection connection = url.openConnection(); | |
// Read response. | |
return streamToString(connection.getInputStream()); | |
} catch (MalformedURLException e) { | |
throw new RuntimeException(e); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Calls URL with POST request, adds data which is alternating key | |
* value pairs, and returns response body. | |
*/ | |
public static String webPost(String urlString, | |
String... data) { | |
try { | |
// Open connection. | |
URL url = new URL(urlString); | |
HttpURLConnection connection = | |
(HttpURLConnection) url.openConnection(); | |
connection.setDoInput(true); | |
connection.setDoOutput(true); | |
connection.setUseCaches(false); | |
connection.setRequestMethod("POST"); | |
connection.setRequestProperty("Content-Type", | |
"application/x-www-form-urlencoded"); | |
connection.connect(); | |
// Write output parameters. | |
stringToWriter(webDataToString(data), | |
new OutputStreamWriter( | |
connection.getOutputStream())); | |
// Read response. | |
return streamToString(connection.getInputStream()); | |
} catch (MalformedURLException e) { | |
throw new RuntimeException(e); | |
} catch (ProtocolException e) { | |
throw new RuntimeException(e); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/** | |
* Prints string. | |
*/ | |
public static void print(String string) { | |
System.out.println(string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment