Thursday, August 21, 2014

Liferay's Search Container #
Here's a basic example that will help get you started:
<liferay-ui:search-container delta="10" emptyResultsMessage="no-users-were-found">
        <liferay-ui:search-container-results
               results="<%= UserLocalServiceUtil.search(
                       company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getActiveObj(),
                       userParams, searchContainer.getStart(), searchContainer.getEnd(),
                       searchContainer.getOrderByComparator()); %>"
               total="<%= UserLocalServiceUtil.searchCount(
                       company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getActiveObj(),
                       userParams); %>"
        />

        <liferay-ui:search-container-row
               className="com.liferay.portal.model.User"
               keyProperty="userId"
               modelVar="user"
        >
               <liferay-ui:search-container-column-text
                       name="name"
                       value="<%= user.getFullName() %>"
               />

               <liferay-ui:search-container-column-text
                       name="first-name"
                       property="firstName"
               />
        </liferay-ui:search-container-row>

        <liferay-ui:search-iterator />

</liferay-ui:search-container>

<liferay-ui:search-container delta="10" emptyResultsMessage="no-users-were-found">
This is the container. It performs a lot of set up work behind the scenes like instantiating the searchContainer object.
·         delta - The number of results per page
·         emptyResultsMessage - The message shown where there aren't results (it can be a key from your language.properties)
        <liferay-ui:search-container-results
               results="<%= UserLocalServiceUtil.search(
                       company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getActiveObj(),
                       userParams, searchContainer.getStart(), searchContainer.getEnd(),
                       searchContainer.getOrderByComparator()); %>"
               total="<%= UserLocalServiceUtil.searchCount(
                       company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getActiveObj(),
                       userParams); %>"
        />
·         results - This is where you input the results. results should be of type List. The important part is to make sure that your method supports some way to search from a beginning index to an end index in order to provide a good performance pagination. Note how we use searchContainer.getStart() for the first index and searchContainer.getEnd() for the second index. As mentioned above, the searchContainer object is available because it has been instantiated already. Some other methods you can use:
o    searchContainer.getStart() - gets starting index of current results page.
o    searchContainer.getResultsEnd() - gets ending index of current results page or index of last result (i.e. will return 3 if delta is 5 but there are only 3 results).
o    searchContainer.getEnd() - gets last index of current results page regardless of size of actually results (i.e. will return 5 if delta is 5 even if there is only 3 results. Will throw out of bounds errors).
o    searchContainer.getCur() - gets number of current results page.
o    searchContainer.setTotal() - must be set so getResultsEnd() knows when to stop.
·         total - This is where you input the total number of items in your list:
<liferay-ui:search-container-row className="com.liferay.portal.model.User" keyProperty="userId" modelVar="user">
·         className - The type of Object in your List. In this case, we have a List of User objects.
·         keyProperty - Primary Key
·         modelVar - The name of the variable to represent your model. In this case the model is the User object.
<liferay-ui:search-container-column-text name="name" value="<%= user.getFullName() %>" />
·         <liferay-ui:search-container-column-text> - Text column
o    name - Name of the column
o    value - Value of the column
o    href - the text in this coulmn will be a link the this URL
o    orderable - allows the user to order the list of items by this column:
<liferay-ui:search-container-column-text name="first-name" property="firstName" />
·         property - This will automatically look in the User object for the "firstName" property. It's basically the same thing as user.getFirstName().
Important to note here; regardless of attribute capitalisation in your service.XML, the property value must always start lower case. After that it seems to follow what you defined.
<liferay-ui:search-iterator />
·         <liferay-ui:search-iterator /> - This is what actually iterates through and displays the List
Hopefully, this gives you a jump start on how to use Liferay's SearchContainer in your own portlets.

Tuesday, August 12, 2014

Code to attache file in email code and sent to email address:



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 * @author Administrator
 * Class to email notification for advertisement form with attachment of file
 */
