2019年10月26日 星期六
[JAVA] IBM MQ PUT / GET Example
// need to compile with com.ibm.mq.jar and j2ee.jar
import java.io.*;
import com.ibm.mq.*;
public class MQTest
{
private static String qMngrSrtr = "";
private static String replyQueue = "";
private static String requestQueue = "";
private static String hostName = "";
private static int port = 0;
private static final String channel = "SYSTEM.AITP.SVRCONN";
private static final String FILEPATH = "C:\\Test\\";
MQQueueManager qManager;
public void init(String environment)
{
try
{
qMngrSrtr = "MBKCQ04";
replyQueue = "MFS.MBK.REPL06";
requestQueue = "MBK.MFS.REQS01";
hostName = "10.41.72.69";
port = 1544;
MQEnvironment.hostname = hostName;
MQEnvironment.channel =- channel;
MQEnvironment.port = port;
qManager = new MQQueueManager(qMngrSrtr);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void putAndGetMessage(String path, String filename)
{
try
{
int openOptions2 = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
int openOptions3 = MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING;
MQQueue mqReply = qManager.accessQueue(replyQueue, openOptions3, null, null, null);
MQQueue mqReqest = qManager.accessQueue(requestQueue, openOptions2, null, null, null);
MQMessage putMessage = new MQMessage();
putMessage.format = MQC.MQFMT_STRING;
putMessage.messageFlags = MQC.MQFMT_REQUEST;
putMessage.replyToQueueName = replyQueue;
putMessage.replyToQueueManagerName = qMngrSrtr;
String msg = readFile(path + filename);
putMessage.writeString(msg);
MQPutMessageOptions pmo = new MQPutMessageOptions();
pmo.options += MQC.MQPMO_NEW_MSG_ID | MQC.MQPMO_SYNCPOINT;
mqReqest.put(putMessage, pmo);
qManager.commit();
mqReqest.close();
MQMessage getMessages = new MQMessage();
getMessages.correlationId = putMessage.messageId;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options += MQC.MQGMO_SYNCPOINT | MQC.MQGMO_WAIT;
gmo.maatchOptions = MQC.MQMO_MATCH_CORREL_ID;
gmo.waitInterval = 30000000;
mqReply.get(getMessages, gmo);
int a = getMessages.getDataLength();
String retrivedMsg = formatXmlString(getMessages.readStringOfCharLength(a));
System.out.println(retrivedMsg);
writeFile(path + filename + ".out", retrivedMsg);
mqReply.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
qManager.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static String readFile(String filename)
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "utf-8"));
StringBuffer sb = new StringBuffer();
String tmp = null;
while(true)
{
tmp = br.readLine();
if(tmp == null)
{
break;
}
sb.append(tmp.trim());
}
return sb.toString();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(Exception e)
{
}
}
return "";
}
public static void writeFile(String filename, String msg)
{
BufferedWriter br = null;
try
{
br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
br.write(msg);
br.newLine();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(Exception e)
{
}
}
}
public static String formatXmlString(String s)
{
StringBuffer sb = new StringBuffer();
try
{
char[] arr = s.toCharArray();
boolean quoteOpenFlag = false;
int arrowOpenFlag = -1;
boolean dataFlag = false;
boolean escapeFlag = false;
boolean firstArrowFlag = true;
boolean tagOpenFlag = false;
char prevC = '\0';
for(char c:arr)
{
if(c=='<')
{
if(!quoteOpenFlag)
{
if(prevC=='>')
{
dataFlag = true;
}
}
escapeFlag = false;
}
else
{
if(!quoteOpenFlag && prevC=='<' && c!='/')
{
if(firstArrowFlag)
{
firstArrowFlag = false;
}
else
{
sb.append("\n");
}
for(int i=0;i<arrowOpenFlag;i++)
{
sb.append("\t");
}
sb.append("<");
}
if(c=='>')
{
if(!quoteOpenFlag)
{
}
sb.append(c);
escapeFlag = false;
}
else if(c=='"')
{
if(!escapeFlag)
{
quoteOpenFlag = !quoteOpenFlag;
}
sb.append(c);
escapeFlag = false;
}
else if(c=='/')
{
if(!quoteOpenFlag && prevC=='<')
{
arrowOpenFlag--;
if(tagOpenFlag)
{
tagOpenFlag = false;
sb.append(prevC);
sb.append(c);
if(!dataFlag)
{
sb.append("\n");
for(int i = 0;i<arrowOpenFlag;i++)
{
sb.append("\t");
}
}
}
else
{
sb.append("\n");
for(int i = 0;i<arrowOpenFlag;i++)
{
sb.append("\t");
}
sb.append(prevC);
sb.append(c);
}
dataFlag = false;
}
escapeFlag = false;
}
else if(c=='\\')
{
escapeFlag = true;
sb.append(c);
}
else
{
if(!quoteOpenFlag && prevC=='>')
{
dataFlag = true;
}
if(!quoteOpenFlag && prevC=='<')
{
arrowOpenFlag++;
tagOpenFlag = true;
}
sb.append(c);
escapeFlag = false;
}
}
// end if
prevC = c;
}
return sb.toString();
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
public static void main(String[] args)
{
MQTest test = new MQTest();
test.init();
test.putAndGetMessage(FILEPATH, "in.txt");
}
}
2018年8月9日 星期四
[JAVA] Google Authenticator 2FA Implementation / TOTP
Library / file required:
Put TOTP.java and Test.java together and run.
Good luck.
Apache Commons Codec
https://commons.apache.org/proper/commons-codec/download_codec.cgiDownload TOTP.java
https://tools.ietf.org/html/rfc6238Put TOTP.java and Test.java together and run.
Good luck.
import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; public class Test { public static void main(String[] args) { String seed = "JBSWY3DPEHPK3PXP"; System.out.println(getTOTPCode(seed)); } public static String getTOTPCode(String secretKey) { String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase(); Base32 base32 = new Base32(); byte[] bytes = base32.decode(normalizedBase32Key); String hexKey = Hex.encodeHexString(bytes); long time = (System.currentTimeMillis() / 1000) / 30; String hexTime = Long.toHexString(time); return TOTP.generateTOTP(hexKey, hexTime, "6"); } }
2018年5月11日 星期五
[Java] Using POI Read Excel Files
https://poi.apache.org/download.html
public class ExcelUtil {
private static final String PATH = "C:\\Users\\bonnie\\Desktop\\";
public static void main(String[] args)
{
try
{
run();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void run() throws Exception
{
// if the excel file does not have password, skip the 2nd parameter
Workbook wb = WorkbookFactory.create(
new FileInputStream(PATH + "a - password.xlsx"), "1234");
Sheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
for(int r = 0;r<10;r++)
{
row = sheet.getRow(r);
for(int c = 0;c<3;c++)
{
cell = row.getCell(c);
System.out.print(cell.getStringCellValue()+", ");
}
System.out.println();
}
}
}
public class ExcelUtil {
private static final String PATH = "C:\\Users\\bonnie\\Desktop\\";
public static void main(String[] args)
{
try
{
run();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void run() throws Exception
{
// if the excel file does not have password, skip the 2nd parameter
Workbook wb = WorkbookFactory.create(
new FileInputStream(PATH + "a - password.xlsx"), "1234");
Sheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
for(int r = 0;r<10;r++)
{
row = sheet.getRow(r);
for(int c = 0;c<3;c++)
{
cell = row.getCell(c);
System.out.print(cell.getStringCellValue()+", ");
}
System.out.println();
}
}
}
2017年7月25日 星期二
Java Get Html Source Using SSL
package com;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.URLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsExample
{
public static void main(String[] args)
{
new HttpsExample();
}
public HttpsExample()
{
run();
}
public void run()
{
try
{
// Create a new trust manager that trust all certificates
//*
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Activate the new trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
//*/
URL url = new URL("https://portal.cuhk.edu.hk/psp/epprd/?cmd=login&languageCd=ENG&");
//System.out.println(url.openConnection().getClass());
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( new BufferedInputStream( is ) ) );
String tmp;
while(true)
{
tmp = br.readLine();
if(tmp==null)
{
break;
}
System.out.println(tmp);
}
br.close();
is.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.URLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsExample
{
public static void main(String[] args)
{
new HttpsExample();
}
public HttpsExample()
{
run();
}
public void run()
{
try
{
// Create a new trust manager that trust all certificates
//*
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Activate the new trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
//*/
URL url = new URL("https://portal.cuhk.edu.hk/psp/epprd/?cmd=login&languageCd=ENG&");
//System.out.println(url.openConnection().getClass());
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( new BufferedInputStream( is ) ) );
String tmp;
while(true)
{
tmp = br.readLine();
if(tmp==null)
{
break;
}
System.out.println(tmp);
}
br.close();
is.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
2017年6月29日 星期四
Java LDAP SSL connection example
package com.ldap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapExample {
public static final String JAVA_HOME = "C:\\Program Files\\Java\\jdk1.8.0_131";
public static void main(String[] args)
{
final String ldapAdServer = "host.com:6368";
final String ldapSearchBase = "dc=bam,dc=edu,dc=hk";
final String ldapUsername = "uid=37b7fe15, dc=bam, dc=edu, dc=hk";
final String ldapPassword = "bambam";
final String ldapAccountToLookup = "(|(universityid=ddz044071))";
LdapContext ctx = null;
try
{
Hashtable env = new Hashtable();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
if(ldapUsername != null)
{
env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
}
if(ldapPassword != null)
{
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
}
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
if( "ssl".equals(env.get(Context.SECURITY_PROTOCOL)) )
{
env.put(Context.PROVIDER_URL, "ldaps://"+ldapAdServer);
}
else
{
env.put(Context.PROVIDER_URL, "ldap://"+ldapAdServer);
}
System.out.println("java home: "+System.getProperty("java.home"));
System.setProperty("javax.net.ssl.keyStore", JAVA_HOME+"\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.trustStore", JAVA_HOME+"\\jre\\lib\\security\\cacerts");
//ensures that objectSID attribute values
//will be returned as a byte[] instead of a String
env.put("java.naming.ldap.attributes.binary", "objectSID");
// the following is helpful in debugging errors
//env.put("com.sun.jndi.ldap.trace.ber", System.err);
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setReturningAttributes(
new String[] {
"ds-cfg-listen-port",
"objectclass"
} );
ctx = new InitialLdapContext( env, null );
LdapExample ldap = new LdapExample();
NamingEnumeration list = ldap.findAccount(ctx,
ldapSearchBase, ldapAccountToLookup);
listResult( list );
// modify attributes
ModificationItem[] mods = new ModificationItem[1];
Attribute mod0 = new BasicAttribute("visible", "yes");
//Attribute mod1 = new BasicAttribute("number2", "AAA");
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
//mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, mod1);
ctx.modifyAttributes("uid=304f8d81-5bce11e7-80babd7d-ae3f753a,dc=cuhk,dc=edu,dc=hk", mods);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(ctx!=null)
{
ctx.close();
}
}
catch(Exception e)
{
}
}
System.out.println("LdapExample exit");
}
public NamingEnumeration findAccount(DirContext ctx,
String ldapSearchBase, String searchFilter) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration results = ctx.search(ldapSearchBase, searchFilter, searchControls);
return results;
}
public static void listResult(NamingEnumeration results) throws NamingException
{
int i = 1;
SearchResult searchResult = null;
while(results.hasMoreElements())
{
searchResult = (SearchResult) results.nextElement();
System.out.println("============ record "+i+" ============");
System.out.println( searchResult.getNameInNamespace() );
Attributes attrs = searchResult.getAttributes();
NamingEnumeration enumer = attrs.getAll();
Attribute attrObj;
while( enumer.hasMore() )
{
attrObj = (Attribute)enumer.next();
//System.out.println( "attr: "+attrObj.getClass().getName() );
//System.out.println( "attr: "+attrObj );
System.out.print( "name: "+attrObj.getID()+", " );
System.out.println( "value: "+attrObj.get() );
//System.out.println( "attr: "+(attrObj instanceof javax.naming.directory.Attribute) );
//break;
}
i++;
}
}
}
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapExample {
public static final String JAVA_HOME = "C:\\Program Files\\Java\\jdk1.8.0_131";
public static void main(String[] args)
{
final String ldapAdServer = "host.com:6368";
final String ldapSearchBase = "dc=bam,dc=edu,dc=hk";
final String ldapUsername = "uid=37b7fe15, dc=bam, dc=edu, dc=hk";
final String ldapPassword = "bambam";
final String ldapAccountToLookup = "(|(universityid=ddz044071))";
LdapContext ctx = null;
try
{
Hashtable
env.put(Context.SECURITY_AUTHENTICATION, "simple");
if(ldapUsername != null)
{
env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
}
if(ldapPassword != null)
{
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
}
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
if( "ssl".equals(env.get(Context.SECURITY_PROTOCOL)) )
{
env.put(Context.PROVIDER_URL, "ldaps://"+ldapAdServer);
}
else
{
env.put(Context.PROVIDER_URL, "ldap://"+ldapAdServer);
}
System.out.println("java home: "+System.getProperty("java.home"));
System.setProperty("javax.net.ssl.keyStore", JAVA_HOME+"\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.trustStore", JAVA_HOME+"\\jre\\lib\\security\\cacerts");
//ensures that objectSID attribute values
//will be returned as a byte[] instead of a String
env.put("java.naming.ldap.attributes.binary", "objectSID");
// the following is helpful in debugging errors
//env.put("com.sun.jndi.ldap.trace.ber", System.err);
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setReturningAttributes(
new String[] {
"ds-cfg-listen-port",
"objectclass"
} );
ctx = new InitialLdapContext( env, null );
LdapExample ldap = new LdapExample();
NamingEnumeration
ldapSearchBase, ldapAccountToLookup);
listResult( list );
// modify attributes
ModificationItem[] mods = new ModificationItem[1];
Attribute mod0 = new BasicAttribute("visible", "yes");
//Attribute mod1 = new BasicAttribute("number2", "AAA");
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
//mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, mod1);
ctx.modifyAttributes("uid=304f8d81-5bce11e7-80babd7d-ae3f753a,dc=cuhk,dc=edu,dc=hk", mods);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(ctx!=null)
{
ctx.close();
}
}
catch(Exception e)
{
}
}
System.out.println("LdapExample exit");
}
public NamingEnumeration
String ldapSearchBase, String searchFilter) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration
return results;
}
public static void listResult(NamingEnumeration
{
int i = 1;
SearchResult searchResult = null;
while(results.hasMoreElements())
{
searchResult = (SearchResult) results.nextElement();
System.out.println("============ record "+i+" ============");
System.out.println( searchResult.getNameInNamespace() );
Attributes attrs = searchResult.getAttributes();
NamingEnumeration enumer = attrs.getAll();
Attribute attrObj;
while( enumer.hasMore() )
{
attrObj = (Attribute)enumer.next();
//System.out.println( "attr: "+attrObj.getClass().getName() );
//System.out.println( "attr: "+attrObj );
System.out.print( "name: "+attrObj.getID()+", " );
System.out.println( "value: "+attrObj.get() );
//System.out.println( "attr: "+(attrObj instanceof javax.naming.directory.Attribute) );
//break;
}
i++;
}
}
}
訂閱:
文章 (Atom)