Update Log4j Appender at runtime

Categories: Java; Tagged with: ; @ April 17th, 2013 18:20
import java.io.IOException;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

/**
 * Test for adding appender to log4j at runtime.
 * @author SGSCLGLD
 *
 */
public class LogingTest {
	
	static Logger log = Logger.getLogger(LogingTest.class);
	
	public static void main(String[] args) throws IOException {
		// setting up a FileAppender at runtime.
		PatternLayout patternLayout = new PatternLayout();
		patternLayout.setConversionPattern("[%d{d/M/yyyy HH:mm:ss}] %p [%t] %c{1}.%M(%L) | %m%n");
		FileAppender appender = new FileAppender(patternLayout,"D:\\ME\\WS_Share\\test1\\log.txt",false);    
		log.addAppender(appender);
		
		log.info("Hello world...");
	}
}

Java RSA Key Generation/Encryption/Decryption RSA秘钥生成/加密/解密

Categories: Java; Tagged with: ; @ April 3rd, 2013 0:17

Requirement:

Generate RSA key pair using Java,  and test encryption/decryption.

Source code:

package com.rsa;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

public class RSATest {

	/**
	 * Generate key pair and encrypt/decrypt message.
	 * @param args
	 * @throws Throwable
	 */
	public static void main(String[] args) throws Throwable {

		String str = "liguoliang.com";
		
		// init private/public key
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(512);
		KeyPair keyPair = keyGen.generateKeyPair();
		PrivateKey privateKey = keyPair.getPrivate();
		PublicKey publicKey = keyPair.getPublic();

		System.out.println("privateKey: " + privateKey);
		System.out.println("PublicKey: " + publicKey);

		System.out.println("Original message: [" + str + "]");
		
		// init cipher
		Cipher cipher;
		cipher = Cipher.getInstance("RSA");
		
		// Encrypt
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] encryptedMsg = cipher.doFinal(str.getBytes());
		System.out.println("Encrypted message: [" + new String(encryptedMsg) + "]");

		// Decrypt
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] decryptedMsg = cipher.doFinal(encryptedMsg);
		System.out.println("Decrypted message: [" + new String(decryptedMsg) + "]");
	}
}

Output:

privateKey: Sun RSA private CRT key, 512 bits
  modulus:          6722431852833652083740039
  public exponent:  65537
  private exponent: 171186757391917267536..695551529001
  prime p:          9879891158983359366387147661330…7700131643
  prime q:          680415577930859..89085598145526159671701009583973
  prime exponent p: 320741816528876..9797652301875289
  prime exponent q: 1025757344699..140192255455019921532401
  crt coefficient:  60972956628933..8290909983925983303
PublicKey: Sun RSA public key, 512 bits
  modulus: 672243185283365208374001..
  public exponent: 65537
Original message: [liguoliang.com]
Encrypted message: ['ËŸò¬Œ÷Já°`ð«6L´aZ0Ž¶¹mçZaÐvCóG%P    ƒtÂÌÖ9ØùýY,vÎ`¦Y»ù    h]
Decrypted message: [liguoliang.com]

Reference

RSA Encryption in Java – http://tspycher.com/2012/10/rsa-encryption-in-java/

用实例给新手讲解RSA加密算法 – http://bank.hexun.com/2009-06-24/118958531.html

http://introcs.cs.princeton.edu/java/78crypto/RSA.java.html

Java Socket Example

Categories: Java; Tagged with: ; @ April 2nd, 2013 0:43

Requirement:  Client send message to Server, Server get the message and return to Client.

Codes:

MesgServer:

package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.common.LogHelper;

/**
 * ServerSide: receive message from Client and return it. 
 * @author Guoliang
 *
 */
public class MesgServer implements Runnable{
	
	public void run() {
		LogHelper.log("ServerStarted");
		try {
			ServerSocket serverSocket = new ServerSocket(8888);
		
			while (true) {
				
					Socket socket = serverSocket.accept();
					LogHelper.log("Request: " + socket.toString());
					
					BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					PrintWriter out = new PrintWriter(socket.getOutputStream());
					
					out.println("Connected!");
					out.flush();
					
					String lineInput;
					while ((lineInput = in.readLine()) != null) {
						LogHelper.log("GotMesgFromClient: " + lineInput);
						out.println("ServerReturnMsg: " + lineInput);
						out.flush();
						if("exit".equals(lineInput)) {
							break;
						}
					}
					
					out.close();
					in.close();
					socket.close();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

MesgClient

package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.common.LogHelper;

public class MesgClient {

	/**
	 * Send mesg to server side.
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		// Start server. 
		new Thread(new MesgServer()).start();
		
		Socket socket = new Socket("localhost", 8888);
		LogHelper.log("Connecting...");
		
		PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        
        LogHelper.log(in.readLine());
        
        // Simplest testing
        out.println("Hello!"); 
        LogHelper.log(in.readLine());
        
        // Read user input.
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String strInput = null;
        while ((strInput = stdIn.readLine()) != null) {
        	out.println(strInput);
        	LogHelper.log("Send: " + strInput);
        	LogHelper.log(in.readLine());
		}
	}
}

Output:

[Thread-0]ServerStarted
[main]Connecting...
[Thread-0]Request: Socket[addr=/127.0.0.1,port=5569,localport=8888]
[main]Connected!
[Thread-0]GotMesgFromClient: Hello!
[main]ServerReturnMsg: Hello!
liguoliang.com  // user input.
[Thread-0]GotMesgFromClient: liguoliang.com
[main]Send: liguoliang.com
[main]ServerReturnMsg: liguoliang.com

Axis2: IWAB0489E Error when deploying Web service to Axis runtime

Categories: Java; Tagged with: ; @ February 27th, 2013 19:28

I try to get started with Axis2, but when I try to create Web Service in Eclipse, I got the following Error:

IWAB0489E Error when deploying Web service to Axis runtime

After googling, I got the solution:

Make sure the config of web service Server and Runtime is correct:

image

正则表达式:根据逗号解析CSV并忽略引号内的逗号 splitting a comma-separated string but ignoring commas in quotes

Categories: Java; Tagged with: ; @ January 30th, 2013 16:04

需求:解析CSV文件并忽略引号内的逗号

解决方案:

public static void main(String[] args) {
	String s = "a,b,c,\"1,000\"";
	String[] result = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
	for (String str : result) {
		System.out.println(str);
	}
}

输出:
a
b
c
“1,000”

Newer Posts <-> Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.