Wednesday, April 25, 2012

How to generate a random alphanumeric word with special characters of variable length

Usually we need to create a random word of some 8+ character to use as a password or an encryption key.
I have recently created this one, though very simple but very effective.
I have tried to replicate the same sequence and run in a loop of 1000000 iteration but with length of 8 characters there were no repetition. Hope the readers would like it.

package in.codeZila.www.utility;

public class RandomWordGenerator {

 public static final String getRandomWord(int length) {
  String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*";
  String rw = "";
  for(int i = 0; i < length; i++) {
   int index = (int) Math.floor(Math.random() * 62);
   rw += chars.charAt(index);
  }

  return rw;
 }
 
 public static void main(String[] args) {
  for(int i=0;i<100;i++){
   String randomPwd=getRandomWord(8);
   System.out.println(randomPwd);
  }
 }
 
}


The Random words generated are :

Please feel free to ask any doubts or clarifications.

Saturday, April 14, 2012

How to get the XML String for a DTO (Data transfer object) using XStream

To get the XML for a DTO XStream (com.thoughtworks.xstream.XStream) is used, Download the "xstream-1.4.2.jar" jar : Click Here and add into your lib folder.

The Method which returns the XML for the passed DTO:
public static String getDTOasXML(Object dto){
 XStream xstream = new XStream();
        return xstream.toXML(dto);
}


The UserDto which needs to be converted to XML :

public class UserDto{

 
 private Long userId;

 private String userName;

 private String userEmail;

 public Long getUserId() {
  return userId;
 }

 public void setUserId(Long userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getUserEmail() {
  return userEmail;
 }

 public void setUserEmail(String userEmail) {
  this.userEmail = userEmail;
 } 
}

Note: Notice that the fields are private. XStream doesn't care about the visibility of the fields. No getters or setters are needed. Also, XStream does not limit you to having a default constructor.

The Test Class to implement the XStream.toXML() method :

package in.codeZila.test;

import in.codeZila.test.dto.UserDto;
import com.thoughtworks.xstream.XStream;


public class Test{
 
 /**
  * Using XStream method toXML():String to generate the XML for the passed DTO object
  * @param dto
  * @return dto XML as String
  */
 public static String getDTOasXML(Object dto){
  XStream xstream = new XStream();
  /**
   * Now, to make the XML outputted by XStream more concise, 
   * you can create aliases for your custom class names to XML 
   * element names. This is the only type of mapping required to 
   * use XStream and even this is optional.
   * 
   * Note: This is an optional step. Without it XStream would work fine, 
   * but the XML element names would contain the fully qualified name of 
   * each class (including package) which would bulk up the XML a bit.
   */
  xstream.alias("UserDto", UserDto.class);
  return xstream.toXML(dto);
 }
 
 public static void main(String[] args) {
  /**
   * Instantiate the UserDto and set its variables
   */
  UserDto userDto=new UserDto();
  userDto.setUserId(new Long(1));
  userDto.setUserName("CodeZila");
  userDto.setUserEmail("codezila@codezila.in");
  /**
   * Pass the userDto Object created above as getDTOasXML() argument
   */
  String dtoXml=Test.getDTOasXML(userDto);
  System.out.println(dtoXml);
 }
}



The Output XML :

Thats all, how simple XStream is!

Summary:

  • Create element name to class name aliases for any custom classes using xstream.alias(String elementName, Class cls); 
  • Convert an object to XML using xstream.toXML(Object obj); 
  • Convert XML back to an object using xstream.fromXML(String xml);


Your valuable inputs and suggestions are welcomed!