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);
        }
    }
    }
   

Wednesday, June 18, 2014


Java Collection Itereator to avoid ConcurrentModificationException getting while iterating the collection and try to remove the element from the collecation:

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. This situation can come in case of multithreaded as well as single threaded environment.

To Avoid ConcurrentModificationException in multi-threaded environment:

1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

Example:

public void removeRow(){
Iterator it = new CopyOnWriteArrayList(empGroupList).iterator();
while(it.hasNext()) {
EmpGroupData empData = it.next();
if(empData.isSelected()) {
empGroupList.remove(empData);
}
}
for(EmpGroupData empData: empGroupList) {
System.out.println("empno:"+empData.getEmpNo());
}

}

Monday, June 16, 2014

Java Socket Program to Maintain Buffer Queue at server side and provide facilitate to Client

Description: 
To create a Buffere Queue on server side, and client can push the message inside queue, if the queue is full then client will get the message that queue is full.

 Client can receive the inserted message from server and once queue is empty client will get message that queue is empty.

Clint can check the status of the queue, that how much message he inserted in buffer queue.

Server Side Program:


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Administrator
 *
 */
public class BufferQueueServer {

private static int qMaxSize;// max queue size
private static int fp = 0;  // front pointer
private static int rp = 0;  // rear pointer
private static int qs = 0;  // size of queue
private static String[] q;    // actual queue
private static ServerSocket server;

