Generates Random Integers in a Specific Range

Generates Random Integers in a Specific Range

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
 
  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");
   
    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
   
    log("Done.");
  }
 
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if (aStart > aEnd) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);  
    log("Generated : " + randomNumber);
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}


An example run of this class:
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Generates Random Floating Point Numbers

Generates Random Floating Point Numbers

import java.util.Random;

/**
 Generate pseudo-random floating point values, with an
 approximately Gaussian (normal) distribution.

 Many physical measurements have an approximately Gaussian
 distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {

  public static void main(String... aArgs){
    RandomGaussian gaussian = new RandomGaussian();
    double MEAN = 100.0f;
    double VARIANCE = 5.0f;
    for (int idx = 1; idx <= 10; ++idx){
      log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
    }
  }
 
  private Random fRandom = new Random();

  private double getGaussian(double aMean, double aVariance){
    return aMean + fRandom.nextGaussian() * aVariance;
  }

  private static void log(Object aMsg){
    System.out.println(String.valueOf(aMsg));
  }
}


An example run of this class:
Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141
Generate random numbers

Generate random numbers

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
 
  public static final void main(String... aArgs){
    log("Generating 10 random integers in range 0..99.");
   
    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGenerator.nextInt(100);
      log("Generated : " + randomInt);
    }
   
    log("Done.");
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}

Example run of this class:
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.
Sending Email through Gmail Server Using JavaServlets

Sending Email through Gmail Server Using JavaServlets

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendEmail extends HttpServlet {

 protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        //final String succ = "/success.jsp";

        String from = "abc@gmail.com"    // Sender Email-Id
        String to = "xyz@gmail.com"     // Receiver Email-Id

System.out.println("mail : "+to);
        String subject = "Subject";          //Your Subject.
        String message = "Message"    Your Message

        String login = "abc@gmail.com";        //Sender Mail_Id
        String password = "xyx"; //Sender Mail Password

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props,auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;
        } catch (MessagingException ex) {
           request.setAttribute("ErrorMessage", ex.getMessage());
       
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
            return;
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp?email="+to);
            dispatcher.forward(request, response);
            return;
    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doPost(HttpServletRequest request,
                         HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

 
}

Java Date and Time

Java Date and Time

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SimpleDateFormatExample {
public static void main(String[] args) {

Date curDate = new Date();

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

String DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
DateToStr = format.format(curDate);
System.out.println(DateToStr);

format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
DateToStr = format.format(curDate);
System.out.println(DateToStr);

try {
Date strToDate = format.parse(DateToStr);
System.out.println(strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:

2014/12/19
19-12-2014 04:54:26
19 December 2014 India Standard Time
Fri, 19 Dec 2014 16:54:26 IST
Fri Dec 19 16:54:26 IST 2014