Friday, November 26, 2010

Random number generator

 private static int RandomNumberGenerator(int aStart, int aEnd, Random aRandom){  
      if ( aStart > aEnd ) {  
       throw new IllegalArgumentException("Start cannot exceed End.");  
      }  
      long range = (long)aEnd - (long)aStart + 1;  
      long fraction = (long)(range * aRandom.nextDouble());  
      int randomNumber = (int)(fraction + aStart);    
      return randomNumber;  
 }  

Pop-ups

 function post_to_url(path, params, method) {  
      method = method || "post"; // Set method to post by default, if not specified.  
      //Here we are creating a form tag and adding attributes to it   
      var form = document.createElement("form");  
      form.setAttribute("method", method);  
      form.setAttribute("action", path);  
      form.setAttribute("target", "NameofthePopup");   
      //Creating input tag and adding attributes to it  
      for(var key in params) {  
           var hiddenField = document.createElement("input");  
           hiddenField.setAttribute("type", "hidden");  
           hiddenField.setAttribute("name", key);  
           hiddenField.setAttribute("value", params[key]);  
           //adding input tags to from tag.  
           form.appendChild(hiddenField);  
      }  
      document.body.appendChild(form);  // Not entirely sure if this is necessary  
      window.open('URL',"NameofthePopup","width=670,height=680,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no");  
      form.submit();// submitting the form  
 }  

  • In the above function we are using the Post method to send the parameters.
  • params should be in follwoing formate(inside the flower brackets):{Arg1:'Arg1Value',Arg2:'Arg2Value'} 

Sending an Email

 java.util.Properties props = new java.util.Properties();  
 props.put("mail.smtp.host", "here you have to give the smtp host address");  
 props.put("mail.smtp.port", "smtp port number, it may or may not required");  
 Session session = Session.getDefaultInstance(props, null);  
 // Construct the message  
 try {  
      Message msg = new MimeMessage(session);  
      String emailfrom=request.getParameter("emailfrom");  
      String emailto=request.getParameter("emailto");  
      String comment="Hi there";  
      msg.setContent(comment,"text/html");  
      msg.setFrom(new InternetAddress(request.getParameter("emailfrom")));  
      msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(request.getParameter("emailto")));  
      msg.setSubject("Enter the subject here");  
      msg.setSentDate(new Date());  
      // Sends the message  
      Transport.send(msg);  
      response.getWriter().print("success");  
 } catch (AddressException e) {  
      // TODO Auto-generated catch block  
      response.getWriter().print("failed");  
      e.printStackTrace();  
 } catch (MessagingException e) {  
      // TODO Auto-generated catch block  
      response.getWriter().print("failed");  
      e.printStackTrace();  
 }  

Sunday, November 21, 2010

SAX Example

 Sample s=new Sample();  
 SAXParserFactory factory = SAXParserFactory.newInstance();  
 SAXParser saxParser = factory.newSAXParser();  
 saxParser.parse("Have to give some class object(consider as Sample.java)", inputStream);  
 inputStream.close();  

 public class Sample extends DefaultHandler{  
      public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException   
      {  
           // This function invokes when parser reads the starting tag  
           // qName is element name  
           // below command gets the value of the Attribute "name"  
          attributes.getValue("name");    
      }  
      public void endElement(String uri, String localName, String qName) throws SAXException {  
           // This function is invoked when the parser reads the ending tag  
      }  
      public void characters(char[] chars, int start, int length) throws SAXException {  
           // Used to read the cdata  
          String s=new String(chars, start,length); // to read CDATA     
      }  
           //Put this line in any of the above method to voluntary exit the
           //parsing  "throw new DoneParsingException();"
 }  

How to use Proxy in java

 Proxy proxy =null;  
 URL url;  
 String decodedXml=null;  
 DataInputStream inStream=null;  
 proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyAddress, ProxyPort));  
 // Above line creates proxy with given address and port
 url = new URL(getUrl);  // you need to give your url here
 URLConnection conn = url.openConnection(proxy);// it creates a connection using proxy
 String flag;  
 inStream = new DataInputStream(conn.getInputStream());  

Wednesday, November 3, 2010

Char to ascii in javascript

 function ascii_value (c)  
 {  
      // restrict input to a single character  
      c = c . charAt (0);  
      // loop through all possible ASCII values  
      var i;  
      for (i = 0; i < 256; ++ i)  
      {  
           // convert i into a 2-digit hex string  
           var h = i . toString (16);  
           if (h . length == 1)  
                h = "0" + h;  
           // insert a % character into the string  
           h = "%" + h;  
           // determine the character represented by the escape code  
           h = unescape (h);  
           // if the characters match, we've found the ASCII value  
           if (h == c)  
                break;  
      }  
      return i;  
 }  

References:
 Rose, Charlton. "converting between characters and ASCII values." http://sharkysoft.com. 3 Jan 1997. Web. 2 Nov 2010. <http://sharkysoft.com/tutorials/jsa/content/018.html>.  

Reading cookies from browser in jsp

 <c:forEach items='${cookie}' var='mapEntry'> // reading cookies from any browser  
   <c:if test='${mapEntry.key eq "AllCookies"}'>  // reading from a map  
     <c:set var="str1" value="${mapEntry.value.value}"/>   
       <c:forEach var="num" items="${fn:split(str1, ',')}"> // spliting a cookie value  
         <c:out value='${num}'/>  
     </c:forEach>   
   </c:if>  
 </c:forEach>