   /**
 * @param size
 * Constructor to initialize the default value of front, rare queue and maximum size of the queue
 */
public BufferQueueServer(int size) {
      qMaxSize = size;
      fp = 0;
      rp = 0;
      qs = 0;
      q = new String[qMaxSize];
      try {
server =new ServerSocket(5050);
} catch (IOException e) {
e.printStackTrace();
}
   }

 

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Waiting for the message from the client....");
BufferQueueServer queue = new BufferQueueServer(4);

while(true) {
try {
//Code to accept the client socket connection
Socket socket = server.accept();
//Create input stream object of server socket
ObjectInputStream FrmClient = new ObjectInputStream(socket.getInputStream());  
//Create output object of client socket
ObjectOutputStream ToClient = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Reading the socket = "+socket);
//Get the input option from client via socket
String str = (String) FrmClient.readObject();
String msg = "";
int option = 0;
//Code to check the option passed by client and if 1 the extract the message which want to add in queue
//else get option directly
if(str.indexOf(",")!=-1) {
String[] msgs=str.split(",");
option = Integer.parseInt(msgs[0]);
msg=msgs[1];
} else {
option = Integer.parseInt(str);
}
System.out.println("Client option is:"+option);
//perform the operation as per the option given by client
switch(option) {
case 1:
System.out.println("Given message is:"+msg);
//Condition to check the queue is full or not, if full then return message else add element in queue
if(!queue.fullq()) {
queue.insert(msg);
ToClient.writeObject("Message added in queue");
} else {
ToClient.writeObject("Queue is full");
}
break;
case 2:
//Condition to check the queue is empty or not, if empty then return message else return the element from queue
if(!queue.emptyq()) {
String recmsg = queue.delete();
ToClient.writeObject("Received msg is:"+recmsg);
} else {
ToClient.writeObject("Queue is empty");
}
break;
case 3:
//Get the queue status and size and return the size of the queue to client
String recmsg = queue.printq();
ToClient.writeObject("Received msg is:"+recmsg);
break;
}
socket.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* @return
* Method to delete the element from the queue and return to first element input by queue
*/
public String delete() {
     if (!emptyq()) {
        qs--;
        fp = (fp)%qMaxSize;
        return q[fp++];
     }
     else {
        System.err.println("Underflow");
        return "?";
     }
  }

/**
* @param c
* Method to insert the element in queue
*/
public void insert(String c) {
     if (!fullq()) {
        qs++;
        rp = (rp)%qMaxSize;
        q[rp] = c;
        rp++;
     }
     else
        System.err.println("Overflow\n");
  }

/**
* @return
* Method to check for empty queue
*/
public boolean emptyq() {
     return qs == 0;
  }

/**
* @return
* Method to check for full queue
*/
public boolean fullq() {
     return qs == qMaxSize;
  }
 
/**
* @return
* Method to print the total number of element inside queue+
*/
public String printq() {
    return "Total size of queue is:"+qs+"\n";
  }

}


Client Side Program

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Administrator
 * Client class to add, retrieve and check the status of the queue from server
 *
 */
public class BufferQueueClient {

public static void main(String[] args) {
try {
String flagCont = "y";
//Flag to check continue message
while("y".equalsIgnoreCase(flagCont)) {              
                int check=1,choice=0;
                //Flag to select the option for the operation
                while(check==1){
                    try{
                    System.out.println("\n\nChoose following option.\n1. For add message\n2. For receive message.\n3. Check Status of queue.\n");
                        Scanner sc=new Scanner(System.in);
                        choice=sc.nextInt();
                        if(choice == 1 || choice == 2 || choice == 3)
                        check=0;
                        else {
                        System.out.println("Please enter correct choice.");
                            check=1;
                        }
                    }
                    catch(Exception e){
                        System.out.println("Please input your choice as a number.");
                        check=1;
                    }
                }
                //Code to open socket connection
                Socket socket = new Socket("localhost", 5050);
                //Create output stream of connected socket
    ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
    //Create input stream of connected socket
                ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream());
                System.out.println("Clent is connected with server");
                String msg = "";
                Scanner sc=new Scanner(System.in);
                /**Switch statement to pass the option to server and get the service
                 * 1. To add the message in server queue
                 * 2. To get the message from queue from server
                 * 3. Check the status of the queue
                 */
               
switch(choice) {
case 1:
System.out.println("Please enter message to add in queue.");
            msg = sc.nextLine();
            toServer.writeObject("1,"+msg);
            msg=(String)fromServer.readObject();
            System.out.println(msg);
break;
case 2:
 toServer.writeObject("2");
 msg=(String)fromServer.readObject();
         System.out.println(msg);
break;
case 3:
 toServer.writeObject("3");
 msg=(String)fromServer.readObject();
         System.out.println(msg);
break;
default:
System.out.println("Invalid choice.Please enter the correct choice");
}
System.out.println("Do you want to continue? Press Y for yes and N for no");
flagCont=sc.nextLine();
                 toServer.close();
                 fromServer.close();
         }


} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


}

Thursday, May 29, 2014

Algorithms and Data Structures link:

http://algs4.cs.princeton.edu/home/

Wednesday, May 28, 2014

Increase the Heap of tomcat Apache server to avoid the Perm Gen Exception:


Tomcat is managed by this script file catalina.bat, dive inside the script, you will find out that catalina.bat always find and run the setenv.bat file to set the environment variables.
{$tomcat-folder}\bin\catalina.bat
//...
rem Get standard environment variables
if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome
call "%CATALINA_BASE%\bin\setenv.bat"
goto setenvDone
:checkSetenvHome
if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"
:setenvDone
//...
2.1 To set the environment variable on Windows, create a setenv.bat manually, and put it into the ${tomcat-folder}\binfolder.
${tomcat-folder}\bin\setenv.bat
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
P.S No double quotes, set JAVA_OPTS={value}.
2.2 Restart Tomcat, it will call the setenv.bat file to set the environment variable automatically.
{$tomcat-folder}\bin\catalina.bat restart

Tuesday, May 27, 2014

Java Code: Copy file from source location to destination location

public static void copyFile(File sourceFile, File destFile) throws IOException {
 if(!destFile.exists()) {
  destFile.createNewFile();
 }
 
 FileChannel source = null;
 FileChannel destination = null;
 try {
  source = new FileInputStream(sourceFile).getChannel();
  destination = new FileOutputStream(destFile).getChannel();
  destination.transferFrom(source, 0, source.size());
 }
 finally {
  if(source != null) {
   source.close();
  }
  if(destination != null) {
   destination.close();
  }
}

Thursday, May 22, 2014

Method to configure the Email in Liferay Server:

1. Login with valid username and password with following URL:

http://localhost:8087/c/portal/login


2. Go to Control Panel

3. Go to Server >> Server Administration 

4. Click on Mail Tab.

5. Fill the required information as mentioned below.



6.  Now the configuration is ready. 
7. User following method to send mail.

public static void sendEmail(String mailBody,String mailSubject) {
String senderMailAddress = "surendra84@gmail.com";
String receiverMailAddress = "surendra84@gmail.com";
try {
MailMessage mailMessage = new MailMessage();
mailMessage.setBody(mailBody);
mailMessage.setSubject(mailSubject);
mailMessage.setFrom(new InternetAddress(senderMailAddress));
mailMessage.setTo(new InternetAddress(receiverMailAddress));
MailServiceUtil.sendEmail(mailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}

8. Now deploy the portlet and cann the defined method inside portlet to send the information.

This part is working fine for me.

Second scenario:

This section shows how to configure the SMTP server with an email address in Apache Tomcat. 
In the file: $LP/conf/Catalina/localhost/ROOT.xml 

}}} 
If you are using a Gmail account you should do the following: 
name="mail/MailSession"
auth="Container"
type="javax.mail.Session"
mail.imap.host="localhost"
mail.pop.host="localhost"
mail.store.protocol="imap"
mail.transport.protocol="smtp"
mail.smtp.host="smtp.gmail.com"
mail.smtp.port="465"
mail.smtp.auth="true"
mail.smtp.starttls.enable="true"
mail.smtp.user="username"
password="*****"
mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"
/>