Thursday, May 23, 2013
Friday, February 15, 2013
Example java daemon code for Powershell interaction
Copy-pasted from: https://forums.oracle.com/forums/thread.jspa?messageID=10078419
public class Gobbler implements Runnable {
private PrintStream out;
private String message;
private BufferedReader reader;
public Gobbler(InputStream inputStream, PrintStream out) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.out = out;
this.message = ( null != message ) ? message : "";
}
public void run() {
String line;
try {
while (null != (line = this.reader.readLine())) {
out.println(message + line);
}
this.reader.close();
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
}
}
}
public class PowerConsole {
private ProcessBuilder pb;
Process p;
boolean closed = false;
PrintWriter writer;
PowerConsole(String[] commandList) {
pb = new ProcessBuilder(commandList);
try {
p = pb.start();
} catch (IOException ex) {
throw new RuntimeException("Cannot execute PowerShell.exe", ex);
}
writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
Gobbler outGobbler = new Gobbler(p.getInputStream(), System.out);
Gobbler errGobbler = new Gobbler(p.getErrorStream(), System.out);
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
}
public void execute(String command) {
if (!closed) {
writer.println(command);
writer.flush();
} else {
throw new IllegalStateException("Power console has ben closed.");
}
}
public void close() {
try {
execute("exit");
p.waitFor();
} catch (InterruptedException ex) {
}
}
public static void main(String[] args) throws IOException, InterruptedException {
/* PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
PowerConsole pc = new PowerConsole(new String[]{"/bin/bash"});
pc.execute("pwd");
pc.execute("ls");
pc.execute("cd /");
pc.execute("ls -l");
pc.execute("cd ~");
pc.execute("find . -name 'test.*' -print");
pc.close();
*/
// PowerConsole pc = new PowerConsole(new String[]{"cmd.exe"});
PowerConsole pc = new PowerConsole(new String[]{"powershell.exe", "-NoExit", "-Command", "-"});
System.out.println("========== Executing dir");
pc.execute("dir");
System.out.println("========== Executing cd\\");
pc.execute("cd \\"); Thread.sleep(2000);
System.out.println("========== Executing dir");
pc.execute("dir"); Thread.sleep(2000);
System.out.println("========== Executing cd \\temp");
pc.execute("cd \\temp"); Thread.sleep(2000);
System.out.println("========== Executing dir");
pc.execute("dir"); Thread.sleep(2000);
System.out.println("========== Executing cd \\bubba");
pc.execute("cd \\bubba"); Thread.sleep(2000);
System.out.println("========== Exiting .... bye.");
pc.close();
}
}
I tested this and there is still a little problem -look at the test below.
It seems that when thecommand
executed in the powershell prints only a one ot two lines,
powershell doesn't flush the output stream
.... but this rather problem of powershell, not the java code
I have not a clue how to force powershell to flush
it's output stream after each command.
C:\temp>java -jar PowerShell.jar
========== Executing dir
Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2012-01-09 01:16 5290 PowerShell.jar
========== Executing cd\
========== Executing dir
Directory: Microsoft.PowerShell.Core\FileSystem::C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2012-01-08 02:56 61587b977687a6e22fbe
d---- 2011-12-14 03:19 Documents and Settings
d---- 2011-12-15 00:05 oraclexe
d-r-- 2012-01-08 03:44 Program Files
d---- 2012-01-05 19:59 sqldeveloper
d---- 2012-01-09 01:15 temp
d---- 2012-01-09 01:13 WINDOWS
-a--- 2011-12-14 03:12 0 AUTOEXEC.BAT
-a--- 2011-12-14 03:12 0 CONFIG.SYS
========== Executing cd \temp
========== Executing dir
Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2012-01-09 01:16 5290 PowerShell.jar
========== Executing cd \bubba
Set-Location : Cannot find path 'C:\bubba' because it does not exist.
At line:1 char:3
+ cd <<<< \bubba
========== Exiting .... bye.
C:\temp>
Thursday, December 27, 2012
Simple way to read properties file in Java
Copy pasted from Link: http://www.mkyong.com/java/java-properties-file-examples/
package com.mkyong.common; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //set the properties value prop.setProperty("database", "localhost"); prop.setProperty("dbuser", "mkyong"); prop.setProperty("dbpassword", "password"); //save properties to project root folder prop.store(new FileOutputStream("config.properties"), null); } catch (IOException ex) { ex.printStackTrace(); } } }
package com.mkyong.common; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //load a properties file prop.load(new FileInputStream("config.properties")); //get the property value and print it out System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); } catch (IOException ex) { ex.printStackTrace(); } } }
package com.mkyong.common; import java.io.FileInputStream; import java.io.IOException; import java.utilutil.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //load a properties file from class path, inside static method prop.load(App.class.getClassLoader().getResourceAsStream("config.properties");)); //get the property value and print it out System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); } catch (IOException ex) { ex.printStackTrace(); } } }
Monday, March 12, 2012
Base-64 implementation example
Copy-pasted from: http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
public class Base64 { private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/"; private static final int splitLinesAt = 76; public static byte[] zeroPad(int length, byte[] bytes) { byte[] padded = new byte[length]; // initialized to zero by JVM System.arraycopy(bytes, 0, padded, 0, bytes.length); return padded; } public static String encode(String string) { String encoded = ""; byte[] stringArray; try { stringArray = string.getBytes("UTF-8"); // use appropriate encoding string! } catch (Exception ignored) { stringArray = string.getBytes(); // use locale default rather than croak } // determine how many padding bytes to add to the output int paddingCount = (3 - (stringArray.length % 3)) % 3; // add any necessary padding to the input stringArray = zeroPad(stringArray.length + paddingCount, stringArray); // process 3 bytes at a time, churning out 4 output bytes // worry about CRLF insertions later for (int i = 0; i < stringArray.length; i += 3) { int j = ((stringArray[i] & 0xff) << 16) + ((stringArray[i + 1] & 0xff) << 8) + (stringArray[i + 2] & 0xff); encoded = encoded + base64code.charAt((j >> 18) & 0x3f) + base64code.charAt((j >> 12) & 0x3f) + base64code.charAt((j >> 6) & 0x3f) + base64code.charAt(j & 0x3f); } // replace encoded padding nulls with "=" return splitLines(encoded.substring(0, encoded.length() - paddingCount) + "==".substring(0, paddingCount)); } public static String splitLines(String string) { String lines = ""; for (int i = 0; i < string.length(); i += splitLinesAt) { lines += string.substring(i, Math.min(string.length(), i + splitLinesAt)); lines += "\r\n"; } return lines; } public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.err.println("encoding \"" + args[i] + "\""); System.out.println(encode(args[i])); } } }
Friday, March 9, 2012
Java sample to do Https
Copied from blog: http://www.java-samples.com/showtutorial.php?tutorialid=1343
import java.io.*;
import java.net.*;
import java.security.Security.*;
import com.sun.net.ssl.*;
import com.sun.*;
public class sslpost {
public static void main(String[] args){
String cuki=new String();
try {
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL url = new URL("https://www.sunpage.com.sg/sso/login.asp");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setFollowRedirects(true);
String query = "UserID=" + URLEncoder.encode("williamalex@hotmail.com");
query += "&";
query += "password=" + URLEncoder.encode("password");
query += "&";
query += "UserChk=" + URLEncoder.encode("Bidder");
// This particular website I was working with, required that the referrel URL should be from this URL
// as specified the previousURL. If you do not have such requirement you may omit it.
query += "&";
query += "PreviousURL=" + URLEncoder.encode("https://www.sunpage.com.sg/sso/login.asp");
//connection.setRequestProperty("Accept-Language","it");
//connection.setRequestProperty("Accept", "application/cfm, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, ///");
//connection.setRequestProperty("Accept-Encoding","gzip");
connection.setRequestProperty("Content-length",String.valueOf (query.length()));
connection.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
// open up the output stream of the connection
DataOutputStream output = new DataOutputStream( connection.getOutputStream() );
// write out the data
int queryLength = query.length();
output.writeBytes( query );
//output.close();
System.out.println("Resp Code:"+connection.getResponseCode());
System.out.println("Resp Message:"+ connection.getResponseMessage());
// get ready to read the response from the cgi script
DataInputStream input = new DataInputStream( connection.getInputStream() );
// read in each character until end-of-stream is detected
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
}
catch(Exception e)
{
System.out.println( "Something bad just happened." );
System.out.println( e );
e.printStackTrace();
}
}
}
Tuesday, January 31, 2012
ThreadLocal - Usage and Explanation
Refer to a developer article : http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use
Read documentation on usage first in the above link. Then refer to the following sample code from the developer:
Read documentation on usage first in the above link. Then refer to the following sample code from the developer:
01.package com.veerasundar;02. 03.public class Context {04. 05. private String transactionId = null;06. 07. /* getters and setters here */08. 09.} 01.package com.veerasundar;02. 03./**04. * this class acts as a container to our thread local variables.05. * @author vsundar06. *07. */08.public class MyThreadLocal {09. 10. public static final ThreadLocal userThreadLocal = new ThreadLocal();11. 12. public static void set(Context user) {13. userThreadLocal.set(user);14. }15. 16. public static void unset() {17. userThreadLocal.remove();18. }19. 20. public static Context get() {21. return userThreadLocal.get();22. }23.} 01.package com.veerasundar;02. 03.public class ThreadLocalDemo extends Thread {04. 05. public static void main(String args[]) {06. 07. Thread threadOne = new ThreadLocalDemo();08. threadOne.start();09. 10. Thread threadTwo = new ThreadLocalDemo();11. threadTwo.start();12. }13. 14. @Override15. public void run() {16. // sample code to simulate transaction id17. Context context = new Context();18. context.setTransactionId(getName());19. 20. // set the context object in thread local to access it somewhere else21. MyThreadLocal.set(context);22. 23. /* note that we are not explicitly passing the transaction id */24. new BusinessService().businessMethod();25. MyThreadLocal.unset();26. 27. }28.} 01.package com.veerasundar;02. 03.public class BusinessService {04. 05. public void businessMethod() {06. // get the context from thread local07. Context context = MyThreadLocal.get();08. System.out.println(context.getTransactionId());09. }10.} Sunday, January 29, 2012
Program to manipulate dependency map
Java Code :
-------------
package com.test.data;
import java.util.*;
// @author - Lakshman.
public class DependencyMap {
private Map> dataMap = null;
private Map valueMap = new HashMap();
public DependencyMap(Map> argMap) {
if (argMap != null) {
dataMap = argMap;
}
else {
dataMap = new HashMap>();
}
}
public void createMap(String keyName, String keyVal) {
if (!dataMap.containsKey(keyName)) {
return;
}
// Check if value is already set in values map.
if (!valueMap.containsKey(keyName)) {
valueMap.put(keyName, keyVal);
}
// Get dependents.
ArrayList valList = dataMap.get(keyName);
if (valList == null) {
return;
}
// Increment the value.
int val = Integer.parseInt(keyVal);
val++;
String depVal = Integer.toString(val);
// For each dependent, set - value + 1
for (String depKey : valList) {
if (!valueMap.containsKey(depKey)) {
valueMap.put(depKey, new String(depVal));
}
}
// For each dependent, recursively traverse.
for (String depKey : valList) {
createMap(depKey, depVal);
}
}
public void displayValueMap() {
for (Map.Entry valEntry : valueMap.entrySet()) {
System.out.println("Key = " + valEntry.getKey() + " :: Value = " + valEntry.getValue());
}
}
public void displayDataMap() {
if (dataMap == null) {
return;
}
int count = 0;
for (Map.Entry> dataMapEntry : dataMap.entrySet()) {
count++;
System.out.print("Element number - " + count);
System.out.print (" - Key = " + dataMapEntry.getKey() + " :: Dependenct List = ");
ArrayList valList = dataMapEntry.getValue();
if (valList == null) {
System.out.println();
continue;
}
for (String val : valList) {
System.out.print(val + " ; ");
}
System.out.println();
}
}
private static HashMap> populateMap1() {
HashMap> dataMap = new HashMap>();
ArrayList valList = new ArrayList();
valList.add("B");
valList.add("C");
valList.add("E");
dataMap.put("A", valList);
valList = new ArrayList();
valList.add("C");
valList.add("D");
dataMap.put("B", valList);
valList = new ArrayList();
valList.add("E");
dataMap.put("C", valList);
dataMap.put("D", null);
dataMap.put("E", null);
return dataMap;
}
public static void testcase1() {
Map> dataMap = populateMap1();
DependencyMap depMap = new DependencyMap(dataMap);
depMap.displayDataMap();
depMap.createMap("A", "1");
depMap.displayValueMap();
}
public static void main(String[] args) {
testcase1();
}
}
Output
--------
Element number - 1 - Key = D :: Dependenct List =
Element number - 2 - Key = E :: Dependenct List =
Element number - 3 - Key = A :: Dependenct List = B ; C ; E ;
Element number - 4 - Key = B :: Dependenct List = C ; D ;
Element number - 5 - Key = C :: Dependenct List = E ;
Key = D :: Value = 3
Key = E :: Value = 2
Key = A :: Value = 1
Key = B :: Value = 2
Key = C :: Value = 2
-------------
package com.test.data;
import java.util.*;
// @author - Lakshman.
public class DependencyMap {
private Map
private Map
public DependencyMap(Map
if (argMap != null) {
dataMap = argMap;
}
else {
dataMap = new HashMap
}
}
public void createMap(String keyName, String keyVal) {
if (!dataMap.containsKey(keyName)) {
return;
}
// Check if value is already set in values map.
if (!valueMap.containsKey(keyName)) {
valueMap.put(keyName, keyVal);
}
// Get dependents.
ArrayList
if (valList == null) {
return;
}
// Increment the value.
int val = Integer.parseInt(keyVal);
val++;
String depVal = Integer.toString(val);
// For each dependent, set - value + 1
for (String depKey : valList) {
if (!valueMap.containsKey(depKey)) {
valueMap.put(depKey, new String(depVal));
}
}
// For each dependent, recursively traverse.
for (String depKey : valList) {
createMap(depKey, depVal);
}
}
public void displayValueMap() {
for (Map.Entry
System.out.println("Key = " + valEntry.getKey() + " :: Value = " + valEntry.getValue());
}
}
public void displayDataMap() {
if (dataMap == null) {
return;
}
int count = 0;
for (Map.Entry
count++;
System.out.print("Element number - " + count);
System.out.print (" - Key = " + dataMapEntry.getKey() + " :: Dependenct List = ");
ArrayList
if (valList == null) {
System.out.println();
continue;
}
for (String val : valList) {
System.out.print(val + " ; ");
}
System.out.println();
}
}
private static HashMap
HashMap
ArrayList
valList.add("B");
valList.add("C");
valList.add("E");
dataMap.put("A", valList);
valList = new ArrayList
valList.add("C");
valList.add("D");
dataMap.put("B", valList);
valList = new ArrayList
valList.add("E");
dataMap.put("C", valList);
dataMap.put("D", null);
dataMap.put("E", null);
return dataMap;
}
public static void testcase1() {
Map
DependencyMap depMap = new DependencyMap(dataMap);
depMap.displayDataMap();
depMap.createMap("A", "1");
depMap.displayValueMap();
}
public static void main(String[] args) {
testcase1();
}
}
Output
--------
Element number - 1 - Key = D :: Dependenct List =
Element number - 2 - Key = E :: Dependenct List =
Element number - 3 - Key = A :: Dependenct List = B ; C ; E ;
Element number - 4 - Key = B :: Dependenct List = C ; D ;
Element number - 5 - Key = C :: Dependenct List = E ;
Key = D :: Value = 3
Key = E :: Value = 2
Key = A :: Value = 1
Key = B :: Value = 2
Key = C :: Value = 2
Friday, January 27, 2012
Servlets / JSP Tutorials
Servlets 3.0 / JSP 2.2 tutorials - 1: http://courses.coreservlets.com/Course-Materials/csajsp2.html
Thursday, January 26, 2012
Unicode character APIs in Java
package com.struts1.tutorials.utils;
import java.util.ArrayList;
import java.util.List;
public class UnicodeCheck {
public static int countUnicodeCharacters(char[] charArray) {
if(charArray == null || charArray.length == 0)
return 0;
int numUnicodeChars = 0;
for (int i = 0; i < charArray.length; i++) {
if (Character.isLetter(charArray[i]) && !((charArray[i] >= 'a') && (charArray[i] <= 'z'))
&& !((charArray[i] >= 'A') && (charArray[i] <= 'Z'))) {
numUnicodeChars++;
System.out.println("Unicode character = " + charArray[i]);
}
}
return numUnicodeChars;
}
// This does not work.
public static int countUnicodeCharacters2(char[] charArray){
if(charArray == null || charArray.length == 0)
return 0;
int numUnicodeChars = 0;
System.out.println("********* Start Testing isLetter() API ************");
for (int i = 0; i < charArray.length; i++) {
if (Character.isLetter(charArray[i]) && !Character.isLowerCase(charArray[i]) && !Character.isUpperCase(charArray[i])) {
numUnicodeChars++;
System.out.println("isLetter() API : Character is unicode = " + charArray[i]);
System.out.println("Character = " + charArray[i] +
" :: int value = " + i +
" :: getType = " + Character.getType(charArray[i]));
}
}
System.out.println("********* End Testing isLetter() API ************");
System.out.println("isLetter() API: Count of unicode characters = " + numUnicodeChars);
return numUnicodeChars;
}
public static void testcase1(char[] chArr) {
System.out.println("Begin Testcase1()");
for (char ch : chArr ) {
int i = ch;
System.out.println("Character = " + ch +
" :: int value = " + i +
" :: getType = " + Character.getType(ch));
Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
System.out.println("Unicode block = " + block);
System.out.println("isUnicodeIdentifierPart = " + Character.isUnicodeIdentifierPart(ch));
System.out.println("isUnicodeIdentifierStart = " + Character.isUnicodeIdentifierStart(ch));
}
}
public static void main(String[] args) {
List pwdList = new ArrayList();
pwdList.add("welcome1");
pwdList.add("Enañol");
pwdList.add("wel\u00f1");
pwdList.add("bargain12345");
pwdList.add("....12345");
pwdList.add("change1234");
pwdList.add("cat12345");
for (String pwd : pwdList) {
char[] pwdChars = pwd.toCharArray();
int count = countUnicodeCharacters(pwdChars);
System.out.println("Input password = " + pwd + " :: unicode chars count = " + count);
}
}
}
Output
=====
Input password = welcome1 :: unicode chars count = 0
Unicode character = ñ
Input password = Enañol :: unicode chars count = 1
Unicode character = ñ
Input password = welñ :: unicode chars count = 1
Input password = bargain12345 :: unicode chars count = 0
Input password = ....12345 :: unicode chars count = 0
Input password = change1234 :: unicode chars count = 0
Input password = cat12345 :: unicode chars count = 0
import java.util.ArrayList;
import java.util.List;
public class UnicodeCheck {
public static int countUnicodeCharacters(char[] charArray) {
if(charArray == null || charArray.length == 0)
return 0;
int numUnicodeChars = 0;
for (int i = 0; i < charArray.length; i++) {
if (Character.isLetter(charArray[i]) && !((charArray[i] >= 'a') && (charArray[i] <= 'z'))
&& !((charArray[i] >= 'A') && (charArray[i] <= 'Z'))) {
numUnicodeChars++;
System.out.println("Unicode character = " + charArray[i]);
}
}
return numUnicodeChars;
}
// This does not work.
public static int countUnicodeCharacters2(char[] charArray){
if(charArray == null || charArray.length == 0)
return 0;
int numUnicodeChars = 0;
System.out.println("********* Start Testing isLetter() API ************");
for (int i = 0; i < charArray.length; i++) {
if (Character.isLetter(charArray[i]) && !Character.isLowerCase(charArray[i]) && !Character.isUpperCase(charArray[i])) {
numUnicodeChars++;
System.out.println("isLetter() API : Character is unicode = " + charArray[i]);
System.out.println("Character = " + charArray[i] +
" :: int value = " + i +
" :: getType = " + Character.getType(charArray[i]));
}
}
System.out.println("********* End Testing isLetter() API ************");
System.out.println("isLetter() API: Count of unicode characters = " + numUnicodeChars);
return numUnicodeChars;
}
public static void testcase1(char[] chArr) {
System.out.println("Begin Testcase1()");
for (char ch : chArr ) {
int i = ch;
System.out.println("Character = " + ch +
" :: int value = " + i +
" :: getType = " + Character.getType(ch));
Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
System.out.println("Unicode block = " + block);
System.out.println("isUnicodeIdentifierPart = " + Character.isUnicodeIdentifierPart(ch));
System.out.println("isUnicodeIdentifierStart = " + Character.isUnicodeIdentifierStart(ch));
}
}
public static void main(String[] args) {
List
pwdList.add("welcome1");
pwdList.add("Enañol");
pwdList.add("wel\u00f1");
pwdList.add("bargain12345");
pwdList.add("....12345");
pwdList.add("change1234");
pwdList.add("cat12345");
for (String pwd : pwdList) {
char[] pwdChars = pwd.toCharArray();
int count = countUnicodeCharacters(pwdChars);
System.out.println("Input password = " + pwd + " :: unicode chars count = " + count);
}
}
}
Unicode character = ñ
Input password = Enañol :: unicode chars count = 1
Unicode character = ñ
Input password = welñ :: unicode chars count = 1
Input password = bargain12345 :: unicode chars count = 0
Input password = ....12345 :: unicode chars count = 0
Input password = change1234 :: unicode chars count = 0
Input password = cat12345 :: unicode chars count = 0
Subscribe to:
Posts (Atom)