public class Email {

public static void main(String[] args) throws IOException {

final String username = "testmail@gmail.com";
final String password = "testpassword";

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

Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

   
 //2) compose message    
 try{
   MimeMessage message = new MimeMessage(session);
   message.setFrom(new InternetAddress(username));
   message.addRecipient(Message.RecipientType.TO,new InternetAddress(username));
   message.setSubject("Message Aleart");
   
   //3) create MimeBodyPart object and set your message text    
   BodyPart messageBodyPart1 = new MimeBodyPart();
   messageBodyPart1.setText("This is message body");
   
   //4) create new MimeBodyPart object and set DataHandler object to this object    
   MimeBodyPart messageBodyPart2 = new MimeBodyPart();

   String filename = "C:\\test_doc.txt";//change accordingly
   DataSource source = new FileDataSource(filename);
   messageBodyPart2.setDataHandler(new DataHandler(source));
   messageBodyPart2.setFileName("a2.text");
   
   
   //5) create Multipart object and add MimeBodyPart objects to this object    
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(messageBodyPart1);
   multipart.addBodyPart(messageBodyPart2);

   //6) set the multiplart object to the message object
   message.setContent(multipart );
   
   //7) send message
   Transport.send(message);
 
  System.out.println("message sent....");
  }catch (MessagingException ex) {
  ex.printStackTrace();
  }
}

public static void sendEmail(String content){
final String username = "testmail@gmail.com";
final String password = "testpassword";

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

Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(username));
message.setSubject("Testing Subject");
message.setText(content);
// message.setContent(message, "charset=utf-8");
Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}


public void sendEmail(HttpServletRequest request) {
final String username = "testmail@gmail.com";
final String password = "testpassword";

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

Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});


        String resultMessage = "";

        try {
        Message msg = new MimeMessage(session);
        if(!ServletFileUpload.isMultipartContent(request)) {
        return;
        }
            msg.setFrom(new InternetAddress(username));
            InternetAddress[] toAddresses = { new InternetAddress(username) };
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
            msg.setSubject("Advertisement application form");
            msg.setSentDate(new Date());
            String contentDetail = "";
            MimeBodyPart messageBodyPart = new MimeBodyPart();
           
            // creates multi-part
            Multipart multipart = new MimeMultipart();
           
            // File upload option to get instance from mime type form data
            ServletFileUpload file = new ServletFileUpload();
            FileItemIterator iter = file.getItemIterator(request);
            while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                    contentDetail += item.getFieldName() + " : "+new Scanner(item.openStream()).nextLine()+"
";

                } else{
                    //Code to attach the file
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
InputStream input = item.openStream();
System.out.println("File name is:" + item.getName());
File tempFile = new File(item.getName());
OutputStream out = new FileOutputStream(tempFile);
out.write(IOUtils.toByteArray(input));
messageBodyPart2.attachFile(tempFile);
messageBodyPart2.setFileName(item.getName());
multipart.addBodyPart(messageBodyPart2);
                }
            }
            messageBodyPart.setContent(contentDetail, "text/html");
            multipart.addBodyPart(messageBodyPart);
            // sets the multi-part as e-mail's content
            msg.setContent(multipart);
            // sends the e-mail
            Transport.send(msg);
           
            resultMessage = "The e-mail was sent successfully";
            request.setAttribute("resultMessage", resultMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage = "There were an error: " + ex.getMessage();
            request.setAttribute("resultMessage", resultMessage);
        }
}
}

Sunday, August 10, 2014

Class to configure email with java mail api

public class SendMail {

final String username = "email@gmail.com";
        final String password = "userpassword";
        final String fromEmail = "email@gmail.com";
        final String subject = "Email text message";
       
        public static void main(String[] args) {

        final String username = "email@gmail.com";
        final String password = "userpassword";

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

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("email1@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("emaial2@yahoo.in"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");
            message.setContent(message, "text/html; charset=utf-8");
           // Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    }