get java.lang.NullPointerException while creating an instance
Hi to all,
Hope you all will be fine.Actually i wrote a code which is about extracting Attachment and create a text file. But the problem is in the very first line of my main class when i try to make an instance it gives me error like
Exception in thread "main" java.lang.NullPointerException
at asteriskproject.AsteriskTextFile.<init>(AsteriskTe xtFile.java:10)
at asteriskproject.Main.main(Main.java:14)
Java Result: 1
Actually i needed to access members of different classes means in my asterisk class i need to access methods of two classes Origmailbox class and CallerId class and in my Origmailbox and CallerID class i needed to access members of Voicemail class and RetreiveAttachment class and voicemail instance was creating in Database class.
So what i did is that in the voicemail class constructor i created an instance of Retreiveattachment class and made a public method that return RetreiveAttachment instance also in the Database class constructor i created an instance of voiemail class and made a public method in the database class that return voicemail instance and the same I did for other classes.
Then i make an instance of Database class in the CallerID class constructor now in this manner i am able to access the members of Database class because i have Database object in my CallerId class, then i simply called the public method of Database class that gives me voicemail object and then i accessed the voiccemail members.Also voicemail class has a public method that return RetreiveAttachment object and i also need it so by using voicemail instance that i just got from database class, I called the public method of voicemail class that gave me a RetreiveAttachment object and now i am able to access both voicemail and RetreiveAttachment because i have both instances in my CallerId class.Then i made two public methods then return both voicemail and Retreiveattachment instances
OrigmailBox class also needs the above two classes instances i.e. voicemail and RetreiveAttachment and these are contained in CallerID class so now i made an instance of CallerID class in the Origmailbox class constructor and then get the instances of voicemail and RetreiveAttachment from the public methods of CallerID class.Also in this class i made a public method that return CallerID instance.
My asterisk file need both CallerId and Origmailbox instances so in my asterisk class constructor i made an instance of OrigmailBox class and then call the Caller ID instance from the public method of Origmal box class and in this manner i have both instances in the asterisk class.
Then what i thought is that if i make an instance of Asterisk class in my main file then first it goes to Asterisk constructor, make a instance of OrigmailBox , then make CallerID then database, voicemail and Retreiveattachment instances.
But at this point i encounter the above exception.
I am unable to fine why this error is coming, this is my first code so please tell me why this error is coming also tell me how you found this code and in which areas i need to concentrate because this is my first code
I am posting the whole code it consist of different classes so it's ease to read i think. Also every class has a code related to it, means in database class only database connection and things regarding database concerning are happening only. Hope may be i got an appreciation from you guys, may be.
Main Class:
Code:
package asteriskproject;
public class Main {
public static void main(String[] args){
//Create an instance of AsteriskTextFile
AsteriskTextFile asteriskTextFile = new AsteriskTextFile();
System.out.println("In main");
//Get OrogMailbox instance so OrigMailbox class access from here and this instance is
//created in AsteriskTextFile so i name it to asteriskMailbox and getting
//the instance through getAsteriskMailbox() method
OrigMailBox origMailbox = asteriskTextFile.getAsteriskMailbox();
//Since CallerID instance is created in OrigMailbox class so i name it to
//mailboxCallerID and get it here through getMailboxCallerID() method
CallerID callerID = origMailbox.getMailboxCallerID();
//Similarly Database instance is created in CallerID class so i name it to
//callerIDDatabase and get it here through getCallerIDDatabase() method
Database database = callerID.getCallerIDDatabase();
//Similarly
Voicemail_conf voicemail_conf = database.getVoicemail_conf();
//Finally
RetreiveAttachment retreiveAttachment = voicemail_conf.getRetAttach();
//Call RetreiveAttachment class method
retreiveAttachment.connectEmailClient();
//Call AsteriskTextFile class method
asteriskTextFile.createFile("C://Temp//msg0000.txt");
}
}
Asterik Class:
Code:
package asteriskproject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class AsteriskTextFile {
private OrigMailBox asteriskMailbox;
//Get CallerId class instance form OrigmailMailbox class by getMailboxCallerID();
//public method
CallerID asteriskCallerID = asteriskMailbox.getMailboxCallerID();
FileWriter msg0000;
BufferedWriter out;
public AsteriskTextFile(){
asteriskMailbox = new OrigMailBox();
System.out.println("In asterisk");
}
public OrigMailBox getAsteriskMailbox(){
return asteriskMailbox;
}
public void createFile(String pathToFile){
try{
msg0000 = new FileWriter(pathToFile);
out = new BufferedWriter(msg0000);
out.write(";");
out.newLine();
out.write("; Message Information File");
out.newLine();
out.write(";");
out.newLine();
out.write("[message]");
out.newLine();
out.write("origmailbox=" + asteriskMailbox.assignMailbox() ); //mailbox the message belongs to
out.newLine();
out.write("context=office" ); //the voicemail context, asterisk config dialplan uses "contexts" as configuration items,
out.newLine();
out.write("macrocontext=" ); //which context was used to answer the call
out.newLine();
out.write("exten=" ); //usually, why the call was transfered to the voicemail
out.newLine();
out.write("priority=3" ); //the priority in the context
out.newLine();
out.write("callerchan=" ); //the incoming channel
out.newLine();
out.write("callerid=" + '"' + asteriskCallerID.splitFullNmae() + '"' + "<" + asteriskCallerID.assignCallerID() +">" ); //who called
out.newLine();
out.write("origdate=" + OrigDate.getDtae() ); //date/time of call
out.newLine();
out.write("origtime=" + OrigTime.getCurrentTime() ); // call timestamp
out.newLine();
out.write("category=" ); // think this is for "categorizing" messages in virtual mailboxes, availble through the vmail.cgi application.
out.newLine();
out.write("duration=" + Duration.duration() ); //how long is the message
out.close();
}catch(IOException e){
e.getMessage();
}
}
}
OrigMailBox class:
Code:
package asteriskproject;
public class OrigMailBox {
private CallerID mailboxCallerID;
//Get Voicemail_conf class instance form CallerID class by getVoice();
//public method
private Voicemail_conf mailboxVoice = mailboxCallerID.getVoice();
//Get retreiveAttachment class instance form callerID class by getCAllerIDRetAttach();
//public method
private RetreiveAttachment mailBoxRetAttach = mailboxCallerID.getCAllerIDRetAttach();
//Constructor
public OrigMailBox(){
mailboxCallerID = new CallerID();
System.out.println("In Mailbox");
}
//Return CallerID instance
public CallerID getMailboxCallerID(){
return mailboxCallerID ;
}
int assignMailbox(){
if(mailboxVoice.getEmail().equalsIgnoreCase(mailBoxRetAttach.getMailTo())){
return mailboxVoice.getMailbox();
}else{
System.out.println("email not exist in NetKarachi database ");
}
return 0;
}
}
CallerID class:
Code:
package asteriskproject;
public class CallerID {
private Database callerIDDatabase;
//Get Voicemail_conf class instance form Database class by getVoicemail_conf();
//public method
private Voicemail_conf voice = callerIDDatabase.getVoicemail_conf();
//Get RetreiveAttachment class instance form CallerID class by getRetAttach();
//public method
private RetreiveAttachment callerIDRetAttach = voice.getRetAttach();
public CallerID(){
callerIDDatabase = new Database();
System.out.println("In CallerID");
}
////Return Voicemail_conf instance
public Voicemail_conf getVoice(){
return voice;
}
//Return RetreiveAttachment instance
public RetreiveAttachment getCAllerIDRetAttach(){
return callerIDRetAttach;
}
public Database getCallerIDDatabase(){
return callerIDDatabase;
}
//Default Access i.e, only classes with in the same package can access to each
//other
String splitFullNmae(){
String[] temp;
temp = voice.getFullname().split(" ");
return temp[0].substring(0, 1).toUpperCase() + temp[0].substring(1).toLowerCase();
}
int assignCallerID(){
if(voice.getEmail().equalsIgnoreCase(callerIDRetAttach.getMailFrom())){
return voice.getMailbox();
}else{
System.out.println("email not exist in NetKarachi database ");
}
return 0;
}
}
Database class:
Code:
package asteriskproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
//Instance variabe
private Voicemail_conf voicemail_conf;
private String emailFromDatabase;
private int mailboxFromDatabase;
private String fullnameFromDatabase;
//constructor
public Database(){
voicemail_conf = new Voicemail_conf(emailFromDatabase, mailboxFromDatabase, fullnameFromDatabase);
this.emailFromDatabase = getEmailFromDatabase();
this.mailboxFromDatabase = getMailboxFromDatabase();
this.fullnameFromDatabase = getFullnameFromDatabase();
System.out.println("In database");
}
public void setEmailFromDatabase(String databaseEmail){
this.emailFromDatabase = databaseEmail;
}
public void setMailboxFromDatabase(int databaseMailBox){
this.mailboxFromDatabase = databaseMailBox;
}
public void setFullnameFromDatabase(String databaseFullNmae ){
this.fullnameFromDatabase = databaseFullNmae;
}
public String getEmailFromDatabase(){
return this.emailFromDatabase;
}
public int getMailboxFromDatabase(){
return this.mailboxFromDatabase;
}
public String getFullnameFromDatabase(){
return this.fullnameFromDatabase;
}
public Voicemail_conf getVoicemail_conf(){
return voicemail_conf;
}
/**
* The ResultSet Interface represent rows returned from a query. It provides
* methods you can use to move from row to row and to get the data for a column
*/
ResultSet emailAndMailbox = emailAndMailboxRows();
/**
* Navigating through the result set
* The ResultSet object returned by the executeQuery statement contains all the
* rows that are retrieved by the select statement. You can only access one of
* those rows at a time. The result set maintains a pointer called a cursor to
* keep track of the current row. You can use the methods shown in Table 4-2 to
* move the cursor through a result set.
* For example, the following snippet shows how you can structure code that
* processes each row in a result set:
while(rows.next())
{
// process the current row
}
*
* All you have to do is replace the comment with statements that retrieve data
* from the result set and process it, as described in the next section.
* Table 4-2 Navigation Methods of the ResultSet Interface
* Method Description
void close() Closes the result set.
void last() Moves the cursor to the last row.
int getRow() Gets the current row number.
boolean next() Moves to the next row.
*
*/
public void navigatingRows(){
try{
while(emailAndMailbox.next()){
Voicemail_conf voicemail = getEmailAndMailbox(emailAndMailbox);
voicemail_conf.showemailAndMailboxes();
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
//Method that returns email and mailbox column from database
private ResultSet emailAndMailboxRows(){
/**
* The Connection class has two methods that you are likely to use .The close()
* method close the connection, and the createStatement() method returns a
* Statement object, which you then use to execute statements.
*/
//Method that returns datebase connection
Connection con = getConnection();
try{
/**
* Statement: The Statement interface contains the methods necessary to
* send statements to the database for execution and return the results.
* In particular, you use the executeQuery method to execute a select
* statement or the executeUpdate method to execute an insert, update,
* or delete statement.
*/
Statement s = con.createStatement();
String select = "SELECT mailbox, email, fullname FROM voicemail_conf ORDER BY" +
" mailbox, email, fullname";
ResultSet rows;
rows = s.executeQuery(select);
return rows;
}catch(SQLException e){
System.out.println(e.getMessage());
}
return null;
} // end of getEmailAndMailbox
private Connection getConnection(){
Connection con = null;
try{
/**
* Before you can use JDBC to access a SQL database, you must first
* establish a connection to the database. The first step to establishing
* a connection involves registering the driver class so the class is
* available. To do that, you use the forName() method of the Class class,
* specifying the package and class name of the driver. For example,
* to register the MySQL connector, use this statement:
Class.forName(“com.mysql.jdbc.Driver”);
*
* To register the standard ODBC driver, use this statement instead:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
* Note that the forName method throws ClassNotFoundException, so you have
* to enclose this statement in a try/catch block that catches
* ClassNotFoundException.
*/
Class.forName("com.mysql.jdbc.Driver");
/**
* After you register the driver class, you can call the static
* getConnection() method of the DriverManager class to open the
* connection. This method takes three String parameters:
* the database URL, the user name, and a password. Here’s an example:
String url = “jdbc:mysql://localhost/Movies”;
String user = “root”;
String pw = “pw”;
con = DriverManager.getConnection(url, user, pw);
*
* The URL parameter has the following syntax:
jdbc:subprotocol:subname
*
* where subprotocol is mysql for a MySQL database and odbc for an ODBC
* driver. The subname is the database name. For a MySQL database,
* this can be a complete URL, but for a database on your own computer,
* you just specify //localhost/ plus the name of the database.
* For ODBC, you use the name you used when you created the data source.
* For example
String url = “jdbc:odbc:Movies”;
*
* The user and password parameters must also be valid for the database
* server you’re using. For testing purposes on a MySQL database, you
* can use root and the password you created when you installed MySQL.
* For ODBC, use admin with no password for testing. Note that the
* getConnection() method throws SQLException, so you need to enclose it
* in a try/catch block statement that catches this exception.
*/
String url = "jdbc:mysql://xx.xxx.xx.xx/asterisk";
String user = "your user name";
String pw = "your password";
con = DriverManager.getConnection(url, user, pw);
}catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}catch(SQLException e){
System.out.println(e.getMessage());
}
return con;
} // end of getConnection()
private Voicemail_conf getEmailAndMailbox(ResultSet emailAndMailbox){
try{
String email = emailAndMailbox.getString("email");
setEmailFromDatabase(email);
int mailbox = emailAndMailbox.getInt("mailbox");
setMailboxFromDatabase(mailbox);
String fullname = emailAndMailbox.getString("fullname");
setFullnameFromDatabase(fullname);
return new Voicemail_conf(email, mailbox, fullname);
//return new Database(email, mailbox, fullname);
}catch(SQLException e){
System.out.println(e.getMessage());
}
return null;
}
} // end of class
Voicemail Class:
Code:
package asteriskproject;
public class Voicemail_conf {
private RetreiveAttachment retAttach;
private String email;
private int mailbox;
private String fullname;
public Voicemail_conf(String email, int mailbox, String fullname){
retAttach = new RetreiveAttachment("pop.gmail.com", "gmail username", "your gmail account password");
this.email = email;
this.mailbox = mailbox;
this.fullname = fullname;
System.out.println("In Voicemail");
}
public String getEmail(){
return email;
}
public int getMailbox(){
return mailbox;
}
public String getFullname(){
return fullname;
}
public RetreiveAttachment getRetAttach(){
return retAttach;
}
protected void showemailAndMailboxes(){
String msg = Integer.toString(getMailbox());
msg += ": " + getEmail();
msg += ": " + getFullname();
System.out.println(msg);
}
}
RetreiveAttachment Class:
Code:
package asteriskproject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
public class RetreiveAttachment {
private String host;
private String username;
private String password;
private String mailFrom;
private String mailTo;
private Date sentDate;
public RetreiveAttachment(String host, String username, String password){
this.host = host;
this.username = username;
this.password = password;
System.out.println("In RetAttach");
}
public void setSentDate(Date sentdate){
this.sentDate = sentdate;
}
public void setMailFrom(String mailfrom){
this.mailFrom = mailfrom;
}
public void setMailTo(String mailto){
this.mailTo = mailto;
}
public String getHost(){
return host;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public String getMailFrom(){
return mailFrom;
}
public String getMailTo(){
return mailTo;
}
public Date getSentDate(){
return sentDate;
}
public void connectEmailClient() {
//Scanner scanner = new Scanner(System.in);
//Create empty properties
Properties props = new Properties();
//props.put("mail.smtp.port", port);
//Get Session
Session session = Session.getDefaultInstance(props, null);
try{
//Get the store
Store store = session.getStore("pop3s");
System.out.println("Trying to connect host");
store.connect(getHost(), getUsername(), getPassword());
System.out.println("Connection Successful");
//Get Folder
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_ONLY);
//Get directory
Message[] message = folder.getMessages();
for(int i=0, n=message.length; i<n; i++){
setMailFrom(InternetAddress.toString(message[i].getFrom()));
setMailTo(InternetAddress.toString(message[i].getRecipients(Message.RecipientType.TO)));
setSentDate(message[i].getSentDate());
System.out.println("From: " + getMailFrom());
System.out.println("To: " + getMailTo());
System.out.println("SendDate: " + getSentDate());
// System.out.println("Hi i am here");
//System.out.println("Do you want to read message? [YES to read/QUIT" +
//" to end]");
//String line = scanner.next();
// if("YES".equalsIgnoreCase(line)){
// System.out.println(i + ": " + message[i].getFrom()[0] + "\t" +
//message[i].getSubject() + "\t" +
// message[i].getRecipients(Message.RecipientType.TO)[0] +
//"getAllrecipent method start" + message[i].getAllRecipients()[0]);
/**
* Forwarding messages is a little more involved. There is no single
* method to call and you build up the message to forward by
* working with the parts that make up a message.
* A mail message can be made up of multiple parts. Each part is
* a BodyPart, or more specifically, a MimeBodyPart when working
* with MIME messages. The different body parts get combined
* into a container called Multipart or, again, more specifically
* a MimeMultipart. To forward a message, you create one part for
* the text of your message and a second part with the message
* to forward, and combine the two into a multipart. Then you
* add the multipart to a properly addressed message and send it.
* That's essentially it. To copy the content from one message to
* another, just copy over its DataHandler, a class from the
* JavaBeans Activation Framework.
*
* // Create the message to forward
Message forward = new MimeMessage(session);
// Fill in header
forward.setSubject("Fwd: " + message.getSubject());
forward.setFrom(new InternetAddress(from));
forward.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here you go with the original +
message:\n\n");
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message.getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
// Send message
Transport.send(forward);
*
*
* Working with Attachments:
* Attachments are resources associated with a mail message,
* usually kept outside of the message like a text file,
* spreadsheet, or image. As with common mail programs like
* Eudora and pine, you can attach resources to your mail message
* with the JavaMail API and get those attachments when you
* receive the message
*
* Sending Attachments:
* Sending attachments is quite like forwarding messages. You
* build up the parts to make the complete message. After the
* first part, your message text, you add other parts where the
* DataHandler for each is your attachment, instead of the shared
* handler in the case of a forwarded message. If you are reading
* the attachment from a file, your attachment data source is a
* FileataSource.
* Reading from a URL, it is a URLDataSource. Once you have your
* DataSource, just pass it on to the DataHandler constructor,
* before finally attaching it to the BodyPart with setDataHandler()
* Assuming you want to retain the original filename for the
* attachment, the last thing to do is to set the filename
* associated with the attachment with the setFileName() method
* of BodyPart.
*
* // Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, +
new InternetAddress(to));
message.setSubject("Hello JavaMail Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Pardon Ideas");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
*
*
* Getting Attachments:
* Getting attachments out of your messages is a little more
* involved then sending them, as MIME has no simple notion of
* attachments. The content of your message is a Multipart object
* when it has attachments. You then need to process each
* Part, to get the main content and the attachment(s). Parts
* marked with a disposition of Part.ATTACHMENT from
* part.getDisposition() are clearly attachments. However,
* attachments can also come across with no disposition
* (and a non-text MIME type) or a disposition of Part.INLINE.
* When the disposition is either Part.ATTACHMENT or Part.INLINE,
* you can save * off the content for that message part. Just get
* the original filename with getFileName() and the input stream
* with getInputStream().
*/
Object content = message[i].getContent();
if(content instanceof Multipart){
handleMultipart((Multipart)content);
}else{
handlePart(message[i]);
}
//}else if("QUIT".equalsIgnoreCase(line)){
// break;
//}
folder.close(false);
store.close();
}
}catch(Exception e){
e.printStackTrace();
}
} //Main
public static void handleMultipart(Multipart multipart)throws MessagingException, IOException{
for(int i=0, n=multipart.getCount(); i<n; i++){
handlePart(multipart.getBodyPart(i));
}
}
public static void handlePart(Part part)throws MessagingException, IOException{
String disposition = part.getDisposition();
String contentType = part.getContentType();
if(disposition == null){
System.out.println("Null: " + contentType);
if((contentType.length() >= 10) && (contentType.toLowerCase().substring(0, 10).equals("text/plain"))){
part.writeTo(System.out);
}else{
System.out.println("OtherBody: " + contentType);
part.writeTo(System.out);
}
} else if(disposition.equalsIgnoreCase(Part.ATTACHMENT)){
System.out.println("Attachment in the mail is: " + part.getFileName() +
": " + contentType );
saveFile(part.getFileName(), part.getInputStream());
} else if(disposition.equalsIgnoreCase(Part.INLINE)){
System.out.println("Inline: " + part.getFileName() + " : " + contentType);
//saveFile(part.getFileName(), part.getInputStream());
} else{
System.out.println("Other: " + disposition);
}
}
public static void saveFile(String fileName, InputStream input)throws IOException{
// if(fileName != null){
// System.out.println("filename is: " + fileName);
//File dir = new File("C://Temp");
//fileName = File.createTempFile("msg0000", ".wav", dir).getName();
//System.out.println("Created temporary file with name: " + fileName );
//Define path for the file
//String fileNamePath = "C://" + fileName;
//String fileNamePath = fileName;
//System.out.println("Created temporary file with name: " + fileNamePath );
//Create new file
File file = new File("C://Temp/msg0000.wav");
//for(int i=0; file.exists(); i++){
//file = new File(fileNamePath );
//}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//Copy the contents of the attachment to the newly created file
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while((aByte = bis.read()) != -1){
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
}
}
Other classes is not necessary but i post here
Duratin class:
Code:
package asteriskproject;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Duration {
//default access i.e., only classes with in same package can access it
static long duration(){
String path = "C://Temp/msg0000.wav";
try{
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File(path));
clip.open(ais);
/**
* Conversion in seconds. Since
* 1 microsecond = 10^(-6) sec
* 1 microsecond = 1/1000000 sec
*/
return((clip.getMicrosecondLength()/1000000) );
}catch(Exception e){
e.getMessage();
}
return 5;
}
}
CallerChan class:
Code:
package asteriskproject;
public class CallerChan {
private static final String ALPHA_NUM ="0123456789abcdef";
public static String getAlphaNumeric(int len) {
StringBuffer sb = new StringBuffer(len);
for (int i=0; i<len; i++) {
int ndx = (int)(Math.random()*ALPHA_NUM.length());
sb.append(ALPHA_NUM.charAt(ndx));
}
return sb.toString();
}
/**
* Another method
String alphaNumerics = "qwertyuiopasdfghjklzxcvbnm1234567890";
String t = "";
for (int i = 0; i < 8; i++) {
t += alphaNumerics.charAt((int) (Math.random() * alphaNumerics.length()));
}
System.out.println("with new code: " + t);
*/
}
OrigTime class:
Code:
package asteriskproject;
import java.sql.Timestamp;
import java.util.Date;
public class OrigTime {
//Method that returns a TimeStamp object
public static Timestamp getCurrentTime(){
//Instiate a Date object and calls the getTime() method, and creates and returns
//the Timestamp object with the current time. In one line
return new Timestamp(new Date().getTime());
//Step by step
/**
*Step 1. Instiate a Date object
* Date d = new date();
*
* Step 2. Call the getTIme() method on that object and assign it to a Timestamp
* reference.
* Timestamp ts = (d.getTime());
*
* Step 3. Return the time as a Timestamp
* return ts;
*
* Instead you can create an object and call one of its methods in one step
* return new Timestamp(new Date().getTIme());
*
*/
}
}
Finally OrigDate class:
Code:
package asteriskproject;
import java.text.SimpleDateFormat;
import java.util.Date;
public class OrigDate {
public static String getDtae(){
String pattern = "EEE MMM dd hh:mm:ss a z yyyy ";
SimpleDateFormat format = new SimpleDateFormat(pattern);
return(format.format(new Date()));
}
}
Please help :(
Thank you