Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Monday, December 20, 2010

Memory Management #1

Dominator Object:
What is Dominator Object? In what circumstances does this thing
happen?. Remember I'm a programmer and I do code. But how the heck
this thing happen? Easy there folks. Lets go through this from the
very bottom of it.
As usual, we start with our lovely but deadly controller. It control our code.
While at logic level, we have our service class. It does the logic and
control data parsing inside the logics. At data level, we have our
models. We may also have the ORM as part of our model. View? Included.
Jsp for view, enough.
But hey, enough with the chat. Now, let's see, when did Dominator
objects happened and what is the effect of having Dominator object.
Not so long time ago, I declare of ORM inside my MainModel (assuming
that MainModel is the model that I used as model in our case). My
program runs. The logical output was true, and the page went well.
(I'll attach picture later, I do post from mobile you know? :) )
Dao/VO declared in model. Easy to call but remain in memory untill full GC is performed.

what's wrong with above method? While development and testing, my
bosses found out Memory Issue. Sometime, small Instance that hold
approximate 10 to 20 application will easily do full GC in every hour
basis. It shows serious memory problem. When I declare another class
in a class (Dominator Objects?), though I've nulled the value when not
in use, sometime, they do stay in memory and cleared once Full GC
done.
How to overcome this kind of problem? If the problem started because
of stacked class inside other class, one quick simple solution was to
clear that stacked class. Just carry the value youu need and leave
behind everything as history. This way, I believe GC will happen
faster. Well, theoritically I guess LOL. (Again, I will attach the
picture soon).

Dao/VO called in service only when program call specific function.

So now we see, how Dominator Object effect the application memory and
how to overcome this problem. Any question? As usual, you are welcome
to raise question + comments in comment section. Your feedback will
much appreciated. (maybe I'll edit this post with further reading).


Further reading:

http://www.eclipse.org/mat/about/screenshots.php
http://www.slideshare.net/guest62fd60c/eclipse-memory-analyzer-presentation

PS: next post: How to programatically done this?

Friday, April 30, 2010

JAVA: Send email from JAVA? Can OR Not?

* Warning: Technical Entry


Salam and good day,

We meet again in another Technical topic. This time it's about JAVA Mail. In this tutorial, we'll use javamail api. Cut the crap now and get ready.


Pre-requisites:
Step-by-step guide:
0. Import the required library onto your project folder. (Use of IDE also can ma: Right click, import libraries, yada yada yada, you know the drill)

1. Create your function that send mail from your service more-or-less like this.
      //Declare this on class header  
   private static final String SMTP_AUTH_USER = "someemailaccount";
   private static final String SMTP_AUTH_PWD = "someemailpassword";
   
   public void postMail(String[] recipients, String subject, String message, 
                         String from, String portalUserName, 
                         String feedbackType) throws MessagingException {
        logger.info("Inside postMail");
        boolean debug = false;

        //Set the host smtp address
        Properties props = new 
        props.put("mail.smtp.host", "email.test.gov.
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        // create some properties and get the default Session
        Session session = Session.getInstance(props, auth);
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);


        // Optional : You can also set your custom headers in the Email if you want
        //msg.addHeader("Feedback Type: " + feedbackType, 
                     // "\nAs reported by " + portalUserName + ".");
        String header = 
            "Portal KPT telah menerima maklumbalas seperti berikut:\n\n";
        String namaPengadu = "Nama: " + portalUserName;
        String emailPengadu = "\nEmel: " + from;
        String kategoriAduan = "\nKategori: " + feedbackType;
        String keterangan = "\nKeterangan: \n\n" + message;
        String footer = 
            "\n\n---\nIni adalah emel janaan automatik. Sebarang kemusykilan teknikal tentang maklumbalas ini boleh emel ke test@test.test.my.";
        message = 
                header + namaPengadu + emailPengadu + kategoriAduan + keterangan + 
                footer;
        //message = message;
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
        logger.info("Leaving postMail");
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }


2. Create String recipientAddress[] in your model. Not to forget getter and setter.
    String recipientAddress();


3. Call the function from your controller.
                   feedbackModel.setRecipientAddress({ "receiverEmail@testServer.gov.my" }); 
          feedbackService.postMail(feedbackModel.getRecipientAddress(), 
                                         "Portal Feedback: "+feedbackModel.getPortalUserName()+"- "+feedbackModel.getFeedbackType(), 
                                         feedbackModel.getFeedbackMessage(), 
                                         feedbackModel.getPortalUserEmail(), 
                                         feedbackModel.getPortalUserName(),
                                         feedbackModel.getFeedbackType());
4. Compile and test send an email.

5. Check your email. make sure that the email is sent.

6. Tada!! my work is done!

As usual. Any comment are highly appreciated?